pro ssw_pfss_synop, times0, time1, ndays=ndays, nlines=nlines, $
   thumbmag=thumbmag, thumbwidth=thumbwidth, synop_default=synop_default, $
   fullmag=fullmag, fullwidth=fullwidth, cadence_hours=cadence_hours, $
   outdir=outdir, ecliptic=ecliptic, only_thumb=only_thumb, $
   last_synop=last_synop, spacing=spacing, debug=debug	

;+
;
;   Name: ssw_pfss_synop
;
;   Purpose: generate PFSS image files for each synoptic (eit/sxi) image
;            
;   Input Parameters:
;       time0,time1 - optional time range
;      
;
;   Keyword Parameters:
;      ndays - number of days to consider (ie, look back queue size)
;      nlines - pass to ssw_index2pfss_cube (number lines per radii)
;      thumbmag/thumbwidth - MAG and WIDTH pfss params for thumbnails (les) 
;      fullmag/fullwidth   - ditto for full size equivilents 
;      cadence_hours=cadence_hours - if time range supplied (overrides 
;                                    default which is sxi l1q synop cadence
;                                    which in turn is EIT synoptic (01,07,13,20)
;      ecliptic - if set, do ecliptic/open lines (see ssw_index2pfss.pro)
;  
;   Method:
;      default: sxi_l1q contents drives cadence
;
;   History:
;      Circa 1-jan-2005 - S.L.Freeland - add PFSS to latest_events
;       2-dec-2005 - S.L.Freeland - change NLINES (100->150) and
;                                   START_RADIUS(0) (1.0 -> 1.1 per Marc DeRosa)
;       3-Jan-2006 - S.L.Freeland - add /ECLIPTIC keyword&function
;       7-Jan-2006 - S.L.Freeland - add /DRAW_FIELD2 switch to ssw_index2pfss
;      10-Jan-2006 - S.L.Freeland - reverse processing order
;                                   from thumbnail/full -> full/thumbnail
;-

if n_elements(ndays) eq 0 then ndays=5     ; look back window

if n_elements(cadence_hours) eq 0 then cadence_hours=6 

last_les=keyword_set(last_synop)
debug=keyword_set(debug)

case 1 of 
   data_chk(outdir,/string):  ; user supplied
   last_les: outdir=concat_dir('$SSWDB','packages/pfss/latest_events')
   else: outdir=concat_dir('$SSWDB','packages/pfss/l1q_synop')
endcase

ecliptic=keyword_set(ecliptic)

if n_elements(thumbwidth) eq 0 then $
   thumbwidth=([2.0,2.5])(last_les)    ; les default
if n_elements(thumbmag) eq 0 then $
   thumbmag=([.38,.53])(last_les)    ; les default
if n_elements(fullwidth) eq 0 then fullwidth=([2.,2.5])(ecliptic)
if n_elements(fullmag) eq 0 then fullmag=([2.0,1.6])(ecliptic)

case 1 of 
   keyword_set(synop_default): begin 
      day0=anytim(reltime(days=(-1*ndays)),/date_only,/ecs,/trunc) 
      wanttimes=timegrid(day0+' 01:00', reltime(hours=6), hours=6)
   endcase
   n_params() eq 2: begin 
      wanttimes=timegrid(time0,time1,hours=cadence_hours,out='int')
   endcase
   else: begin
      sxisynd=concat_dir('$SSWDB','goes/sxig12/l1q_synop')
      sxisynop=findfile(sxisynd)
      wanttimes=file2time(last_nelem(sxisynop,ndays*4),out='int')
   endcase
endcase
if last_les then wanttimes=last_nelem(wanttimes,last_synop) ; last NN only	
curf=findfile(outdir)
ecliptic=keyword_set(ecliptic)

; pfss_yyyymmdd_hhmmss_Bfield_yyyymmdd_hhmmss
ncnt=n_elements(wanttimes)
;
need=lonarr(ncnt)+1         ; needed vector - default YES
remove=lonarr(ncnt)         ; remove old vector - default NO
remthumbs=strarr(ncnt)      ; potential old to remove

only_thumb=keyword_set(only_thumb) or last_les
troots=concat_dir(outdir,'pfss_'+  time2file(wanttimes))
for i=0,ncnt-1 do begin 
   thumbi=findfile(troots(i)+'*thumb' +(['.*','_eclip.*'])(ecliptic))
if n_elements(thumbi) gt 1 then begin
    dfthumb=thumbi(0)
    dfbig=str_replace(dfthumb,'thumb','full')
    box_message,['Removing...',dfthumb,dfbig]
    ssw_file_delete,[dfthumb,dfbig]
    thumbi=last_nelem(thumbi)
endif 
   if thumbi(0) ne '' then begin 
      box_message,'thumb found, checking for newer pfss
      ft0=ssw_strsplit(thumbi,'Bfield',tail=ft1)
      pfssi=pfss_time2file(wanttimes(i),/url,/ssw_cat)
      needit=(file2time(ft1) ne file2time(pfssi)) or only_thumb
      need(i)=needit
      remove=needit and (1-only_thumb)
      nmess=(['Newer PFSS available','THUMB_ONLY (force)'])(only_thumb)
      box_message,(['OK','Newer PFSS available'])(needit)
      remthumbs(i)=(['',thumbi])(needit)
   endif else box_message,'No thumb yet, need...'
endfor
needss=where(need,ncnt)


case n_elements(nlines) of 
   0: nls=[50,150]
   1: nls=replicate(nlines,2)
   else: nls=nlines(0:1)
endcase

types=str2arr('thumb,full')
mags=[thumbmag,fullmag]
widths=[thumbwidth, fullwidth]  
if n_elements(spacing) eq 0 then spaces=[([10,2.5])(last_les),2.5] else $
   spaces=spacing
pdefs=[0,252,250,254]
ldefs=[11,12,7,5]                         ; PFSS -> LINECOLORS mapping
tvlct,rs,gs,bs,/get                       ; preserve ct
dtemp=!d.name                             ; and plot device
set_plot,'z'
wdef,xx,/zbuffer
linecolors                                ; fancy ssw colors (E.Einfalt)
tvlct,r,g,b,/get
for i=0,ncnt-1 do begin                   ; for each want+need pfss time 
   for np=n_elements(mags)-1-only_thumb,0,-1 do begin   ; for each mag/width combo
     newpfss=pfss_time2file(wanttimes(needss(i)),/url,/ssw_cat)
     fname='pfss_'+time2file(wanttimes(needss(i)))+$
           '_Bfield'+strextract(newpfss,'Bfield','.sav') + '_'+ $
           types(np)+ (['','_eclip'])(ecliptic) + '.png'
     if ecliptic then begin 
        ssw_index2pfss,wanttimes(needss(i)),pii,pdd,/draw_field2, $
        mag=mags(np),  width=widths(np),spacing=spaces(np),/ecliptic
     endif else begin 
        ssw_index2pfss_multi,wanttimes(needss(i)),pii,pdd,/draw_field2, $
          mag=mags(np),  width=widths(np), nlines=nls(np), $
          /earth_view,start_radius=[1.1,2.5]  ; photosphere + source surface
     endelse
     for col=0,n_elements(pdefs)-1 do begin ; pfss color -> ssw linecolor map 
        ss=where(pdd eq pdefs(col),sscnt)
        if sscnt gt 0 then pdd(ss)=ldefs(col)
     endfor
     if last_les then begin 
        index2map,pii,pdd,pmap
        delvarx,zz
        wdef,zz,im=pdd
        plot_map,pmap,margin=.0001,grid=([30,15])(ecliptic), $
                  /limb,drange=[0,255], gcolor=150,lcolor=150,ticklen=.01
        if ecliptic then begin 
           nar=get_nar(reltime(days=-2),reltime(/now),/uniq)
           nar=drot_nar(nar,anytim(pii,/utc_int),count=count)
           if data_chk(nar,/struct) then oplot_nar,nar,color=4,thick=2,size=.9 
        endif
     endif else tv,pdd         ; update Zbuff image 
     if debug then stop,'prefile'
     zbuff2file2,concat_dir(outdir,fname),r,g,b    ; update dbase
   endfor                       ; end of this MAG/WIDTH combo
endfor
set_plot,dtemp
tvlct,rs,gs,bs                  ;restore CT

removess=where(remthumbs ne '',rcnt)
if rcnt gt 0 and (1-last_les) then begin
   rthumbs=remthumbs(removess)
   rfull=str_replace(rthumbs,'thumb','full')
   box_message,['Removing previous versions (ie, pfss updated)',$
                ssw_strsplit(rthumbs,'/',/tail,/last)]
   ssw_file_delete,[rthumbs,rfull]
endif else box_message,'No old versions to remove...'


return
end 
