pro ssw_gev_locator, time0, time1, refresh=refresh,  $
   _extra=_extra, www=www, fdtype=fdtype, subdir=subdir, $
   archive=archive, debug=debug
;
;+
;   Name: ssw_gev_locator
;
;   Purpose: for each GEV entry, use specified full disk set to locate flares
;
;   Input Paramters:
;      time0 - start time
;      time1 - optional stop time
; 
;   Keyword Parameters:
;      www - if set, produce some WWW output
;      fdtype - full disk set to use ('eit','sxin','sxt'...) - def=EIT195
;      _extra - unspecified keywords passed to 'ssw_flare_locator.pro;
;      refresh - if set AND www, then regenerate location and www files even if they exist
;
;   History:
;      26-Feb-2002 - S.L.Freeland
;      18-Mar-2003 - S.L.Freeland - Hooks for SXI as backup
;      20-Mar-2003 - S.L.Freeland - use SXI-CS (def=FL) for "small" flares
;       4-Apr-3003 - S.L.Freeland - use SXI over EIT for "short" duration flares
;      11-Apr-2003 - S.L.Freeland - made differencing default for sxi also
;      24-apr-2006 - S.L.Freeland - default to not relocate if curr if 
;                                   location alread exists and same FD files 
;                                   (use refresh to override)
;
;-
archive=keyword_set(archive)
debug=keyword_set(debug)
refresh = keyword_set(refresh) ; force relocation even if same FD files implied

newdata=1-archive
curgev=get_gevloc_data()

if not data_chk(fdtype,/string) then fdtype='eit'
www=keyword_set(www)
topwww=get_logenv('path_http')

les_parent=get_logenv('ssw_latest_events_parent')
case 1 of 
   n_elements(subdir) eq 0: subdir=concat_dir(topwww,'latest_events')
   strpos(subdir,'/') ne -1: 
   else: subdir=concat_dir(topwww,subdir)
endcase 
ecat=concat_dir(subdir,'ssw_gev_locate.geny')
if not file_exist(subdir) then begin 
   box_message,'Output path: ' + subdir + ' does not exist, creating it now'
   spawn,['mkdir','-p',subdir],/noshell
endif
case n_params() of
   0: begin
        time0=reltime(days=-2,/day_only)
        time1=reltime(/now)
   endcase
   1: time1=reltime(/now)
   else:
endcase

gev_loc_template= $
    {date_obs:'',ename:'',class:'',fstart:'', fstop:'', fpeak:'', xcen:0,ycen:0,        helio:'', lfiles:'',recok:0}

gev=get_gev(time0,time1)

if not data_chk(gev,/struct) then begin 
   box_message,'No GEV events from ' + anytim(time0,/vms,/trunc) + $
                              ' through ' + anytim(time1,/vms,/trunc)
   return
endif
ssok=where(gev.peak gt 0,okcnt)
if okcnt gt 0 then gev=gev(ssok)       ; filter problem entries 
decode_gev,gev,ft0,ft1,ftp
ssok=where(ssw_deltat(ft1,ref=ftp) gt 0,okcnt)  ; one more problem set...
if okcnt gt 0 then gev=gev(ssok) 

gev=gev(uniq(anytim(gev,/ecs,/trunc)))
if newdata then begin 
   box_message,'Reading dummy gev record(s)'
   dgevfile=concat_dir('$SSW_GEVLOC','data,dummygev.geny')
   if file_exist(dgevfile) then begin 
      restgenx,file=dgevfile(0),dummygev
      dummygev=dummygev(sort(anytim(dummygev)))
      ssr=sel_timrange(dummygev,time0,time1,/between)
      if ssr(0) ne -1 then gev=concat_struct(gev,dummygev(ssr))
      atim=anytim(gev)
      gev=gev(uniq(atim,sort(atim)))
   endif else box_message,'Dummy gev file not found'
endif

; remove problems
prob_times=['24-APR-03  23:01:00']         ; << ??? TODO, Why mreadfits_sxig12 problem?
prob_times=['5:30 31-aug-2003'] 
probchk=tim2dset(prob_times,gev,delta=dts)
okss=where(dts ne 0)
gev=gev(okss)


nev=n_elements(gev)
if file_exist(ecat) then restgenx,file=ecat,catrecs else catrecs=gev_loc_template
retval=replicate(gev_loc_template,nev)

