pro tostds_deseg,ifilt,rootile,over=over,zdb=zdb
; this routine rejoins the time-segmented obs data files created from
; the tile rootile for filter number ifilt.  
; It reads them in one at a time, merges them,
; and writes them out to a file called 'temp_' + rootile.
; If keyword over is set, this name is replaced with rootile itself,
; so the old huge obs directory (if any) is itself overwritten.

; constants
zdbase=getenv('ZDBASE')
if(keyword_set(zdb)) then zdbase=zdb
cd,zdbase+'/survey/observations'
astrolib
!priv=2
filtdir=['u','g','r','i','z','gr','d5']

; get list of database files to concatenate
cd,zdbase+'/survey/observations/'+filtdir(ifilt)
cmd='ls '+rootile+'???.dbd'
spawn,cmd,dbnames
nfile=n_elements(dbnames)
for i=0,nfile-1 do begin
  nc=strpos(dbnames(i),'.dbd')
  dbnames(i)=strmid(dbnames(i),0,nc)
endfor

; make output file name
if(keyword_set(over)) then bigtile=rootile else bigtile='temp_'+rootile

; read the data, build the data arrays
for i=0,nfile-1 do begin
  dbopen,dbnames(i)
  dbext,-1,'starid,ra,dec,iseq,filter,mag,err,x,chip',v1,v2,v3,v4,v5,v6,$
              v7,v8,v9
  dbext,-1,'xcen,ycen,sky,sharp,chi,dra,ddec',w1,w2,w3,w4,w5,w6,w7
  if(i eq 0) then begin
    starid=v1
    ra=v2
    dec=v3
    iseq=v4
    filter=v5
    mag=v6
    err=v7
    x=v8
    chip=v9
    xcen=w1
    ycen=w2
    sky=w3
    sharp=w4
    chi=w5
    dra=w6
    ddec=w7
  endif else begin
    starid=[starid,v1]
    ra=[ra,v2]
    dec=[dec,v3]
    iseq=[iseq,v4]
    filter=[filter,v5]
    mag=[mag,v6]
    err=[err,v7]
    x=[x,v8]
    chip=[chip,v9]
    xcen=[xcen,w1]
    ycen=[ycen,w2]
    sky=[sky,w3]
    sharp=[sharp,w4]
    chi=[chi,w5]
    dra=[dra,w6]
    ddec=[ddec,w7]
  endelse
endfor

; adjust the output .dbd file size to be big enough
npt=n_elements(ra)

; Read in .dbd file, look for max entries, prompt user for new value
dbdname=zdbase+'/observ.dbd'
bigtiledbd=bigtile+'.dbd'
OpenR, iun, dbdname, /Get_LUN
OpenW, oun, bigtiledbd, /Get_LUN
ss=''
maxentold=0L
maxentnew=0L
WHILE (NOT EOF(iun)) DO BEGIN
  ReadF, iun, ss
  PrintF, oun, ss
  IF (STRMID(ss, 0, 4) EQ '#max') THEN BEGIN
    readf,iun,ss
    maxentnew = long(1.1*npt)
    PrintF, oun, strtrim(string(maxentnew),2)
  ENDIF
ENDWHILE
Close, iun & Free_lun, iun
Close, oun & Free_lun, oun

; write out the big database file
dbcreate,bigtile,1,1,/silent
dbopen,bigtile,1
dbbuild, starid,ra,dec,iseq,filter,mag,err,x,chip,xcen,ycen,sky,$
    sharp,chi,dra,ddec, /silent
dbclose,bigtile

; sort it into ra, dec order
dbopen,bigtile
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,bigtile,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
dbclose

end