pro trace_idlcat, qfile=qfile, debug=debug
;+
;   Name: trace_idlcat
;
;   Purpose: WWW interface to trace catalog search utilities(IDL)
;
;   Keyword Parameters:
;      qfile - WWW Post Query filename  
;  
;   History:
;      2-Feb-1998 - S.L.Freeland 
;     21-Apr-1998 - S.L.Freeland - use the real TRACE catalog
;     24-Apr-1998 - S.L.Freeland - add some pointing XCEN/YCEN
;      8-May-1998 - (FZ)  Removed link from itable header
;     17-May-1998 - S.L.Freeland - add MERGE_LIST and RANGE_LIST to
;                   <form_qstr_valid> call   
;     19-May-1998 - S.L.Freeland - added OLIMIT and cgi hook to order FORM
;     26-May-1998 - S.L.Freeland - add some informational HTML
;     11-Jun-1998 - S.L.Freeland - Flag bad JPEG decodes & inhibit hyperlinks
;                                  (NX=NY=1)
;
;     20-Jan-1999 - S.L.Freeland - add PERCENTD (data qual) to output list
;     29-Jan-1999 - S.L.Freeland - expanded jpeg size
;     29-Feb-2000 - S.L.Freeland - disable common, limit time range
;-
;common trace_idlcat_blk, catalog, seconds
debug=keyword_set(debug)

;configure_http,/trace                     ; set WWW defaults to TRACE
set_logenv,'path_http','/archive/ssw'
set_logenv,'top_http','http://www.lmsal.com/solarsoft'

;if n_elements(catalog) eq 0 then begin    ; initialize
;  trace_cat, x0, x1, catalog,/fast
;  seconds=int2secarr(catalog)
;endif

box_message,'Running trace_idlcat...'

; --------------- read and decode the FORM input -----------
break_file,qfile,log,paths,qfil,qver,qext
qfile=concat_dir(concat_dir(get_logenv('path_http'),'text_client'),qfil+qver+qext)
outfil=qfile + '.text'
qstr=url_decode(qfile=qfile)
strtext=str2cols(str_help(qstr,/nobox),':')
; --------------- -----------------------------------------

; ----------  derive HTML output document ---------------------
htmlfile=str_replace(outfil,'text','html')

mess=['TRACE_IDLCAT:  run at ' + systime(), $
      'Query File: ' + strrep_logenv(qfile,'path_http')] ;, $
;      'HTML  File: ' + strrep_logenv(htmlfile,'path_http'), $
;      'HTML  URL:  ' + http_names(htmlfile)]
; ------------------------------------------------

prstr,mess,/nomore

; ------- extract start and stop times and do some sanity checks ------
startt=url_query2time(qstr,/start,/nodef)
stopt =url_query2time(qstr,/stop,/nodef)
adjust_times, startt, stopt, attext, status=atstatus, maxdays=15
trace_cat, startt, stopt, catalog
seconds=int2secarr(catalog)

; -----------------------------------------

; --------- quick filter on times -----------
if debug then stop
usecs=int2secarr(anytim([startt,stopt],out='ints'),catalog(0))
sstime=where( (seconds ge usecs(0) ) and (seconds le usecs(1)),tcount)
; -----------------------------------------

; ------------- start a catalog parameter file ------------
conffile=qfile+'.search'
file_append,conffile,'; '+ mess,/new
file_append,conffile,'; '+ ['start_time: ' + startt(0), $
		                'stop_time:  ' + stopt(0)]
; ---------------------------------------------------------

ocount=tcount                                 ; default to all time matches
testmode=tag_index(qstr,'test_mode') ne -1
; ------------------ filter on everything else ------------------

if tcount gt 0 then begin
  form_qstr_valid, qstr, tag, value, count, confarr=confarr, gtarr=gtarr, $
	    merge_list='wave_len', range_list=['xcen,ewfov','ycen,nsfov']
  if count gt 0 then begin
     file_append, conffile, confarr
     if not testmode then begin 
       ss=trace_where(catalog(sstime),ocount,conf_file=conffile)  
        omess="Number of images matching other criteria: " + strtrim(ocount,2)
        if ocount gt 0 then ss=sstime(ss)
      endif else begin
        confarr=[['Query Value',confarr], ['IDL Search',gtarr]]
        confarr=strtab2html(transpose(confarr),/left,/row0)
        omess="<b><em>TEST MODE ENABLED</em></b> suppressing auxilary searches"
        ss=sstime
     endelse
     
endif else begin
     omess="[All other search parameters were NOPS]"
     ss=sstime
   endelse
endif else omess="[No images match your criteria]"
; -----------------------------------------

