pro 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
; This routine enters new observations taken with the given filter into
; the 'observations' databases.  It is assumed that the 'stars' databases
; have already been updated, ie, that most of the input parameters to this
; routine have been returned from obs2stardb.pro.
; On input,
;  iseq = image sequence number, ref to images DB
;  jd = scaler R*8 Julian date
;  ra = RA in decimal hours vector R*8
;  dec = Dec in decimal degrees vector R*8
;  mag = magnitudes in color 'filter', vector R*4
;  err = error on mag, vector R*4
;  x = airmass, vector R*4
;  chip = 4-shooter chip, vector I*2
;  xcen,ycen = x,y posn on chip vector R*4
;  sky = sky value for star in ADU, vector R*4
;  sharp = daophot sharp parameter
;  chi = daophot goodness-of-fit parameter
;  dra,ddec = difference between this measurement of posn and stars DB
;              position, in decimal hours or degrees, resp. vector R*4
;  hits = vector I*2, =2 if star is in stds DB, =0,1 if in targets DB
;  stdnames = string array, containing names of std DB tiles
;  targnames = string array, containing tiles in which targets live
;  unid = vector I*4, contains last indices in data arrays corresp to
;           each tile
;  ibot = vector I*4, like unid, but contains first indices 
;  starid = string array with unique ID names for each star

; ****NOTE****
; For testing purposes, iseq, filter, and jd are all independent input
; parms.  In real use, they should be retrieved from the 'images' DB,
; perhaps by the routine that calls this one
; *********************
; If keyword zdb is set, its value overrides environment var ZDBASE
; If keyword noseg is set, std star data go into a single tostds database.
; Otherwise (ie, by default), they go into time-segmented databases with
; names like tostds107, or more generally tostdsnnn, where nnn counts the
; number of 15-day segments since JD 2453000.2

; constants for determining standard field names
jd0=2453000.2d00
nday=15L

; make path names, etc.

filts=strtrim(filter,2)
case filts of
  'u': begin
      filt='u'
      fna='u        '
      end
  'g': begin
      filt='g'
      fna='g        '
      end
  'r': begin
      filt='r'
      fna='r        '
      end
  'i': begin
      filt='i'
      fna='i        '
      end
  'z': begin
      filt='z'
      fna='z        '
      end
  'Gred': begin
      filt='gr'
      fna='Gred     '
      end
  'D51': begin
      filt='d5'
      fna='D51      '
      end
else: begin
  print,'Illegal filter name ',filter
  goto,fini
  end
endcase
zdbase=getenv('ZDBASE')
if(keyword_set(zdb)) then zdbase=zdb
path=zdbase+'/survey/observations/'+filt+'/'
;astrolib
!priv=2
ntile=n_elements(unid)
nst=n_elements(ra)
iis=lonarr(nst)+iseq
filtname=strarr(nst)
for i=0,nst-1 do begin
  filtname(i)=fna
endfor

;obs2stardb,jd,ra,dec,mag,err,x,chip,xcen,ycen,sky,dra,ddec
; index over tiles
for i=0,ntile-1 do begin

; If there are standard stars for this tile, identify them from hits table
  ib=ibot(i)
  it=unid(i)
  if(ib ge 0 and it ge 0) then begin
  s=where(hits(ib:it) eq 2,ns)
  if(ns gt 0) then begin
    s=s+ib                           ; offset s to corresp to this tile

; make name of needed database file.
; ******** now modified to access segmented standard field databases ********
    slen=strlen(stdnames(i))
    stdname='to'+strmid(stdnames(i),1,slen-1)
    if(keyword_set(noseg)) then begin
      dbname=path+stdname
    endif else begin
      iseg=long(jd-jd0)/nday
      siseg=strtrim(string(iseg),2)
      nbiseg=n_elements(byte(siseg))
      if(nbiseg eq 1) then siseg='00'+siseg
      if(nbiseg eq 2) then siseg='0'+siseg
      dbname=path+stdname+siseg
    endelse

; create the file if it doesn't already exist
    ierr=findfile(dbname+'.dbh')
    berr=byte(ierr)
    if(berr(0) eq 0) then begin
      comm='cp '+zdbase+'/observ.dbd '+dbname+'.dbd'
      spawn,comm
      dbcreate,dbname,1,1,/silent
    endif

; add data to observations DB file
    dbopen,dbname,1
    dbbuild,starid(s),ra(s),dec(s),iis(s),filtname(s),mag(s),err(s),x(s),$
        chip(s),xcen(s),ycen(s),sky(s),sharp(s),chi(s),dra(s),ddec(s),/silent

; sort results back into correct order
    dbopen,dbname
    so=dbsort(-1,'ra,dec')
    dbext,so,'starid,ra,dec,iseq,filter,mag,err,x,chip',v1,v2,v3,v4,v5,v6,$
              v7,v8,v9
    dbext,so,'xcen,ycen,sky,sharp,chi,dra,ddec',w1,w2,w3,w4,w5,w6,w7
    dbopen,dbname,1
    dbupdate,-1,'starid,ra,dec,iseq,filter,mag,err,x,chip',v1,v2,v3,v4,v5,v6,$
              v7,v8,v9, /silent
    
    dbupdate,-1,'xcen,ycen,sky,sharp,chi,dra,ddec',w1,w2,w3,w4,w5,w6,w7,/silent

    dbindex

  endif

; Now repeat for target stars in this tile
; identify them from hits table
  s=where(hits(ib:it) lt 2,ns)
  if(ns gt 0) then begin
    s=s+ib

; make name of needed database file
    slen=strlen(targnames(i))
    stdname='to'+strmid(targnames(i),1,slen-1)
    if(keyword_set(noseg) or (stdname ne 'to294+046' and $
                              stdname ne 'to295+040')) then  begin
      dbname=path+stdname
    endif else begin
      iseg=long(jd-jd0)/nday
      siseg=strtrim(string(iseg),2)
      nbiseg=n_elements(byte(siseg))
      if(nbiseg eq 1) then siseg='00'+siseg
      if(nbiseg eq 2) then siseg='0'+siseg
      dbname=path+stdname+siseg
    endelse

; create file if needed
    ierr=findfile(dbname+'.dbh')
    berr=byte(ierr)
    if(berr(0) eq 0) then begin
      comm='cp '+zdbase+'/observ.dbd '+dbname+'.dbd'
      spawn,comm
      dbcreate,dbname,1,1,/silent
    endif

; add data to DB file
    dbopen,dbname,1
    dbbuild,starid(s),ra(s),dec(s),iis(s),filtname(s),mag(s),err(s),x(s),$
        chip(s),xcen(s),ycen(s),sky(s),sharp(s),chi(s),dra(s),ddec(s),/silent

; sort entries in modified DB file
    dbopen,dbname
    so=dbsort(-1,'ra,dec')
    dbext,so,'starid,ra,dec,iseq,filter,mag,err,x,chip',v1,v2,v3,v4,v5,v6,$
              v7,v8,v9
    dbext,so,'xcen,ycen,sky,sharp,chi,dra,ddec',w1,w2,w3,w4,w5,w6,w7
    dbopen,dbname,1
    dbupdate,-1,'starid,ra,dec,iseq,filter,mag,err,x,chip',v1,v2,v3,v4,v5,v6,$
              v7,v8,v9, /silent
 
    dbupdate,-1,'xcen,ycen,sky,sharp,chi,dra,ddec',w1,w2,w3,w4,w5,w6,w7,/silent

    dbindex

  endif
  endif

; next tile
endfor

fini:
end