pro ssw_last_event_summary_mag,path,debug=debug, legend_bottom=legend_bottom, $
   extend_mag=exten_mag,  corcadence=corcadence
;
;+
;   Name: ssw_last_event_summary
;
;   Purpose: integrate flare-locator and contextual dbases -> summary plot
;
;   History:
;      Circa March 2002 - S.L.Freelnd written
;      19-Sep-2002 - correct SWEPAM bulk speed units (km/hour -> km/sec)
;      15-Nov-2002 - add message / annotation if no data for nHours
;      21-Sep-2003 - Add titles to index and event summary pages
;      28-Sep-2003 - add call to trace_special_movies_online  
;                    (and annotations/links if any) - ala sep_events_online  
;      18-Dec-2003 - add link to Last Events Archive
;       9-mar-2004 - extended for ACE-MAG/Bz + Kyoto DST  + pfss
;      15-Mar-2004 - use SXI "synoptic" when EIT 284 not available  
;                    due to gap, bakeout...
;      11-Apr-2004 - add CORCADENCE keyword and function
;      13-may-2004 - PFSS now done offline via separate task 
;      30-nov-2004 - change full disk scaling algorithm (ssw_sigscale)
;       9-mar-2005 - add an Estimated KP bar (via ssw_apkpbar.pro call)
;       2-aug-2005 - call ssw_les_htmltable (adds NOAA AR and ARM links)
;       5-jan-2006 - add PFSS Ecliptic/Coronal Hole 
;       8-feb-2006 - add CACTUS CME detection bar/links
;-
debug=keyword_set(debug)

extend_mag=1 

phttp=get_logenv('path_http')
thttp=get_logenv('top_http') 

if n_elements(path) eq 0 then path=concat_dir(phttp,'latest_events')

cat=file_list(path,'*geny')
if cat(0) eq '' then begin 
   box_message,'No catalog available'
   return
endif

restgenx,file=cat(0),floc

ss=where(floc.lfiles ne '',gcnt)
if gcnt gt 0 then begin 
   floc=floc(ss)
   sxi=strpos(floc.lfiles,'SXI') eq 0
endif
t0x=reltime(days=-5,out='vms')
t1x=reltime(/now,out='vms')

;wdef,xx,1280,([700,968])(extend_mag),/zbuffer
wdef,xx,1315,([700,1160])(extend_mag),/zbuffer
set_plot,'z'
loadct,3
linecolors
savesys,/aplot
!p.multi=[0,1,([3,6])(extend_mag)]

!p.charsize=1.2
day_grid=gt_day(timegrid(t0x,reltime(t1x,days=1),/day,out='ints'),/string)

print,!p.multi,'pre goesx'
!p.font=3
plot_goes,t0x,t1x,timerange=[t0x,t1x],back=11,color=7, xstyle=9, $
   ymargin=[2,3],xmargin=[8,0],/nolabel, gcolor=50, /ascii,/goes12
   ;title='!C      GOES 12 XRayes'

ssw_les_fdinfo, last_time=last_time, gapmess=gapmess, dtnow=dtnow
if gapmess ne '' then begin 
   ;evt_grid,last_time,align=0, $ ; label='No Flare Locator Images ->',$
   ;  color=5, labpos=.67, labcolor=2,labsize=.9, tickpos=.67,/noarrow
   if ssw_deltat(last_time,ref=t0x) lt 0 then last_time=t0x
   evt_grid, color=2, last_time,align=0,/noarrow,$
      label=gapmess, labpos=.91,labcol=2,labsize=1.,$ ; tickpos=.7 , $
      /imap,imagemap_coord=imcgap, linestyle=0 ; .695
;   evt_grid, color=4,'11:47 11-sep-2005',align=0,/noarrow,$
;      label='NO SXI DATA --->',linestyle=0,labpos=.95,labcol=4,labsize=1

endif

evt_grid,day_grid,linestyle=0,color=5
if n_elements(sxi) gt 0 then begin 
evt_grid,anytim(floc.date_obs,/int),color=([4,5])(sxi),$
   label='!3'+floc.helio,$
   labpos=stag_lab(floc.helio,min=([.88,.93])(extend_mag),max=.99,sep=.035), $
   labsize=.8,labcolor=([4,5])(sxi), background=11

