pro hinode_make_wwwmovies, time0, time1, _extra=_extra, $
   search_array=search_array, prog_no=prog_no, $ 
   movie_dir=movie_dir, refresh=refresh, $
   max_xy=max_xy, min_frames=min_frames, max_frames=max_frames, $
   xrt=xrt, url_movies=url_movies, debug=debug, $
   latest_events=latest_events, latest_movies=latest_movies, $
   voevent_movies=voevent_movies, make_voevent=make_voevent, iquv=iquv , $
   sirius=sirius, context=context, sp_only=sp_only, fg_only=fg_only, $
   add_point=add_point, v_only=v_only, event_type=event_type, $
   xcenycen=xcenycen
;
;+
;   Name: hinode_make_wwwmovies
;
;   Purpose: make Hinode SOT/XRT movies for given time range
;
;   Input Parameters:
;      time0,time1 - time range for movies
;
;   Keyword Parameters:
;      search_array - optional search array filter (per sot_cat.pro)
;      movie_dir - parent directory for movies
;      min_frames - ignore modes/observations with fewer frames
;      search_array=search_array, $ 
;      prog_no - optionally, limit movies to this PROG_NO (slot number)
;      max_frames - upper limit frames-per-movie throttle
;      max_xy - upper limit on output resolution; aspect ratio preserved
;      refresh - keyword; if set, force regeneration even if no new cat entries
;      xrt - if set, make XRT movies (default=SOT)
;      latest_events, latest_movies, and voevent_movies - special switches for 
;         standard WWW output areas - (ssw latest events, 
;      make_voevent (switch) - generate VOEvent xml (Call mk_voe_obs,G.L.Slater)
;      context (switch) - if set, add context using all defaults
;      size_context - optional vector of context image size(s) 
;      fov_context  - optional vector of context FOV(s) (arcmin)
;      v_only - if set, only deal with V component (FGIV,FGQUIV,SPQUIV)
;      event_type - optionally string description of "Event Type" ;
;       (Flare,CME,Filament,...) 
;
;   History:
;      17-Feb-2007 - S.L.Freeland
;      20-Feb-2007 - S.L.Freeland - fg_prep hooks, /REFRSH&MAX_XY added
;      22-Feb-2007 - S.L.Freeland - PROG_NO hooks
;      27-feb-2007 - S.L.Freeland - PLANINFO hooks (call sot_time2planinfo)
;       1-mar-2007 - S.L.Freeland - add /MAKE_VOEVENT keyword & function
;      14-mar-2007 - S.L.Freeland - add xrt_prep hook
;      15-mar-2007 - S.L.Freeland - add /IQUV (include Non-Simple FG/SP)
;       6-apr-2007 - S.L.Freeland - add CONTEXT keywords & function
;      12-apr-2007 - S.L.Freeland - add /SP_ONLY keyword&function
;                                   (forces parallel tree and voevent files)
;      19-apr-2007 - S.L.Freeland - add V_ONLY keyword&function
;       3-may-2007 - S.L.Freeland - prepend {sot,xrt} in directory names
;      10-may-2007 - S.L.Freeland - add credits to html docs 
;                                   (via hinode_credits.pro)
;       3-jun-2007 - S.L.Freeland - add XCENYCEN (patch plan vs actual hiccups)
;
;   Method:
;      sot_cat, sot_prep , sot_umodes, then the usual of ssw-gen 
;          data management & movie making utilities...
;
;   Restrictions:
;      Assumes sot/xrt catalogs online and local version of SOT/XRT Level0 data
;
   
debug=keyword_set(debug)
if n_params() lt 2 then begin 
   box_message,'Need a time range....
   return
endif

incprog=n_elements(prog_no) gt 0 ; xtra PROG_NO (slot number) stuff...
make_voevent=keyword_set(make_voevent) ; generate VOEevent XML if set
xrt=keyword_set(xrt)
v_only=keyword_set(v_only)

iquv=keyword_set(iquv)

if not iquv then begin ; exclude SP & non-Simple (mag) FG 
   case n_elements(search_array) of
      0: search_array='naxis1>100'
      1: search_array=[search_array,'naxis=2']
      else: search_array=[search_array,'naxis=2']
   endcase
endif
if incprog then begin  
   box_message,'PROG_NO processing
   prog_nos='prog_no='+strtrim(prog_no,2)
   if n_elements(search_array) eq 0 then search_array=prog_nos else $
      search_array=[search_array,prog_nos]
endif

sp_only=keyword_set(sp_only) 
fg_only=keyword_set(fg_only)

if sp_only or fg_only then begin 
   msearch=(['FG*','SP*'])(sp_only)
   box_message,'Only considering '+ msearch+ '... modes'
   msearch='obs_type='+msearch
   if n_elements(search_array) eq 0 then search_array=msearch else $
      search_array=[search_array,msearch]
endif
   
sirius=keyword_set(sirius)
quicklook=1-sirius
xrt=keyword_set(xrt)
instr=(['sot','xrt'])(xrt)

sot_cat,time0,time1,cat,files, search_array=search_array, xrt=xrt, $
  match=match, sirius=sirius

if n_elements(xcenycen) eq 2 then begin 
   box_message,'Patching XCEN/YCEN'
   cat.xcen=xcenycen(0)
   cat.ycen=xcenycen(1)
endif

if match eq 0 then begin 
   box_message,'No catalog records match your time/search params'
   return ;!! early exit
endif

if xrt then cat=add_tag(cat,cat.ec_fw2_,'wave')

if n_elements(max_frames) eq 0 then max_frames=25
if n_elements(min_frames) eq 0 then min_frames=5
if n_elements(max_xy) eq 0 then max_xy=512

if xrt then umodes=xrt_umodes(cat,info=info,mcount=mcount,add_point=add_point) else $
   umodes=sot_umodes(incat=cat,info=info,mcount=mcount,add_point=add_point)
nmodes=n_elements(umodes)
box_message,['Uniq Modes:',umodes]

spre='' 
case 1 of
   data_chk(movie_dir,/string):  ; user supplied
   keyword_set(latest_events): begin 
      sub='latest_events'
      evttype='les'
      spre=(['sot_','xrt_'])(xrt)
   endcase
   keyword_set(latest_movies): begin 
      sub='latest_movies'
      evttype='lem'
   endcase
   keyword_set(voevent_movies): begin 
      sub='voevent_movies' + (['_sot','_xrt'])(xrt)
      evttype='Obs'
   endcase
   else: movie_dir=concat_dir(curdir(),+'_'+time2file(time0),/second)
endcase

if not data_chk(event_type,/string) then event_type=evttype

topwww_path='/net/kokuten/archive/hinode/metadata/wwwmovies' + $
   (['','_sirius'])(sirius) 

topwww_http='http://www.lmsal.com/solarsoft/hinode/movies' + $
   (['','_sirius'])(sirius) 
   
progname=''
if incprog then progname='_prog_'+string(prog_no,format='(I2.2)')

if data_chk(sub,/string) then begin ; some standard archive setup...
   phttp=get_logenv('path_http') 
   thttp=get_logenv('top_http') 
   movie_parent=concat_dir(topwww_path,sub)
   trange=time2file(time0)+'_'+time2file(time1)
   daily=ssw_time2paths(time0,time0,parent=movie_parent)
   movie_dir=concat_dir(daily,spre+trange+progname) + (['','_sp'])(sp_only)
   set_logenv,'path_http',topwww_path
   set_logenv,'top_http',topwww_http
box_message,'CHECK ENV
   indexgeny=concat_dir(movie_dir,trange+progname+'.geny') ; track some useful stuff... 
   if file_exist(indexgeny) then begin ; already done this-chk for new cat/data  
      restgenx,file=indexgeny,ecat
      refresh=keyword_set(refresh) or n_elements(cat) gt n_elements(ecat)
      if not refresh then begin 
         box_message,'Implied movies already made; use /REFRESH to regenerate...'
         return
      endif
   endif
endif

if not file_exist(movie_dir) then mk_dir,movie_dir ; create target directory

index_html=concat_dir(movie_dir,'index.html')

mhtml=concat_dir(movie_dir,time2file(time0)+ '_' + $
   time2file(time1)) + progname + '.html'
html_doc,mhtml,/header
file_append,mhtml,hinode_credits(xrt=xrt,sot=(1-xrt),/url)
if incprog then begin 
   planinf=sot_time2planinfo(time0,match_slot=float(prog_no))
endif


mnames=strarr(nmodes)
mok=intarr(nmodes)
for m=0,nmodes-1 do begin   ; movie per mode   
   delvarx,mstr,oindex
   box_message,'Processing mode>> ' + umodes(m)
   if xrt then ss=xrt_umodes(cat,info=info, where_mode=umodes(m),add_point=add_point) else $
      ss=sot_umodes(incat=cat,info=info,where_mode=umodes(m),add_point=add_point) ; SS for This mode
   nimg=n_elements(ss)
   allmatches=cat(ss)
   if nimg ge min_frames then begin ; enough frames to moviefy
      if nimg ge max_frames then ss=ss(grid_data(anytim(cat(ss).date_obs,/int),$
             nsamp=max_frames))
      mfiles=files(ss)
      validss=where(file_exist(mfiles),vcnt) ; check for missing level0
      if vcnt lt n_elements(mfiles) then begin ; 
         mfilesn=ssw_strsplit(mfiles,'.',/head) + '.0.fits'
         validssn=where(file_exist(mfilesn),vcntn)
         if vcntn gt vcnt then begin
            mfiles=mfilesn
            box_message,'Kluding file names...
            validss=validssn
            vcnt=vcntn
         endif
      endif

      if vcnt gt 0 then begin  
      mfiles=mfiles(validss) ; try not to read files which don't exist
      read_sot,mfiles,index,data
      if n_elements(xcenycen) eq 2 then begin
         index.xcen=xcenycen(0)
         index.ycen=xcenycen(1)
      endif
      fg=strpos(umodes(m),'FG') ne -1
      sp=strpos(umodes(m),'SP') ne -1
      scaleit=1
      case 1 of 
         fg: begin
            if index(0).naxis eq 2 then begin  
               fg_prep,index,data,oindex,odata,/no_polcal,/no_redspot,/no_flat
            endif else begin 
               if v_only then box_message,'V_ONLY set; only doing V component'
               sot_iquv_3d, index,data,oindex,sdata , v_only=v_only
               scaleit=0
               box_message,'FG non-simple'
            endelse
         endcase
         xrt: begin 
             xrt_prep,index,data,oindex,odata
             if quicklook then oindex=xrt_kludge_pointing(oindex)
         endcase
         sp: begin 
            box_message,'SP...
            sot_iquv_3d, index,data,oindex,sdata 
            scaleit=0
         endcase
         else: begin 
            box_message,'Non FG...'
            oindex=index
            odata=data-80 ; !! TODO?
         endcase
      endcase
      if data_chk(oindex,/struct) then begin 
      if xrt then sdata=bytscl(ssw_sigscale(oindex,odata, $ 
              log=(oindex(0).EC_FW2_ ne 'Gband'))) else $
          if scaleit then sdata=bytscl(ssw_sigscale(oindex,odata))
      dxy=float([index(0).naxis1,index(0).naxis2])
      factor=min(1./(dxy/max_xy))
      outsize=factor*dxy
      mname=str_replace(strcompress(get_infox(cat(ss(0)),'obsdir,wave,naxis1,naxis2')),' ','_')
      tittags=(['obsdir,wave','obsdir,ec_fw1_,ec_fw2_'])(xrt)
      title=get_infox(cat(ss(0)),tittags) + ' ,' + $
         arr2str(string(dxy,format='(I5)'),' x ')
      labels=mname+'_'+anytim(index.date_obs,/ecs,/trunc)
      mname=mname+'_'+time2file(index(0).date_obs,/second)
      mnames(m)=mname
if debug then stop,'mname,index,sdata' 
      contx=keyword_set(context) or keyword_set(fov_context) or $
         keyword_set(size_context)

      if contx then begin
          fdisk=oindex(0).fovx gt 2000 and oindex(0).fovy gt 2000 ; XRT fullD?
          deffov=[([15,35])(fdisk),([25,35])(fdisk),35]
          defsiz=[800,180,120]
          if n_elements(size_context) eq 0 then size_context=defsiz
          if n_elements(fov_context) eq 0 then fov_context=deffov
          cnames=mname+'_context_'+string(defsiz,format='(i4.4)')+'.gif'
          ssw_file_delete,concat_dir(movie_dir,cnames)
          ct2rgb,0,rr,gg,bb,gamma=.8
          amatch=''
          if n_elements(nimg gt max_frames) then $
            amatch=struct2ssw(allmatches,/nopoint) ; show ommited cadence
          for ci=0,1 do begin 
             cimg=hinode_fov_context(oindex,sdata,margin=.05,charsize=.7,$
             oplotnar=(ci eq 0), fov=fov_context(ci),xsize=size_context(ci), $
             r=rr,g=gg,b=bb, offset=50,/limb,grid=([15,30])(ci gt 0) , $
             xrt=(abs(ssw_deltat(reltime(/now),ref=index(0).date_obs)) gt 30), $
             debug=debug, gcolor=120,/goes,/extremes, $
             all_fov=amatch)
             if n_elements(cimg) eq 1 then box_message,'bad context??' else $
                write_gif,concat_dir(movie_dir,cnames(ci)),byte(cimg),rr,gg,bb 
          endfor
          
      endif
      special_movie,index.date_obs,sdata,movie_name=mname,movie_dir=movie_dir, $
         _extra=_extra,html=html,/inctimes, $ ;thumbsize=[.2*index(0).naxis1,.2*index(0).naxis2],$
         outsize=outsize , labels=labels, thumbsize=150, framethumb=-1, $
         context=cnames, maxxy=150
      file_append,mhtml,'<h3> <font color=orange>'+title + '</font></h3>
      file_append,mhtml,'<em>(Total of ' + strtrim(nimg) + $
         ' frames like this in time range)</em>'
      file_append,mhtml,str2html_anchor(mname,'',/drop_anchor)  ; drop html anchor
      file_append,mhtml,html
      mok(m)=1
      murls=http_names(concat_dir(movie_dir,mnames))
      subcat=str_subset(cat(ss(0)),$
      'naxis1,naxis2,xcen,ycen,fovx,fovy, date_obs,wave,waveid,obsdir,prog_no')
      mstat=ssw_modeinfo(allmatches,cat(ss),umode=title(0))
      mstr=join_struct(mstat,subcat)
      if tag_exist(mstr,'wave') and tag_exist(mstr,'wavelnth') then $
             mstr.wavelnth=mstr.wave
      mroot=concat_dir(movie_dir,mnames(m))
      mexts=str2arr('.html,_j.html,_g.gif,_m.mpg,_j_micon.gif,_j_mthumb.gif')
      murl_tags='url_'+ $
         str2arr('mparent,javascript,gifanim,mpeg,micon,mthumb')
      murls=str_replace(mroot+mexts,topwww_path,topwww_http)
      for mi=0,n_elements(murl_tags)-1 do begin 
         ii=tag_index(mstr,murl_tags(mi))
         if ii ne -1 then mstr.(ii)=murls(mi)         
      endfor
      mstr.url_thumb=str_replace(mstr.url_mthumb,'mthumb','fthumb') ; single frame thumbnails
      if contx then begin 
         conff=concat_dir(movie_dir,cnames)
         if file_exist(conff(0)) then begin 
            mstr.url_context_thumb=str_replace(conff(1),topwww_path,topwww_http)
            mstr.url_context=str_replace(conff(0),topwww_path,topwww_http)
          endif
      endif
      if n_elements(allmstrs) eq 0 then allmstrs=mstr else $
         allmstrs=[allmstrs,mstr]
      endif else box_message,'No VALID FRAMES??' 
if data_chk(allmstrs,/struct) then begin 
; save movie info for indexing/event externalization
at0=allmstrs.start_time
at1=allmstrs.stop_time
atimes=[at0,at1]
atimes=atimes(sort(atimes))
time_window,atimes,mt0,mt1,out='ccsds'
parenturl=str_replace(mhtml,topwww_path,topwww_http)
mstruct={eventid:'',creation_time:'', $
   telescop:gt_tagval(index(0),/telescop,missing=''), $
   instrume:gt_tagval(index(0),/instrume,missing=''), $
   url_parent:parenturl, $
   search_start:anytim(time0,/ccsds),search_stop:anytim(time1,/ccsds), $
   prog_start:mt0 ,prog_stop:mt1, movie_info:ssw_struct_byte2int(allmstrs)}
mstruct.creation_time=reltime(/now,out_style='CCSDS')
mstruct.eventid='VOEvent_'+event_type+(['S','X'])(xrt) + anytim(mt0,/ccsds) + '.xml'
savegenx,file=indexgeny,mstruct,/over
if make_voevent then begin
   box_message,'Generating VOEvent XML...'
   oldvoe=file_search(movie_dir,'VOE*.xml')
   if oldvoe(0) ne '' then begin 
      box_message,'Removing existing VOEvent files...'
      ssw_file_delete,oldvoe
   endif
   mk_voe_obs,mstruct,outdir=movie_dir,/write, $
     utility=keyword_set(voevent_movies)
endif
endif
   endif else box_message,'MIN FRAMES criteria not met for ' + umodes(m)
   endif else box_message,"skipping unknown mode"
endfor
file_append,mhtml,hinode_credits(/html) ; add Hinode-wide credits
html_doc,mhtml,/trailer
;

file_append,index_html,rd_tfile(mhtml),/new


if n_elements(phttp) gt 0 then begin ; restore environment
   set_logenv,'path_http',phttp
   set_logenv,'top_http',thttp
endif

return
end





