pro sxt2file,  index,  data, r, g, b, infil=infil, ss=ss,         $
   prefix=prefix, logfile=logfile, description=description,       $
   currentcolor=currentcolor,					  $
   outsize=outsize, outdir=outdir, $
   replace=replace, fits=fits, gif=gif, jpeg=jpeg, tiff=tiff, pict=pict, $
   red=red, green=green, blue=blue, quality=quality, loud=loud,		 $
   newfiles=outfils, mag_fact=mag_fact, goes=goes
;+
;   Name: sxt2file
;
;   Purpose: Convert an SXT image file to a standard format (fits/jpeg/gif/tiff)
;
;   Input Parameters:
;      index - SXT Index record(s)
;      data  - SXT image(s)
;      r,g,b - if permitted by output format, optional 8bit color table values
;
;   Keyword Parameters:
;      infil - If supplied, read from SDA file to get INDEX and DATA
;      ss - (used with infil option only)  - only process these file images
;      outsize - if set, image will be "congridded" to this size
;      mag_fact - if set, magnification factor (instead of outsize)
;      outdir - output directory (default is apprpriate WWW image area)
;      replace - if set, overwrite existing file 
;      fits - if set, output files are FITS format
;      gif  - if set, output files are GIF format
;      jpeg - if set, output files are JPEG format
;      tiff - if set, output files are TIFF format
;      pict - if set, output files are PICT format
;      quality - optional quality (JPEG only)
;      currentcolor - switch, if set, use current R,G,B values
;      red/green/blue - optional color table values (3x256 bytes)
;      prefix - if set, output file prefix name (default='sxt')
;      goes (input) switch, if set, merge GOES lightcure/timeline w/imag

;   Calling Sequence:
;      sxt2file, index, data, [r,g,b, /gif,/tiff,/jpeg,/fits, outsize=outsize]
;      sxt2file, infil=infil, /gif,/tiff,/jpeg,/fits, red=red,blue=blue,green=green
;
;   Calling Examples:
;      sxtfile, index, data, /gif, outsize=256
;      sxtfile, infil='$DIR_SXT_SFM/sfm950300.0000', /jpeg, quality=25
;   
;   Notes:
;      Makes one file per SXT image - output file name is:
;         PREyymmdd.hhmm.XXX  (PRE=user supplied prefix, default='sxt')
;                             (XXX=gif/fits/tiff/jpeg/pict)
;
;      If r,g,b postional or RED,GREEN,BLUE keywords  are not specified then:
;         switch /CURRENTCOLOR - will use current color table
;	  otherwise, a default RED greyscale table is assigned
;	  (original color is restored prior to return)
; 
;      If OUTDIR not specified, looks under WWW area (environ "path_http")
;      for         1) ../im*g*/XXX   (ex: ../images/gif, ../img/fits)
;		   2) ../im*g*	     (ex: ../img, ../image, /images)
;      If OUTDIR and $path_http not defined, uses current directory
;
;   Restrictions:
;      TODO: Update FITS header if outsize specified
;
;   History:
;      22-Sep-1995 (SLF) - simplify WWW and other file interchange work
;      20-oct-1995 (SLF) - add PICT keyword and function
;      25-oct-1995 (SLF) - add LOG and PREFIX keywords and function
;      13-nov-1995 (SLF) - add MAG_FACT keyword 
;-

; ------------ allow optional SDA file input ----------------
readit=keyword_set(infil)
if readit and n_params() eq 0 then begin
   if not file_exist(infil) then begin
      message,/info,"Cannot find input file: " + infil
      return
   endif
   rd_sda, infil,-1, index,/nodata			    ; get index array
endif
if not keyword_set(ss) then ss=lindgen(n_elements(index))
; --------------------------------------------------------

; ----------- Verify SXT INDEX structures ---------------
if not data_chk(index,/struct) then begin
   message,/info,"Need an SXT INDEX record and image..."
   return
endif
; only sxt index&data allowed
if total(is_member(['sxt','gen'],tag_names(index),/ignore)) ne 2 then begin
   message,/info,"Need an SXT INDEX record and image..."
   return
endif
; --------------------------------------------------------

; ----- Define Color Table Variables (R,G,B)  ------------
if keyword_set(red)   then r=red
if keyword_set(green) then g=green
if keyword_set(blue)  then b=blue

if not keyword_set(b) and is_member(!d.name,['x','z'],/ignore) then begin
   tvlct,r,g,b,/get			; current color table
   tvlct,rr,gg,bb,/get			; save a copy 
   if not keyword_set(currentcolor) then begin
      loadct,3,/silent			; load a default table
      stretch,255,0,.8
      tvlct,r,g,b,/get			; store new (red) color table
      tvlct,rr,gg,bb			; restore callers color table
   endif
endif
; ---------------------------------------------------------