ename='gev_'+time2file(gev)
pname=concat_dir(subdir,ename+'.png')
retval.ename=ename
for i = nev-1,0,-1 do begin 
    chkec=where(catrecs.ename eq ename(i) and catrecs.recok,okcnt)
    if okcnt eq 0 then begin 
       decode_gev,gev(i),f0,f1,fp, class=class,out='ecs' 
       retval(i).date_obs=anytim(fp,/ccsds)
       retval(i).class=class(0)
       retval(i).fstart=f0
       retval(i).fstop=f1
       retval(i).fpeak=fp
       lfiles=''                           ; initialize to nothing
       case fdtype of 
          'eitsocket': begin 
               eit_closest_fd,f0,fp,fbef,faft, status=status, window_min=[-45,45]
               if not status then $
                  eit_closest_fd,f0,fp,fbef,faft, status=status, window_min=[-45,45],/after_time0
               if status then begin 
                   eit_sock_copy,fbef,out_dir=subdir
                   eit_sock_copy,faft,out_dir=subdir
                   eitl0=file_list(subdir,[fbef,faft])
                   if n_elements(eitl0) ne 2 then begin 
                      box_message,'Problem with one or more transfers'
                   endif else begin 
                     read_eit,eitl0,index,data
                     newpre='eitp_'+strtrim(index(0).wavelnth,2) + '_'
                     eit_prep,index,data=data,oindex,odata
                     lfiles=str_replace(eitl0,'efz',newpre(0)) 
                     mwritefits,oindex,odata,$
                        outfile=lfiles
                   endelse

               endif else begin 
                  box_message, 'No suitable EIT FD images around flare'
               endelse

          endcase
          'eit': begin 
delvarx,lfiles
               time_window,[f0,f1],t0x,t1x,min=[-60,12],out='vms'
               lxfiles=eit_high_cadence(t0x,t1x,/l1q,/return_files,high_wave=hwave) 

               ; lxfiles=sswdb_files(t0x,t1x,/eit,/l1q,pat='_195_*512.')
               ftimes=file2time(lxfiles,out='int')
               fbef=last_nelem(where(ssw_deltat(ftimes,ref=f0,/min) le 0,bcnt))
               faft=(where(ssw_deltat(ftimes,ref=fp,/min) gt -2,acnt))(0)
               if acnt eq 0 then $
                 faft=(where(ssw_deltat(ftimes,ref=f0,/min) gt -1,acnt))(0)
            
               rejecteit=0
               if acnt gt 0 then begin
                  chksxi=rd_tfile(concat_dir('$SSW_SITE_LOGS','sxi_over_eit.dat'))
                  eit_overt=file2time(chksxi,out='int')
                  ssover=tim2dset(eit_overt,ftimes,delta=dts)
                  ssrej=where(dts eq 0,rcnt)
                  mineitdt=6.    ; minimum flare duration for eit detection
                  tooshort=abs(ssw_deltat(f0,f1,/min)) lt mineitdt ; and $
                     ;ssw_deltat(f0,ref='3-sep') le 0
                  toosmall=class lt 'C5' and f0 ne '2003/07/18 13:35:00'
                  toosmall=class lt 'C5' and ssw_deltat(f0, ref='3-aug 0:00') $
                     le 0 
                  toosmall=class lt 'C7' and ssw_deltat(f0,ref='3-sep') le 0
                  toosmall=ssw_deltat(f0,ref='31-oct') gt 0  
                  toosmall=toosmall and (ssw_deltat(t0x,'23:50 2-nov') ne 0)
                  toosmall=toosmall and ssw_deltat(f0,ref='12:00 5-nov') le 0
                  toosmall=toosmall and ssw_deltat(f0,ref='15:00 7-nov') le 0
                  toosmall=ssw_deltat(f0,ref='12-nov-2003') le 0 $
                     or class lt 'M9'
                  toosmall=ssw_deltat(f0,ref='04:00 21-may-2004') lt 0 or $
                           ssw_deltat(f0,ref='16:42 21-may-2004') gt 0
                  toosmall=class lt 'C8' or $
                         ssw_deltat(f0,ref='16-jul 00:00') gt 0
                  toosmall=class lt 'M1' or $
                         (ssw_deltat(f0,ref='25-jul 14:00') gt 0 and $
                          ssw_deltat(f0,ref='28-jul 22:00') lt 0)
                  toosmall=class lt 'M1' and $
                    ( abs(ssw_deltat(fp,ref='4:31 9-oct-2004')) gt 120) 
                  toosmall=class lt 'M1' and $
                     (ssw_deltat(fp,ref='14:00 24-nov-2004') lt 0 or $
                      ssw_deltat(fp,ref='23:00 25-nov-2004') gt 0)  
                  toosmall=class lt 'M1' and $
                     (abs(ssw_deltat(f0,ref='5-apr-2005 04:45')) gt 120)
                  toosmall=class lt 'M1' and $
                     (abs(ssw_deltat(f0,ref='04:46:00 6-apr-2005')) gt 120)  and $
                     (abs(ssw_deltat(f0,ref='04:39:00 8-apr-2005')) gt 120)  and $
                     (abs(ssw_deltat(f0,ref='04:48:00 11-apr-2005')) gt 120)
                  toosmall=class lt 'C1';  and $
                     ;ssw_deltat(f0,ref='15:00 23-nov-2005') lt 0
                  toosmall =class lt 'C1.5'  ; and $
                  ;     ssw_deltat(f0,ref='06:00 22-mar-2006') lt 0
                  ;tooshort=0
                  ;toosmall=0
                  rejmess=(['Explicit','Duration < minEITdt'])(tooshort) + ') '
                  rejmess=([rejmess,' Too Small > ' + class(0)])(toosmall)
                  rejecteit=(rcnt gt 0) or tooshort or toosmall
                  eitoversxi=is_member(ename(i),$
                     ['gev_20031206_0006,gev_20041015_1523'])
                  rejecteit=rejecteit and (1-eitoversxi)

                  if rejecteit then box_message,['REJECTING EIT> (' + rejmess,$
                             lxfiles(faft)]
                endif
                  
