PRO rebuild_obsdb, tilename, manual=manual

; This procedure is used when the max number of entries defined in an obs db 
; has been, or is close to being, exceeded.  

;Instructions:
;
; If max entries has been exceeded (testing procedures for preventing this 
;   are in development, but failure is always possible): 
;   Run obstilecounts.pro to find tile that is overrun (note it); remove all
;   contents of the dbase/survey directory (rm -r survey) then restore the
;   most recent tar file (survey#.tar in dbase directory); run this procedure
;   with the overrun tilename as the argument.
;
; If max entries has not yet been exceeded, run this procedure with the 
;   tilename indicated in a warning from run_obs2db2.pro (or from 
;   obstilecounts.pro) as the argument.
;
; NOTE: tilename will be in the format 'fullpath/tile', the same format output
;   by obstilecounts.pro (i.e. /daisy/i/kolinski/.../g/to292+036)
;
; If keyword manual is set, then
; The procedure will prompt for a new maximum number of entries for that tile.
; Otherwise, it will add 150000 to the max obs count.

!priv = 2  

; Open tile db and extract all current data
dbopen, tilename
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, tilename

; Read in .dbd file, look for max entries, prompt user for new value
OpenR, iun, tilename+'.dbd', /Get_LUN
OpenW, oun, 'temp.dbd', /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, maxentold
q:
    Print, 'Current value of maxentries: '+strtrim(string(maxentold), 2)

    if(keyword_set(manual)) then begin
      Read, maxentnew, PROMPT='Enter desired value of maxentries: '
      IF (maxentnew LE maxentold) THEN BEGIN
        Print, 'New value should be larger than old value!'
        goto, q
      ENDIF
    endif else begin

      maxentnew = maxentold+150000L
    endelse
    print, 'New value of maxentries: '+strtrim(string(maxentnew), 2)
    Print, string(7b)  ;ring bell
    PrintF, oun, strtrim(string(maxentnew),2)
  ENDIF
ENDWHILE
Close, iun & Free_lun, iun
Close, oun & Free_lun, oun

SPAWN, 'mv temp.dbd '+tilename+'.dbd'

; Remove old db files
SPAWN, 'rm '+tilename+'.dbf '+tilename+'.dbx '+tilename+'.dbh'

; Create new db files and fill them
dbcreate, tilename, 1, 1, /silent
dbopen, tilename, 1
dbbuild, starid,ra,dec,iseq,filter,mag,err,x,chip,xcen,ycen,sky,sharp,chi,dra,ddec, /silent
dbclose, tilename

END