evt_grid,anytim(floc.date_obs,/int),labcolor=9,label=strtrim(indgen(gcnt)+1,2), $
    labpos=stag_lab(floc.helio,min=([.905,.938])(extend_mag),max=1,sep=.035), $
       labsize=.85,/noline, $
       /imap,imagemap_coord=imc,/imcircle
endif else imc=''

trace_special_movies_online,t0x,t1x, $
   pt0=pt0tm, pt1=pt1tm, urls=urlstm,ecount=ecount
if ecount gt 0 then begin
   venus=ssw_in_timerange(pt0tm,'03:00 8-jun','14:00 8-jun-2004')
   cool= ssw_in_timerange(pt0tm,'19:00 16-jun-2005','21:00 16-jun-2005')
   tracelabs=replicate('TRACE',ecount) + (['','-VENUS!!'])(venus)
   tracelabs=tracelabs+(['','!CHow SEPs Work'])(cool)
   lcolors=([12,9])(venus)
   lcolors=([12,2])(cool)
   evt_grid,anytim(pt0tm,/int), /noarrow, $
        label=tracelabs, $
      align=.5,labcolor=12,labsiz=.9, $
      labpos=stag_lab(tracelabs,min=([.69,.83])(extend_mag) ,$
         max=([.73,.86])(extend_mag),sep=([.02,.01])(extend_mag)), $
     /imap,imagemap_coord=imctm,linestyle=1,color=lcolors 
if debug then stop ,'TRACE Movies'
endif
;evt_grid,anytim('17:50 8-feb-2006',/int),  $
;   label='LASCO/NRL!CCME(C2-diff)', $
;   label=' MOSES!C<-- Launch/Obs. Window!C (click for context)',$ 
;   align=0,labcolor=4,labsiz=.9, /noarrow, $ 
;   labpos=.91, $
;  /imap,imagemap_coord=imclm,linestyle=1,color=4
;urlslm='http://www.lmsal.com/solarsoft/latest_events_summary/gev_20060203_0725/gev_20060203_0725_laslm.html'
; urlslm='http://www.lmsal.com/solarsoft/les_moses/moses_context_j.html"
;evt_grid,anytim('17:50 8-feb-2006',/int),color=4
;evt_grid,anytim('19:00 8-feb-2006',/int),color=4
;
;-------------------------- sxi eclipse-------------------------
;evt_grid,anytim('03:27 28-feb-2006',/int),  $
; evt_grid,anytim('10-may-2006 12:00',/int),  $
;   label='<-- SXI Eclipse!C(Now, w/Darker Moon!)!C  (Click for Movie)',$
;   label='<-EIT 304 Prom Dance-> !C (Click for Movie)',$
;   align=.5,labcolor=4,labsiz=.9,  $
;   labpos=.91,/noarrow, $
;  /imap,imagemap_coord=imceclipse,linestyle=1,color=4

;urlseclipse='http://www.lmsal.com/solarsoft/latest_events_summary/gev_20060228_0305/gev_20060228_0305_sxilm.html'
;urlseclipse='http://www.lmsal.com/solarsoft/jtest/eit304_eprom_20060324.html'
;urlseclipse='http://www.lmsal.com/solarsoft/dpe304/prom_dance.html'
; --------------------------------------------------------------
goes8=ssw_deltat(t1x,ref='19-jun-2003') lt 0
goes11=1-goes8
print,!p.multi,'pre goesP'
plot_goesp, t0x, t1x,  xstyle=1, /nowindow, /log, $
   ymargin=[2,3], xmargin=[8,0], /proton_only,timerange=[t0x,t1x], $
   yrange=[1,10e4],/ystyle,/nolabel , ticklen=.01,/clear, $
   legend_bottom=1, $  ; set to bottom for CACTUS co-habitat (8-feb-2006)
   goes8=goes8,goes11=goes11, $
   title='GOES 11 Proton & CACTUS/SIDC Detections!C(CME Width/CPA link->SIDC)'

evt_grid,day_grid,linestyle=0,color=5, /vertical, label=strmid(day_grid,0,6), $
      labcolor=5, labsize=.9,labpos=.75