if class eq 'M6.5' and bcnt eq 0 and acnt eq 3 then begin 
;  No "before", plenty during...
;  should really be handled by auto-switch to single 'close to peak' image solution
;
   box_message,'Kludge case...' ; gev_20030602_0007 (no sxi, eit switch waves (304->195), M6.5)
   bcnt=1
   fbef=2
endif
if faft eq fbef then faft=faft+1
               if bcnt gt 0 and acnt gt 0 and (1-rejecteit) then begin
                  lfiles=lxfiles([fbef,faft])  
               endif else begin 
                  box_message,'no eit, trying sxi...'
                  sxiimgcode=(['FL','AR'])(class le 'C3.0')
                  box_message,'Flare CLASS: ' + class + $
                                ' IMG_CODE: ' + sxiimgcode
                  remove_bad_sxi
                  lxfiles=sxi_high_cadence(t0x,t1x,/l1q,/return,goesn=goesn)
                     ;IMG_CODE=sxiimgcode)
 ftimes=file2time(lxfiles,out='int')

               fbef=last_nelem(where(ssw_deltat(ftimes,ref=f0,/min) lt 0,bcnt))
               faft=(where(ssw_deltat(ftimes,ref=fp,/min) gt -2,acnt))(0)
               if acnt eq 0 then $
                 faft=(where(ssw_deltat(ftimes,ref=f0,/min) gt -1,acnt))(0)

               case 1 of 
                  acnt gt 0 and bcnt gt 0: lfiles=lxfiles([fbef(0),faft(0)])
                  acnt gt 0:lfiles=replicate(lxfiles(faft(0)),2) 
                  else:
               endcase

               endelse 
          endcase
          else: box_message,'Only FDTYPE=EIT available for today'
       endcase
       if n_elements(lfiles) le 1 and debug then stop,'lf=1'
       if n_elements(lfiles) gt 1 then begin
       
       lfnames=arr2str(ssw_strsplit(lfiles,/tail,'/',/last),/comp,/no_dup)
       sscur=where(curgev.ename eq retval(i).ename,sscnt)
       if sscnt eq 1 then curtest=curgev(sscur).lfiles else curtest=''
       relocate=(lfnames ne curtest(0))  or refresh
       if relocate then begin 
          retval(i).lfiles=lfnames
          delvarx,index,data
          if n_elements(lfiles) gt 2 then stop,'too man...'
          mreadfits,lfiles,index,data
          ssm=where(data le 0,mcnt)
          if mcnt gt 0 then begin        
             data(ssm)=0
             ssw_fill_cube,data
          endif
          data(0,0,0)=nospike(data(*,*,0),/flare)
          data(0,0,1)=nospike(data(*,*,1),/flare)
          limbflares=concat_dir('$SSW_GEVLOC','data/limbflares.dat')
          if file_exist(limbflares) then begin 
             limbdat=rd_tfiles(limbflares)  
             maskdat=str2cols(limbdat,' ',/unal,/trim)
             strtab2vect,maskdat,gevnam, ann_lo,ann_hi   ; annulus to consider
             lss=where(retval(i).ename eq gevnam,lcnt)
             if lcnt gt 0 then begin
                annulus=float([ann_lo(lss(0)),ann_hi(lss(0))])
                box_message,'Limb flare special processing...
                if not required_tags(index,'mjd') then $
                   index=struct2ssw(index)
                for lii=0,1 do begin
                    data(0,0,lii)=data(*,*,lii)* $
                      solar_mask(index(lii),annu=annulus ) ; [.9,1.5]) 
                endfor
             endif

          endif
lsxi=strpos(lfiles(0),'SXI') ne -1 
if lsxi then begin
box_message,lfiles
   mreadfits_sxig12,lfiles,index,data,/register,/composite
   if n_elements(annulus) eq 2 then begin
