pro sotsp_level2summary, l1dirs, outdir=outdir

;+
;   Name: sotsp_level2summary
;
;   Purpose: generate summary http for SOT-SP Level 1.5 data (yes, the
;   name of the routine implies that a Level 2 summary webpage is
;   being created, but it is actually a Level 1.5 webpage being created)
;
;   Input Parameters
;      l1dirs - list of one or more SOT Level 1 directories
;
;   Keyword Parameters:
;      outdir - if set, write out summary webpages to specified directory,
;               otherwise the default is to write to the production directory
;               structure (so be careful!)
;
;   Example:
;      sotsp_level2summary,'/archive1/hinode/sot/level1hao/2020/12/01/SP3D/20201201_000158',outdir='.'
;
;   History:
;      9-Oct-2007 - S.L.Freeland - to summarize stksimages_sbsp output & ...
;      6-Feb-2008 - S.L.Freeland - tweaks for hao organization
;     14-Apr-2021 - M.DeRosa - removed lots of cruft and added better comments
;-

tpath=get_logenv('path_http')
ttop=get_logenv('top_http')
set_logenv,'path_http',get_logenv('ssw_path')
set_logenv,'top_http','https://www.lmsal.com/solarsoft'

;  make sure input is a string or string array
if not data_chk(l1dirs,/string) then begin 
   box_message,'Need list of Level1 directories...'
   return
endif

;  make sure all input directories exist
nl1=n_elements(l1dirs)
fex=file_exist(l1dirs)
okss=where(fex,okcnt)
badss=where(1-fex,bcnt)
case 1 of 
  okcnt eq nl1:  ; all exist
  bcnt eq nl1: begin 
    box_message,'Cannot find any of your input directories..'
    return
    end
  else: begin 
    box_message,['Only found ' + strtrim(okcnt,2) + ' of your L2 paths ', $
                 'Missing: ',l1dirs(badss) ]
    end
endcase
l1d=l1dirs(okss)
nl1=okcnt

;  set output path
l15d=str_replace(l1d,'level1hao','level1d')
l15d=str_replace(l15d,'/archive','/archive1')
droot=ssw_strsplit(l1d,'/',/tail)
if keyword_set(outdir) then l15d=outdir+'/'+droot
hdocs=concat_dir(l15d,'index.html')
for i=0,nl1-1 do mk_dir,l15d(i)  ;  make output directories if needed
stkssave=droot+'_'+'stksimg.save'
thermdsave=droot+ '_' + 'thermdrift.save'