;ssw_cactus_bar,ticklen=.002,/label,tickpos=.785,labcol=9,$
cmes=ssw_getcme_cactus(/quicklook)
cacturls=''
if data_chk(cmes,/struct) then begin
pos=stag_lab(string(cmes.duration),min=.78,max=.82,sep=.025)
ssw_cactus_bar,cmes, ticklen=.005,/label,tickpos=pos, labcol=9, labpos=pos+.005, $
   /imap,imagemap_coord=cactimap, cacturls=cacturls,/width_sort
endif

special_events_online,t0x,t1x,peak=peak,labels=labels,urls=urlssp,ecount=ecount
if ecount gt 0 then begin
   evt_grid,anytim(peak,/int), /arrow, /head,  $
        label=labels, labsize=.7, $
      align=1,labcolor=9,labpos=.84,tickpos=.83,ticklen=.01,  $
     /imap,imagemap_coord=imcsp,linestyle=0,color=2 
if debug then stop ,'special events'
endif

proton_events_online,t0x,t1x,peak=peak,/read_goesp,urls=urlsgp,ecount=ecount
if ecount gt 0 then begin
   evt_grid,anytim(peak,/int), /noarrow, $
        label=replicate('[SEP Details]',ecount), $
      ;label='  New Region NE !C  Homologous CMEs !C !C  (Click to Compare)', $
      align=1,labcolor=4,labpos=.78,  $
     /imap,imagemap_coord=imcgp,linestyle=0,color=2 ; ,/arrow,/head 
     ;urlsgp='http://www.lmsal.com/solarsoft/homolcme_20060428/'
     ;evt_grid,'16:15 29-apr-2006',linestyle=0,color=2,/arrow,/head
if debug then stop ,'SEP events'
endif
acedata=get_acedata(t0x,t1x,/daily,/swepam)

print,!p.multi,'pre SWEPAM
utplot,acedata,acedata.b_speed,title='!3ACE/SWEPAM and SoHO/EIT-284 + SXI-G12', $
   ytitle='Bulk Speed (Km/Sec)', $
   ymargin=[4,2], xmargin=[8,0],timerange=[t0x,t1x], xstyle=1, $
   /ynozero,color=7, ticklen=.01