; ----------- call listing routine w/optional html select --------
llimit=100               ; live html listing limit
olimit=1000               ; image order limit

taglist='wave_len,naxis1,naxis2,img_min,img_max,img_avg,img_dev,xcen,ycen,sht_mdur,obs_prog,percentd,comp_code,image_ss'
header=str2arr('DATE,TIME,WAVE,NX,NY,MIN,MAX,AVG,DEV,XCEN,YCEN,EXP,OBS_PROG,QUAL%,JPEG?,IMAGE#',/nomult)
format='   a7,     i4,    i4,    f7.1,   f7.1,   f7.1,    f7.1,   f6.1, f6.1, f5.1, a20,   f4.0, i3, i5'

if ocount gt 0 then begin
  lss=ss(0:ocount<llimit-1)
  oss=ss(0:ocount<olimit-1)
  ilist=get_infox(catalog(oss), fmt_tim='ecs', $
	   taglist, format=format)
   ilist=str2cols(ilist)
   hflist=trace_struct2filename(catalog(oss),/hourly)
   dslist=string(gt_tagval(catalog(oss),/image_ss),format='(i4.4)')
   cgilookup='<a href="/cgi-bin/trace_get1www_image.sh?' + $
	      [hflist+'_'+dslist]+'">' + reform(ilist(0,*)) + '</a>'
;  ----------- FLAG bad JPEG decodes and inhibit hyperlinks for those ------
   nxny=catalog(oss).naxis1 gt 1 and catalog(oss).naxis2 gt 1
   oknxny=where(nxny, okcnt)
   badnxny=where(1-nxny,badcnt)
   if okcnt gt 0 then ilist(0,oknxny)=cgilookup(oknxny)  ; add hyperlinks
   if badcnt gt 0 then begin
       ilist(3,badnxny) ='<font color=red>'+ reform(ilist(3,badnxny)) +'</font>'
       ilist(4,badnxny) ='<font color=red>'+ reform(ilist(4,badnxny)) +'</font>'
   endif
   llist=[[header],[ilist(*,0:ocount<llimit-1)]]
   itable=strtab2html(llist,/row0)
   if ocount gt llimit then itable=[ $
       '<p><b><em><font color=red>Listing truncated to first  '+ strtrim(llimit,2)+ ' matches</font><p>',itable]
endif

; ---------------- generate html output -------------------
html_doc,htmlfile,/header
file_append,htmlfile,'<p><b>'+mess+'</b>
file_append,htmlfile,"<p>Search Times: " + startt + ' <em> to </em> ' + stopt
file_append,htmlfile,"<p>Number of images within time range: " + strtrim(tcount,2)
if not atstatus then file_append,htmlfile,'<p><em>'+attext+'</em>'

if n_elements(confarr) gt 0 then begin
if testmode then file_append, htmlfile, $
    ["<p>Auxilary Search Parameters",confarr] else $ 
    file_append, htmlfile, strtab2html(transpose(["Auxilary search criteria...",confarr]))
endif

if ocount gt 0 then begin
   if ocount le olimit then begin
      sfile=str_replace(conffile,'search','success')
      box_message,'Success file: ' + sfile
      file_append,sfile,';' + rd_tfile(conffile)   
      help,dslist,hflist
      file_append,sfile,temporary(strjustify(hflist)) + ' ' + temporary(dslist)
      omess=[omess+'<em><a href="/cgi-bin/trace_order_data.sh?' + $
	  sfile+'">&#32 &#32 <b> Order all images<b></a><em>']
   endif else begin
      omess=[omess + '<font color=blue><em> &#32 &#32 <b>', $
	     'Number of matches exceeds full image order limit of ('+ $
	     strtrim(olimit,2) +') </b></em></font>']
   endelse
endif  

file_append,htmlfile,"<p>"+omess

if ocount gt 0 then begin
  file_append,htmlfile, ['<p>Individual hyper-links in column 1 generate a ',$
    'summary page including a scaled and reduced GIF image and link to the full resolution FITs image', $
    ' (<em>on-the-fly</em>, so will take a few seconds)']	       
  file_append,htmlfile, itable    ; image listing
endif

file_append, htmlfile,['<p><em>This HTML generated by <b>trace_idlcat.pro</b> ',$
   ' ,S.L.Freeland, Last Revision: 27-May-1998, <br>and running under the ', $
   '  <a href="http://www.lmsal.com/solarsoft/">SolarSoft </a> environment.', $
    ' Problems or suggestions? <a href="mailto:freeland@sxt1.lmsal.com">freeland@sxt1.lmsal.com<a>']

html_doc,htmlfile,/trailer
; ----------------------------------------------------------------
box_message,['URL:',http_names(htmlfile)]

if debug then stop

return
end