;  process each scanID
for i=0,nl1-1 do begin ; for each L1 directory
  box_message,'Processing>> ' + l1d(i)
  stks=(file_search(l1d(i),stkssave(i)))(0)
  thermsave=(file_search(l1d(i),thermdsave(i)))(0)
  if stks(0) eq '' then begin 
    box_message,'Warning: No stksimages_sbsp output file found (skipping)'
  endif else begin

    ;  get filenames and urls
    l1files=file_search(l1d(i),'*fits')
    l1urls=str_replace(l1files,'/net/kokuten/archive','https://www.lmsal.com/solarsoft')
    l1urls=str_replace(l1urls,'/sot','')
    
    ;  read L1 files and create a map index reflecting entire scan/l1input
    l1times=file2time(l1files,out='ecs')
    avtime=anytim((total(anytim(l1times))/n_elements(l1times)),/ecs)
    read_sot,[l1files(0),last_nelem(l1files)],index
    index2fov,index,/extremes,center_fov=cfov, size_fov=sfov
    ssw_fake_index,avtime,spindex, fov_as=sfov,xcen=sfov(0),ycen=sfov(1),$  
      cdelt1=index(0).cdelt2

    ;  scale images
    stksdata=ssw_save2struct(stks(0))
    if file_exist(thermsave) then thermdata=ssw_save2struct(thermsave)
    cont=bytscl(gt_tagval(stksdata,/conti))  ;  continuum
    long=sigrange(gt_tagval(stksdata,/blapp)>(-1500)<1500,fr=0.995)  ;  Blos
    trans=gt_tagval(stksdata,/btapp)
    trans=256-bytscl(trans,min=0,max=2000 < max(trans))  ;  Btrans
    veloc=stksdata.ctrline(*,*,0)
    veloc=bytscl(veloc,min=median(veloc)-2,max=median(veloc)+2)  ;  velocity

    ;  create images
    labels=['Continuum','Logitudinal','Transverse','Velocity (6301.5 &#x212b)'] 
    gfiles=str2arr('cont,long,trans,veloc,therm,context')
    tfiles=gfiles+'_thumb'
    mfiles=gfiles+'_micon'
    cts=[0,0,0,0]  ;  color tables
    delvarx,all_micon
    for g=0,3 do begin 
      estat=execute('idat='+gfiles(g))
      wdef,xx,/zbuffer,im=idat
      loadct,cts(g)
      tvscl,idat
      zbuff2file2,concat_dir(l15d(i),gfiles(g)+'.png')
      mxy=min([data_chk(idat,/x),data_chk(idat,/y)])
      if mxy gt 20 then ithumb=confac(idat,.4) else ithumb=idat
      wdef,xx,im=ithumb,/zbuffer
      tvscl,ithumb
      zbuff2file2,concat_dir(l15d(i),tfiles(g)+'.png')
      if mxy gt 20 then ithumb=confac(idat,.1) 
      wdef,xx,im=ithumb,/zbuffer
      tvscl,ithumb
      zbuff2file2,concat_dir(l15d(i),mfiles(g)+'.png')
      if n_elements(all_micon) eq 0 then all_micon=bytscl(ithumb) else $
      all_micon=[all_micon,bytscl(ithumb)]
    endfor
    wdef,xx,im=all_micon,/zbuffer
    tv,all_micon
    zbuff2file2,concat_dir(l15d(i),'clt_micon.png')

    ;  make webpage
    html_doc,hdocs(i),/header
    file_append,hdocs(i),hinode_credits(/sot,/url)
    tab=str2html(gfiles(0:3)+'.png',link=tfiles(0:3)+'.png')      
    tab=[[labels],[tab]]
    file_append,hdocs(i),strtab2html(tab,/row0header)

    ;  make thermal drift plot and add to webpage
    wdef,xx,650,400, /zbuffer
    linecolors
    utplot,l1times,thermdata.wdelw,background=11,color=7,$
           title='Thermal Drift History Along Slit w/smoothed fit & Cadence',psym=3
    outplot,l1times,thermdata.fitww,color=5
    evt_grid,l1times,ticklen=.01,tickpos=.2,color=4
    zbuff2file2,concat_dir(l15d(i),'thermaldrift.png')
    file_append,hdocs(i), $
    ['<p><font color=orange size=+1> Thermal Drift (Level0 -> Level1)', $
     '</font>',strtab2html('<img src="thermaldrift.png">')]

    ;  make centerline plot and add to webpage
    utplot,l1times,29.0-thermdata.avctr,background=11,color=7,$
           title='Average Centerline w/smoothed fit & Cadence',psym=3
    outplot,l1times,thermdata.fitav,color=5
    evt_grid,l1times,ticklen=.01,tickpos=.2,color=4
    zbuff2file2,concat_dir(l15d(i),'avectr.png')
    file_append,hdocs(i), $
    ['<p><font color=orange size=+1> Average Centerline (Level0 -> Level1)', $
     '</font>',strtab2html('<img src="avectr.png">')]

    ;  finish webpage
    sptext='$SSW/site/idl/util/fpp/sotsp.txt'
    file_append,hdocs(i),rd_tfile(sptext)
    l2subdir=ssw_strsplit(l15d(i),'/',/last,/tail) 
    file_append,hdocs(i),["<font size=+1>IDL> </font>",$
                          "<font color=blue> stks=sotsp_stks2struct('"+l2subdir+"')</font>"]
    file_append,hdocs(i),['<br> The above will copy data from the ',$
                          "SOT-SP Level2 server; Then, for example<br>",$
                          "<font size=+1>IDL> </font>",$
                          "<font color=blue> help,stks,/str</font><br>", $
                          "Output structure tags map 1:1 to save file 'Output Parameters' description in doc header of ",$
                          '<a href="https://sohowww.nascom.nasa.gov/solarsoft/hinode/sot/idl/sp/util/stksimages_sbsp.pro">stksimages_sbsp.pro</a>'] 
    
    file_append,hdocs(i),['<p>',hinode_credits(/url)]
    html_doc,hdocs(i),/trailer
    
  endelse
endfor

end

   