index=struct2ssw(index)
for lii=0,1 do begin
                    data(0,0,lii)=data(*,*,lii)* $
                      solar_mask(index(lii),annu=annulus ) ; [.9,1.5])
                endfor

      delvarx,annulus
   endif

endif 

          xycen=ssw_flare_locator(index,data,oindex,ldata=ldata,$
              flare_helio=flare_helio,_extra=_extra,$
  limb_pad=([50,-50])(abs(ssw_deltat(index(1),'18:07 7-oct-2004')) lt 120), $
              smooth=round(25./(index(0).cdelt1) ), nofill=nofill, $ 
              reg_minutes=15, $ ; SLF 12-May-2005
              ;;dark=(retval(i).date_obs eq '2002-10-16T12:39:00.000Z'))
              dark=(retval(i).ename eq 'gev_20051130_2135'))


          if n_elements(xycen) eq 2 then begin 
            retval(i).xcen=xycen(0)
            retval(i).ycen=xycen(1)
            if www then begin 
               dindex=retval(i)
               dindex=add_tag(dindex,oindex.cdelt1,'cdelt1')
               dindex=add_tag(dindex,oindex.cdelt2,'cdelt2')
               dindex=add_tag(dindex,50,'naxis1')
               dindex=add_tag(dindex,50,'naxis2')
               ddata=bytarr(50,50,3)
               index2map,oindex,ldata,fdmap
               dindex=replicate(struct2ssw(dindex),3)
               dtags=str2arr('time,day,mjd,date_obs,crpix1,xrpix2,xcen,ycen')
               for ind=0,1 do  begin
                  temp=dindex(ind)
                  copy_struct,index(ind),temp, select=dtags
                  dindex(ind+(ind ne 0))=temp
               endfor
               context=ssw_fov_context(dindex,ddata,fdmap=fdmap,grid=15,$
                  xsize=512,margin=.07,composite=3,$
               fov=25,ss=1,/goes,tw_percent=100.,/oplotnar)
               wdef,im=context,/zbuffer
               tv,context
               delvarx,context
               ct2rgb,5,r,g,b
               fhns=flare_helio(0) & fhew=flare_helio(1)
               hstring=$
                (['S','N'])(fhns gt 0)+ string(abs(fhns),format='(i2.2)') + $
                (['E','W'])(fhew gt 0)+ string(abs(fhew),format='(i2.2)')
               itop=data_chk(context,/ny)
               retval(i).helio=hstring 
               xmar=60
               xyouts,xmar,itop-60,'Flare Peak: '+ fp + ' Class: ' + class,/device
               xyouts,xmar,itop-80,'Derived flare XCEN/YCEN: ' + $
                          arr2str(string(xycen,format='(2f6.1)'),$
                          /compress,delim=' / '),/device, color=250
               xyouts,xmar,itop-100, 'Heliographic: ' + hstring + $
               ; (['S','N'])(fhns gt 0) + string(abs(fhns),format='(i2.2)') + $
               ; (['E','W'])(fhew gt 0) + string(abs(fhew),format='(i2.2)') + $
                           ' @ ' + anytim(oindex,/ecs,/truncate) ,/device, color=250
               xyouts,xmar,itop-120,'Difference: ' + $
                  arr2str(reverse(anytim(index,/ecs,/trunc)),delim=' - '),/device
               zbuff2file2,pname(i),r,g,b,/png 
               savegenx,file=ecat,retval,/overwrite
               if retval(i).ename eq 'gev_20060131_1740' then $
                 les_moses_patch,/temp
            endif 
          endif else box_message,'Problem with location derivation?'
endif else begin ; relocatetion  not required
   box_message,'NO REFRESH REQUIRED
   cname=str_replace(pname(i),'_temp','')
   spawn,['cp','-p',cname,subdir],/noshell    ; current imag -> subdir(temp)
   new=str_copy_tags(retval(i),curgev(sscur)) ; current param -> new vect 
   retval(i)=new
   savegenx,file=ecat,retval,/overwrite
endelse
       endif else box_message,'no FD data (yet?)' 
    endif else box_message,'Event ' + ename(0) + ' already completed'

endfor 
  
savegenx,file=ecat,retval,/overwrite
les_moses_patch,/temp
; 
arch=get_logenv('ssw_latest_events_archive')
if arch eq '' then arch=concat_dir('$ssw_latest_events_parent','archive')

catdir=concat_dir(toparch,'gevloc')
ssok=where(retval.helio ne '',okcnt)
if okcnt gt 0 then begin
 write_genxcat,retval(ssok),/nelem,/geny,topdir=catdir
endif

return
end
