pro fit2stardb3,filin
; This routine reads the fits file filin, containing positions and magnitudes
; for SDSS DR1 subfields.  Stars that are bright enough and that have low
; errors are tagged as good.  Data for these stars is entered into the 'stars'
; database $ZDBASE/survey/stars/tstds.  If this database does not exist 
; (no .dbh file)
; then it is created, using the $ZDBASE/stars2.dbd file for a template.
; This version of the routine deals with Mark's 2nd-generation data files

; read the input data, convert ra from decimal degrees to decimal hours
rd_sdss_q,filin,nst,rad,dec,u,g,r,i,z,eu,eg,er,ei,ez,/swap
ra=rad/15.

; find stars satisfying quality and brightness criterea
s=where(r ge 14.5 and r le 16.5 and eu le .03 and eg le .03 and er le .03 $
         and ei le .03 and ez le .03,ns)
if(ns gt 0) then begin
  ra=ra(s)
  rad=rad(s)
  dec=dec(s)
  u=u(s)
  eu=eu(s)
  g=g(s)
  eg=eg(s)
  r=r(s)
  er=er(s)
  i=i(s)
  ei=ei(s)
  z=z(s)
  ez=ez(s)
  nst=ns
endif else begin
  print,'No valid stars!  File=',filin
  goto,fini
endelse

; check to see if database file exists.  If not, create it.
zdbase=getenv('ZDBASE')
filout=zdbase+'/survey/stars/tstds'
ier=findfile(zdbase+'/survey/stars/tstds.dbh')
berr=byte(ier)
if(berr(0) eq 0) then begin
  comm='cp '+zdbase+'/stars3.dbd '+filout+'.dbd'
  spawn,comm
  astrolib
  !priv=2
  dbcreate,filout,1,1,/external,/silent
endif

; make star names, JD values, default arrays
mk_starid,ra,dec,names
names=string(names)
jd=dblarr(nst)+julday(1,1,2000,0.,0.,0.)     ; set JD = Jan 1, 2000
dd=fltarr(nst)+99.9
dz=fltarr(nst)
ii=intarr(nst)
il=lonarr(nst)
ii7=intarr(7,nst)
src=ii+2

; open database, insert new data
dbopen,filout,1
dbbuild,names,ra,dec,dz,dz,u,eu,g,eg,r,er,i,ei,z,ez,dd,dd,dd,dd,dd,dd,dd,il,$
    ii,ii,jd,src,ii7,/silent

; sort on ra,dec, put all the data back in sorted order
dbopen,filout
so=dbsort(-1,'ra,dec')
dbext,so,'ra,dec,dra,ddec,u,sig_u,g,sig_g,r,sig_r',v1,v2,v3,v4,v5,v6,v7,v8,$
             v9,v10
dbext,so,'i,sig_i,z,sig_z,D51,sig_D51,Gred,sig_Gred,J,H',w1,w2,w3,$
             w4,w5,w6,w7,w8,w9,w10
dbext,so,'K,ID2mass,starid,var,crwd,jd,source,badflag',x0,n0,n1,x1,x2,x3,x4,x5

dbopen,filout,1
dbupdate,-1,'starid',n1
dbupdate,-1,'ra,dec,dra,ddec,u,sig_u,g,sig_g,r,sig_r',v1,v2,v3,v4,v5,v6,v7,v8,$
             v9,v10
dbupdate,-1,'i,sig_i,z,sig_z,D51,sig_D51,Gred,sig_Gred,J,H',w1,w2,w3,$
             w4,w5,w6,w7,w8,w9,w10
dbupdate,-1,'K,ID2mass,var,crwd,jd,source,badflag',x0,n0,x1,x2,x3,x4,x5
dbindex

dbclose

fini:

end