pro obs2db4,obsfile,over=over,zdb=zdb,noseg=noseg
; This routine reads obsfile, which contains photometry and necessary
; header information for a single 4-shooter image.  This version takes
; as input Mark's 2nd-generation data files.  It then
;  Creates a new entry in the 'images' DB, provided that an entry with
;    the same JD (within +/- 5s) does not exist.
;    If keyword 'over' is set, then data from obsfile overwrite existing
;    'images' DB data, regardless of possible time collision.
;  Adds entries as necessary to the 'stars' standards and targets DBs,
;    and identifies existing entries.
;  Adds entries to the 'observations' standards and targets DBs, reflecting
;    the new data.
; New DB files are created in subdirectories of ZDBASE/survey as needed
; to provide for the new input data.
; A log file ZDBASE/survey/obs2db.log is updated on each invocation of
; obs2db, giving summaries of number of chips used, number of stars
; input and output, and number of stars matched to reference stars.
; If zdb keyword is set, its value overrides environment var ZDBASE
; If keyword noseg is set, std stars data go into one large database,
; and observations from tile 294+046 go into to294+046.
; Otherwise, they go to time-segmented databases with names like tostds123,
; to294+046123.

; constants
dt=.00006             ; time matching cutoff, in days (~= 5s)
rad2deg=57.295
widmin=.15
widmax=.25            ; min & max plausible coord spread for 1 chip, in deg
zdbase=getenv('ZDBASE')
if(keyword_set(zdb)) then zdbase=zdb
path=zdbase+'/survey/'
imdbase=path+'images/images'
logfile=path+'obs2db.log'
f1='(f13.5)'
;astrolib  ;called in run_obs2db2.pro
!priv=2

; read the data file
;rd_obs,obsfile,filter,jd,exptime,rac,decc,xmid,obj,focus,tccd,ra,dec,mag,$
;        err,x,chip,xcen,ycen,sky

;rd_obs,obsfile,filter,jd,exptime,rac,decc,xmid,obj,focus,fwhm,bias,gain,$
;        ra,dec,mag,err,x,chip,xcen,ycen,sky,sharp,chi

rd_obs2,obsfile,imid,filter,jd,exptime,rac,decc,xmid,obj,focus,fwhm,bias,$
        gain,apercor,ra,dec,mag,err,x,chip,xcen,ycen,sky,sharp,chi,ra2m,dec2m,$
        idno2m,j2m,h2m,k2m
nst0=n_elements(ra)
nst2m=n_elements(ra2m)
; set various bad data flags to zero, set camera flag
cldf=fix(0)
astf=fix(0)
fitf=fix(0)
camf=icamera(jd)

; open the log file, write in input filename
openw,iul,logfile,/get_lun,/append
printf,iul,'Processing '+obsfile+'   Filter = '+filter+'exptime = ',fix(exptime)
printf,iul,'JD= ',jd,format='(1a4,f13.5)'
printf,iul,'No of input, 2mass stars =        ',nst0,nst2m

if(nst0 le 0 or nst2m le 0) then goto,fini

; check to see if images DB exists.  If not, create it, put data in.
ierr=findfile(imdbase+'.dbh')
berr=byte(ierr)
if(berr(0) eq 0) then begin
  comm='cp '+zdbase+'/images4.dbd '+imdbase+'.dbd'
  spawn,comm
  dbcreate,imdbase,1,1,/silent
  dbopen,imdbase,1
  dbbuild,imid,jd,filter,rac,decc,exptime,xmid,obj,focus,fwhm,bias,gain,$
    apercor,cldf,astf,fitf,camf,/silent
  iseq=1
  goto,contin
endif

; check to see that no other image was taken at the same time
dbopen,imdbase
jdmin=string(jd-dt,format=f1)
jdmax=string(jd+dt,format=f1)
sstr=jdmin+' < JD < '+jdmax
ll=dbfind(sstr, /silent)
if(ll(0) le 0 or keyword_set(over)) then begin

; put new data into the images DB.  2 cases: entry doesn't yet exist,
; or entry exists and must be overwritten.
  if(ll(0) le 0) then begin      ; entry doesn't exist
    dbopen,imdbase,1
    dbbuild,imid,jd,filter,rac,decc,exptime,xmid,obj,focus,fwhm,bias,gain,$
            apercor,cldf,astf,fitf,camf, /silent
    dbopen,imdbase
    lnew=dbfind('jd = '+string(jd,format=f1), /silent)
    dbext,lnew,'entry',iseq & iseq=iseq(0)
  endif else begin    ; entry exists, so must be overwritten
    dbopen,imdbase,1
    dbupdate,ll(0),'imid,jd,filter,ra,dec,exptime,xmid,obj,focus,fwhm,bias,',$
               imid,jd,filter,rac,decc,exptime,xmid,obj,focus,fwhm,bias,/silent
    dbupdate,ll(0),'gain,apercor,cldflg,astflg,fitflg,camera',$
               gain,apercor,cldf,astf,fitf,camf,/silent
    iseq=ll(0)
  endelse

  contin:

; remove from input all stars on chips that have bad coord spread --
; this indicates failure of world coord conversion.
  ierr=rmbaddat(ra,dec,mag,err,x,chip,xcen,ycen,sky,sharp,chi,camf,$
               nbch,nbp,nbst)
  printf,iul,'Bad chips, chi/shrp, all bad = ',nbch,nbp,nbst
  printf,iul,'Good stars =               ',n_elements(ra)
  if(ierr ne 0) then begin  ;print some stuff to help keep place in obs2db.log
    printf,iul,'Ref, targ, new stars = ',0,0,0
    printf,iul,'ndiag, version = ',8,2
    diags=fltarr(8)
    printf,iul,diags
    printf,iul
    goto,fini
  endif
; put data into the stars db, get back a bunch of useful derived quantities
  obs2stardb3,jd,ra,dec,mag,err,x,chip,xcen,ycen,sky,sharp,chi,$
     ra2m,dec2m,idno2m,j2m,h2m,k2m,dra,ddec,$
     hits,stdnames,targnames,unid,ibot,starid,zdb=zdb
  sref=where(hits eq 2,nsref)
  strg=where(hits eq 1,nstrg)
  smis=where(hits eq 0,nsmis)
  printf,iul,'Ref, targ, new stars =     ',nsref,nstrg,nsmis
  obsdiagnos,jd,filter,exptime,mag,sky,sharp,chi,dra,ddec,ra,dec,ra2m,dec2m,$
    j2m,k2m,x,diags,diagnames,ver,zdb=zdb
  ndiag=n_elements(diags)
  printf,iul,'ndiag, version =',ndiag,ver
  printf,iul,diags
  printf,iul
;stop

; put data into the observations db
  obs2obsdb,iseq,filter,jd,ra,dec,mag,err,x,chip,xcen,ycen,sky,sharp,chi,$
     dra,ddec,hits,stdnames,targnames,unid,ibot,starid,zdb=zdb,noseg=noseg

;stop

endif else begin
  print,'Image already exists in DB.  JD-2450000 = ',jd-2450000.
endelse

fini:
close,iul
free_lun,iul

end