; ---- Extension Dependencies (define execute statement) -----
case 1 of
   keyword_set(fits): begin
      extension='.fits'
      write_string="sxt2fits, index, data, outfil=outfils(i), outdir=outdir,/quiet"      
   endcase
   keyword_set(jpeg): begin
      if not since_version('3.6') then begin
         message,/info,"JPEG not available - Need IDL version > 3.6"
         return		;******* unstructured exit ************
      endif
      extension='.jpeg'
      if not keyword_set(quality) then quality=75
      write_string="write_jpeg,outfil,image,quality=quality"
   endcase
   keyword_set(tiff): begin
      extension='.tiff'
      write_string="tiff_write,outfil,image,red=r,blue=b,green=g"
   endcase
   keyword_set(pict): begin
      extension='.pict'
      write_string='write_pict,outfil,image,r,g,b
   endcase
else: begin
      extension='.gif'
      write_string="write_gif,outfil,image,r,g,b"
   endcase
endcase

; ----------- define output directory if not specified --------
if not keyword_set(outdir) then begin
   outdir=get_logenv('path_http')		; top level WWW
   if outdir eq '' then outdir=curdir() else begin
      outdirs=get_subdirs(outdir)			; more appropriat subdirectory?
      ssdir=wc_where(outdirs,'*'+str_replace(extension,'.','')+'*',cnt)
      if cnt eq 0 then ssdir=wc_where(outdirs,'*im*g*',cnt)
      if cnt gt 0 then outdir=outdirs(ssdir(0))
   endelse
endif
; --------------------------------------------------------------
; ----------------- derive output file name -----------------------
if not keyword_set(prefix) then prefix='sxt'
outfils=prefix + ex2fid(anytim2ex(index(ss)),/sec) + extension
outnames=concat_dir(outdir,outfils)
; --------------------------------------------------------------
;

; ---------------------- Image Resizing? -----------------------
case 1 of 
   keyword_set(mag_fact): $				; base size on 1st image
      newsize = [gt_shape_cmd(index(0),/x)*mag_fact,  $  ; scale by MAG_SIZE
	        gt_shape_cmd(index(0),/y)*mag_fact]
   n_elements(outsize) eq 1: $				; outsize=xsize
      newsize=  [outsize, $				; (scale y accordingly)
                gt_shape_cmd(index(0),/y) * $
                (float(outsize)/gt_shape_cmd(index(0),/x))]
   n_elements(outsize) eq 2: newsize=outsize		; nx,ny passed
   else:
endcase
rebinit=keyword_set(newsize)
; --------------------------------------------------------------

loud=keyword_set(loud)
noreplace=1-keyword_set(replace)


; merge GOES lightcurve/timeline on request (size=newsize(0),.5*newsize(0))
goes=keyword_set(goes)
if keyword_set(goes) then begin
;  make the GOES plot movie via <event_movie>
   event_movie,index, outgoes, /goes,outsize=newsize*[1.,.5], $
	/ticks, /default
   tvlct,r,g,b,/get
endif


; ------------ Image / File generation Loop -------------------
status=''
wstatus=bytarr(n_elements(ss))
for i=0, n_elements(ss)-1 do begin
   outfil=outnames(i)
;  Check for pre-existin file...
   if file_exist(outfil) and noreplace then begin
      mess=["File" + outfil + $
            " exists - use /REPLACE to overwrite (Nothing saved...)"]
   endif else begin
      if readit then rd_sda,infil,ss(i),ind,image else $  ; File input option
         image=data(*,*,i)
      if rebinit then $
         image=congrid(image,newsize(0),newsize(1) )	; resize image?
      if goes then begin
         image=bytscl(image,top=!d.table_size-14)+16	; scale to top of table
         image=byte([[image],[outgoes(*,*,i)]])		; concatentate w/GOES
         image(*,newsize(1))=200
      endif
      if loud then $					; diagnostic
         message,/info,"Executing: " + write_string
      exestat=execute(write_string)			; WRITE via execute
      mess="Wrote File: " + outfil
      wstatus(i)=exestat                                ; successful write?
   endelse
   status=[status,mess]
   prstr,mess
endfor							; all images done
; --------------------------------------------------------------

status=status(1:*)
; generate a log file on request (genx file)
if keyword_set(logfile) then begin
   if data_chk(logfile,/string) then lfile=logfile else begin
      lfile='sxt2file_' + ex2fid(ut_time(/ex))
       odir=concat_dir(get_logenv('path_http'),'logs')
       if not file_exist(odir) then $
          odir=get_logenv('DIR_SITE_LOGS')
   endelse
   if data_chk(infile,/string) then $
      type="File Input: " + infil else type="Index/Data " 
  if n_elements(quality) eq 0 then qual="N/A" else qual=strtrim(quality,2)
  pr_status,head,header="SXT2FILE LOG FILE", caller='sxt2file.pro'
  desc=[head, type,                                                $
             "Output Size = " + fmt_tag(size(image)),              $
	     "Quality = " + qual,                                  $
	     "Logfile = "+ str_replace(lfile,'genx','') + "genx" ]
   
   udesc="No user supplied text description"
   case 1 of 
      n_elements(description) eq 0: 
      file_exist(description(0)): udesc=rd_tfile(description)
      data_chk(description,/string): udesc=description
      else:
   endcase
   desc=[desc,udesc]
   savegen,file=concat_dir(odir,lfile), text=desc, $
      index, outdir, outfils,  r, g, b, status, wstatus, $
         names=['index,outdir,outfiles,r,g,b, status, wstatus']  
endif   
return
end