evt_grid,day_grid,linestyle=0,color=5
;
; plot some thumbnails...
; synop grid (use eit synoptic cadence, fill gaps with 

st0='01:00 ' + anytim(reltime(t0x,days=-5),/vms,/date_only)
st1='01:00 ' + anytim(reltime(t1x,days= 1),/vms,/date_only)

dtdays=ssw_deltat(t0x,t1x,/days)
if n_elements(corcadence) eq 0 then corcadence= 6*(round(dtdays/1.5)) else $
   box_message,'Using user supplied cadence ' + strtrim(corcadence,2) +' hours'
box_message,'synopcadence='+strtrim(corcadence,2)
sgrid=timegrid(st0,st1,hours=corcadence,out='vms')   ; ideal grid
e284=sswdb_files(t0x,t1x,pat='_284_',/l1q)  ; try eit284 first
t284=file2time(e284,out='int')              ; times
ess=tim2dset(t284,sgrid,delta=dteit)        ; match -> grid
sxisynop=file_list('$SSWDB/goes/sxig12/l1q_synop','*.FTS')
sxisynop=sel_filetimes(t0x,t1x,sxisynop)

tsxi=file2time(sxisynop,out='int')
sss=tim2dset(tsxi,sgrid,delta=dtsxi)

sse=where(dteit lt 3600,ecnt)
sssxi=where(dteit gt 3600 and dtsxi lt 3600,scnt)
 
if ecnt gt 0 then efss=tim2dset(t284,sgrid(sse))  
if scnt gt 0 then sfss=tim2dset(tsxi,sgrid(sssxi))

nmerge=total([ecnt, scnt])   ; number of merged images

if nmerge gt 0 then begin 
   outsize=512
   mcube=make_array(outsize,outsize,nmerge,/byte)
   mtimes=strarr(nmerge)
   if debug then stop,'teit
   case 1 of 
      scnt gt 0 and ecnt gt 0: sorder=sort([sse,sssxi])
      scnt gt 0: sorder=indgen(scnt)
      ecnt gt 0: sorder=indgen(ecnt)
      else: box_message,'Impossible!'
   endcase
   i=0
   if ecnt gt 0 then begin 
      mreadfits,e284(efss),i284,d284,outsize=512
      ;s284=bytscl(do_eit_scaling(d284,/log,/no_prep))
      s284=ssw_sigscale(i284,d284,/log,/corner_cut)
      for i=0,ecnt-1 do begin 
         mcube(0,0,sorder(i))=s284(*,*,i)
         mtimes(sorder(i))=anytim(i284(i),/ecs)
      endfor
   endif

   if scnt gt 0 then begin 
      mreadfits,sxisynop(sfss),si284,sd284
      ;ss284=safe_log10(sd284>.3,/byte)    
      ;ss284=ssw_sigscale(si284,sd284+.5)
      ss284=bytscl((safe_log10(si284,sd284))^.8)
      for ii=0,scnt-1 do begin 
         mcube(0,0,sorder(i+ii))=ss284(*,*,ii)
         mtimes(sorder(i+ii))=anytim(si284(ii),/ecs)
      endfor
   endif
   ssreorder=sort(mtimes)
   mtimes=mtimes(ssreorder)
   tempcube=mcube
   for i=0,data_chk(mcube,/nimage)-1 do tempcube(0,0,i)=mcube(*,*,ssreorder(i))
   mcube=temporary(tempcube)
   box_message,['Post Merge=================',mtimes]
   case 1 of 
      data_chk(i284,/struct) and data_chk(si284,/struct): $
           i284=concat_struct(anytim(i284,/int),anytim(si284,/int))
      data_chk(si284,/struct): i284=si284
      else:
   endcase
   if n_elements(i284) gt 1 then i284=sort_index(i284)       ; assure time -> 

   ssd=confac(mcube,.30)
   evt_grid,i284
   split_colortab,0,200,16
   nei=n_elements(i284)
   evt_grid,i284,labdata=ssd+16<!p.color, labpos=([.05,.52])(extend_mag), $
      /imap,imagemap_coord=imcthumb
endif
outplot,acedata,acedata.b_speed,color=7

if extend_mag then begin                ; Bz+DST+PFSS
   ssw_pfss_time2l1q,i284,pfss_cube,full_urls=pfss_urls ; time->PFSS dbase 
   ssw_pfss_time2l1q,i284,pfss_eclip_cube, full_urls=pfss_eclip_urls,/eclip
   acedata=get_acedata(t0x,t1x,/daily,/mag)
   dst=ssw_getdst(t0x,t1x)
   if not data_chk(dst,/struct) or n_elements(dst) lt 10 then begin 
      dst=timegrid(t0x,t1x,/hour,out='int')
      dst=add_tag(dst,0.0,'dst')
   endif
if get_logenv('ssw_chk_dst') ne '' then stop,'dst'
   print,!p.multi,'pre ACEMAG/pfss'
   utplot,dst,dst.dst,title='!3Kyoto DST (NRT) and PFSS (Derosa, Schryver)', ymargin=[4,2],thick=1.5, /nolabel, $
      xmargin=[8,0],timerange=[t0x,t1x], xstyle=1, color=5, ytitle='DST (nT)'
   evt_grid,i284,labdata=pfss_cube, labpos=.36, $
      /imap,imagemap_coord=imcpfss  ; imcthumb
   outplot,dst,dst.dst,color=4,thick=4
   if min(dst.dst) lt 50 then outplot,[t0x,t1x],[-50,-50],color=2,$
      thick=2,linestyle=1
   if min(dst.dst) lt 100 then outplot,[t0x,t1x],[-100,-100],color=2,$
      thick=2, linestyle=0

;  PFSS ecliptic/CH plot
   utplot,dst,dst.dst,title='!3PFSS Open-Ecliptic & PFSS Derived Coronal Holes', $
      yticklen=.001, ymargin=[4,2],thick=1.5, /nolabel,ystyle=4, $
      xmargin=[8,0],timerange=[t0x,t1x], xstyle=1, color=11, ytitle='PFSS'
   evt_grid,i284,labdata=pfss_eclip_cube(*,20:120,*), labpos=.212, $
      /imap,imagemap_coord=imcpfss_eclip  ; imcthumb

;  ACE-MAG
   brange=[min(acedata.bz),max(acedata.bt)]
   utplot,acedata,acedata.bz,title='!3ACE/MAG-Bz/BTotal + Est KP',ytitle='Bz/BTot (nT)', $
   ymargin=[4,2], xmargin=[8,0],timerange=[t0x,t1x], xstyle=1, $
   /ynozero,color=9, ticklen=.01, yrange=brange
   outplot,acedata,acedata.bz,color=7
   outplot,acedata,acedata.bt,color=9
   outplot,[t0x,t1x],[0,0],color=2,linestyle=1,thick=1
   evt_grid,day_grid,linestyle=0,color=5
   ssw_apkpbar,ticklen=.013,tickpos=.145,/label,thick=25,/labove,$
      /estimated,labcolor=4

if debug then stop , 'done plots...'      
endif

summary='summary_plot'+(['','_extmag'])(extend_mag) + '.png'
plot_summ=concat_dir(path,summary)

zbuff2file2,plot_summ,/png
restsys,/aplot ,/init 

; generate top page
nevt=n_elements(floc)
epngs=concat_dir(path,floc.ename+'.png')
hpngs=str_replace(epngs,'png','html')
break_file,epngs,ll,pp,ff,ee,vv
relepng=ff+ee+vv
;
htable=ssw_les_htmltable(floc,/arm_links) ; gevloc -> html table w/noaaAR

; Generate a page for each event 
for i=0,nevt-1 do begin
   html_doc,hpngs(i),/header, title= $
      '!3SolarSoft Latest Events - Summary of event: ' + floc(i).ename
   file_append,hpngs(i),strtab2html(htable(*,[0,i+1]),/row0)
;
;  Check for pre-existing event summary html
   sumdir='latest_events_summary/'+floc(i).ename
   summp=concat_dir(phttp,sumdir)
   sumhttp=concat_dir(summp,floc(i).ename+'_lm.html.dat')
   if file_exist(sumhttp) then begin 
      shttp=rd_tfile(sumhttp)
      relhttp=str_replace(shttp,'gev_','../'+sumdir+'/gev_')
      file_append,hpngs(i),'<h3>Flare Sequence - Full disk and derived FOV</h3>'
      file_append,hpngs(i),relhttp
   endif 
   sumhttp=concat_dir(summp,floc(i).ename+'_sxilm.html.dat')
   if file_exist(sumhttp) then begin 
      shttp=rd_tfile(sumhttp)
      relhttp=str_replace(shttp,'gev_','../'+sumdir+'/gev_')
      file_append,hpngs(i),'<h3>SXI-GOES12 Flare Sequence - Full disk and derived FOV</h3>'
      file_append,hpngs(i),relhttp
   endif 
   sumhttp=concat_dir(summp,floc(i).ename+'_laslm.html.dat')
   if file_exist(sumhttp) then begin 
      shttp=rd_tfile(sumhttp)
      relhttp=str_replace(shttp,'gev_','../'+sumdir+'/gev_')
      file_append,hpngs(i),'<h3>LASCO C2 Difference - GOES Start - 30 min <em>to</em> GOES End+4 hours </h3>'
      file_append,hpngs(i),'<em>Courtesy LASCO/NRL</em>'
      file_append,hpngs(i),relhttp
   endif 
   sumhttp=concat_dir(summp,floc(i).ename+'_trace.html.dat')
   if file_exist(sumhttp) then begin 
      shttp=rd_tfile(sumhttp)
      relhttp=str_replace(shttp,'HREF="','HREF="../'+sumdir+'/')
      relhttp=str_replace(relhttp,'SRC="','SRC="../'+sumdir+'/')
      file_append,hpngs(i),'<h3>TRACE event sequences</h3>'
      file_append,hpngs(i),relhttp
   endif 
   file_append,hpngs(i),'<h3>Flare Locator Image</h3>' 
   file_append,hpngs(i),'<em>Difference: '+ $
      arr2str(reverse(str2arr(floc(i).lfiles)),' - ')
   file_append,hpngs(i),$
       strtab2html('<IMG SRC="'+ relepng(i)+'">')
   html_doc,hpngs(i),/trailer
endfor
html_linklist,hpngs,insert='sundiv.gif'         ; link-list the event html files  
index=concat_dir(path,'index' + (['_orig',''])(extend_mag) + '.html')
enames=strtrim(reform(htable(1,1:*)),2)
htable(1,1:*)=str2html(enames+'.html',link=enames,/nopar)

; image map info 
imcurl=enames+'.html'
imcall=imc
if n_elements(imcthumb) gt 0 then begin   ; coronal thumbs?
   imcall=[imcall,imcthumb]
   armurls='http://beauty.nascom.nasa.gov/arm/'
   armurls=ssw_nar2armurl(/top)
   subgrid=time2file(i284,/date_only)
   ;today=time2file(reltime(/now),/date_only)
   ;sstod=where(subgrid eq today,tcnt)
   ;if tcnt gt 0 then subgrid(sstod)='latest'
   armurls=armurls+'/'+'index.php?date='+subgrid 
   imcurl=[imcurl,armurls]
endif

if n_elements(imcpfss) gt 0 then begin    ; pfss ?
   imcall=[imcall,imcpfss]
   imcurl=[imcurl, pfss_urls] ; replicate(pfssurl,data_chk(pfss_cube,/nimage))]
