pro tostd_segment,ifilt,nday=nday,zdb=zdb,n11=n11,n19=n19
; This routine reads the tostds database for filter ifilt (integer 0 to 6),
; and segments it into multiple databases with names like tostdsnnn,
; where nnn counts the number of nday-long segments following
; JD = 2453000.  These are written into the same directory as the original
; database file.
; nday defaults to 15, but can be specified with the nday keyword.
; If keyword n11 is set, the functions described are performed for the
; observations tile to294+046, which contains the NGC6811 standard field.
; If keyword n19 is set, the same is done for tile to295+040, containing
; NGC6819.

; constants
jd0=2453000.2d00        ; add 0.2 because obs sometimes slop into next JD
nday=15L 
filtdir=['u','g','r','i','z','gr','d5']
zdbase=getenv('ZDBASE')
if(keyword_set(zdb)) then zdbase=zdb
path=zdbase+'/survey/'
imdbase=path+'images/images'
astrolib
!priv=2

; read the database contents
dbpath=path+'observations/'+filtdir(ifilt)+'/tostds'
if(keyword_set(n11)) then dbpath=path+'observations/'+filtdir(ifilt)+'/to294+046'
if(keyword_set(n19)) then dbpath=path+'observations/'+filtdir(ifilt)+'/to295+040'
dbopen,dbpath
dbext,-1,'starid,ra,dec,iseq,filter,mag,err,x,chip',$
          starid,ra,dec,iseq,filter,mag,err,x,chip
dbext,-1,'xcen,ycen,sky,sharp,chi,dra,ddec',$
          xcen,ycen,sky,sharp,chi,dra,ddec
dbclose

; read the images dbase, tag each observation with a jd
dbopen,imdbase
dbext,-1,'entry,jd',entry,jd
dbclose
jdobs=jd(iseq-1)

; make segment number for output databases
iseg=long(jdobs-jd0)/nday
miniseg=min(iseg)
maxiseg=max(iseg)

;stop

; now loop over possible segments
for i=miniseg,maxiseg do begin
  s=where(iseg eq i,ns)
  if(ns gt 0) then begin

; select desired data
  starido=starid(s)
  rao=ra(s)
  deco=dec(s)
  iseqo=iseq(s)
  filtero=filter(s)
  mago=mag(s)
  erro=err(s)
  xo=x(s)
  chipo=chip(s)
  xceno=xcen(s)
  yceno=ycen(s)
  skyo=sky(s)
  sharpo=sharp(s)
  chio=chi(s)
  drao=dra(s)
  ddeco=ddec(s)

; make the name of the output database
  si=strtrim(string(i),2)
  nb=n_elements(byte(si))
  if(nb eq 1) then si='00'+si
  if(nb eq 2) then si='0'+si
  dboname=dbpath+si 
  
; write the new database
  comm='cp '+zdbase+'/observ.dbd '+dboname+'.dbd'
  spawn,comm
  dbcreate,dboname,1,1,/silent

; put in the new data
  dbopen,dboname,1
  dbbuild,starido,rao,deco,iseqo,filtero,mago,erro,xo,chipo,$
          xceno,yceno,skyo,sharpo,chio,drao,ddeco,/silent
  dbclose

  print,dboname,'   n_elements = ',ns

  endif
endfor

end