endif

if n_elements(imcpfss_eclip) gt 0 then begin ; pfss ecliptic
   imcall=[imcall,imcpfss_eclip]
   imcurl=[imcurl, pfss_eclip_urls]
endif

help,imcgap
if n_elements(imcgap) gt 0 then begin 
   imcall=[imcall,imcgap]
   ;imcurl=[imcurl,'http://umbra.nascom.nasa.gov/eit/CCD_bakeout.html']
   ;imcurl=[imcurl,'http://sohowww.nascom.nasa.gov/whatsnew/HGA/']
   ;imcurl=[imcurl,'http://www.nasa.gov/vision/earth/lookingatearth/Isabels_Engine.html']
   imcurl=[imcurl,'http://sohowww.nascom.nasa.gov/data/synoptic/.targets/today.html']
endif

if n_elements(imctm) gt 0 then begin           ; TRACE special movies...
   imcall=[imcall,imctm]
   imcurl=[imcurl,urlstm]
endif

if n_elements(imclm) gt 0 then begin 		; LASCO movies
   imcall=[imcall,imclm]
   imcurl=[imcurl,urlslm]
endif

if n_elements(imcgp) gt 0 then begin 
   imcall=[imcall,imcgp]
   imcurl=[imcurl,urlsgp]
endif

if n_elements(imcsp) gt 0 then begin 
   imcall=[imcall,imcsp]
   imcurl=[imcurl,urlssp]
endif

if n_elements(cactimap) eq n_elements(cacturls) then begin
   imcall=[imcall,cactimap]
   imcurl=[imcurl,cacturls]
endif else box_message,'Not mapping CACTUS...)

if n_elements(imceclipse) gt 0 then begin
    imcall=[imcall,imceclipse]
    imcurl=[imcurl,urlseclipse]
endif

imaphtml=ssw_imapcoord2html(summary,imcall,imcurl, $
    target='_blank')
ss=where(strpos(imaphtml,'cactus') ne -1, ccnt)
if ccnt gt 0 then begin 
   box_message,'CACTUS retargeting...'
  imaphtml(ss)=str_replace(imaphtml(ss),'"blank"','"cactus"')
endif
imaphtml(0)=strtab2html(imaphtml(0),border=2,spacing=3,padd=3)
outhtml=''
ssw_ar_summary,outhtml=outhtml,/nodoc, outdir=path,thumbsize=256, /sxi
html_doc,index,/header,title='SolarSoft Latest Events'
file_append,index,[ $
   '<a href="http://www.lmsal.com/solarsoft/latest_events_archive.html">',$
   'Data for earlier dates is available at <em>Latest Events Archive</em></a>']
file_append,index,outhtml
;file_append,index,'<h4> Select AR above to link to BBSO/ARM details - Select Event# (<font color="#00CCFF">Bright Blue</font>) on the GOES X-Ray plot  for event summary page</h4>'
file_append,index,imaphtml
file_append,index,strtab2html(htable,/row0,cellpad=5,cellspac=2,border=2)
html_doc,index,/trailer


return
end
