;+
; Project     :	SOHO - CDS
;
; Name        :	CDS_THUMBNAIL
;
; Purpose     :	Makes a thumbnail sketch of images from a CDS study.
;
; Category    :	CDS, Class3, Quicklook
;
; Explanation :	This procedure creates a 128x128 GIF thumbnail image from a CDS
;               observation.  The software first tries to find one of a number
;               of preferred wavelengths to form the image from.  If it can't
;               find a preferred wavelength, it uses the first window.  If it
;               can't form an image, it makes a simple plot.
;
; Syntax      :	CDS_THUMBNAIL, FILENAME  [, OUTFILE ]
;		CDS_THUMBNAIL, DATA      [, OUTFILE ]
;
; Examples    :	CDS_THUMBNAIL, 's3042r00.fits'
;
;		A = READCDSFITS('s3042r00.fits')
;		CDS_THUMBNAIL, A
;
; Inputs      :	FILENAME = Name of CDS FITS file to read in.
;
; Opt. Inputs :	DATA	 = A quicklook data structure as returned by
;			   READCDSFITS.
;
;               OUTFILE  = The name of the output file.  The default extension
;                          is ".gif".  If not passed, the name is formed from
;                          the name stored in the FITS header, with "_tn.gif"
;                          appended.
;
; Outputs     :	The thumbnail is written to a GIF file.
;
; Opt. Outputs:	None.
;
; Keywords    :	OUTPATH = The path to write the GIF file.  The default is to
;                         write it in the current directory.
;
;               ERRMSG = If defined and passed, then any error messages will be
;			 returned to the user in this parameter rather than
;			 depending on the MESSAGE routine in IDL.  If no errors
;			 are encountered, then a null string is returned.  In
;			 order to use this feature, ERRMSG must be defined
;			 first, e.g.
;
;				ERRMSG = ''
;				CDS_THUMBNAIL, INPUT, ERRMSG=ERRMSG
;				IF ERRMSG NE '' THEN ...
;
; Calls       :	DATATYPE, READCDSFITS, GT_WINDATA, GT_WINDESC, AVERAGE,
;		CDS_CLEAN_IMAGE, SIGRANGE, SETPLOT, TVREAD, BREAK_FILE,
;               FORM_FILENAME, SSW_WRITE_GIF
;
; Common      :	None.
;
; Restrictions:	Can only be used for rasters which build up images via mirror
;		(and slit for GIS) movements.  Otherwise, average spectra are
;		shown.
;
; Side effects:	None.
;
; Prev. Hist. :	Partially based on CDS_SNAPSHOT
;
; History     :	Version 1, 01-Jul-2005, William Thompson, GSFC
;
; Contact     :	WTHOMPSON
;-
;
pro cds_thumbnail, input, outfile, errmsg=errmsg, outpath=outpath
;
on_error, 2
wavepref_nis = [584.3, 629.7, 554.5, 607.6, 609.8, 537.0, 599.6, 625.0, $
                368.1, 520.7, 335.0, 361.0]
;
;  Check the number of parameters passed.
;
if n_params() lt 1 then begin
    message = 'Syntax:  CDS_THUMBNAIL, FILENAME or CDS_THUMBNAIL, DATA'
    goto, handle_error
endif
;
;  Determine whether to plot images or spectra.  Could be overridden below.
;
do_spectra = 0
;
;  If a data structure was passed, then use it.  Otherwise, read the fits file
;  whose name was passed.
;
if datatype(input,1) eq 'Structure' then begin
    a = input
end else begin
    if datatype(input,1) ne 'String' then begin
        message = 'INPUT must be either a structure or a character string'
        goto, handle_error
    endif
;
    a = readcdsfits(input)
    if datatype(a,1) ne 'Structure' then begin
        message ='Unable to read FITS file ' + input
        goto, handle_error
    endif
endelse
;
;  Extract the number of windows from the data structure.
;
n_windows = n_elements(a.detdesc)
windows = indgen(n_windows)
;
;  Filter out those windows which don't exist.
;
ixstop = a.detdesc.ixstop
w_valid = where(ixstop(0,windows) ge 0, count)
if count gt 0 then begin
    windows  = windows(w_valid)
    n_windows = n_elements(windows)
end else begin
    message = 'No windows to display'
    goto, handle_error
endelse
;
;  Get the wavelength ranges, and determine which window to process.
;
wavemin = a.detdesc[windows].wavemin
wavemax = a.detdesc[windows].wavemax
i = 0
if a.header.detector eq 'NIS' then begin
    wavepref = wavepref_nis
    repeat begin
        w = (where((wavepref[i] ge wavemin) and (wavepref[i] le wavemax)))[0]
        i = i + 1
    endrep until (w ge 0) or (i eq n_elements(wavepref))
    if w lt 0 then begin
        window = windows[0]
        wave = wavepref[i]
    end else begin
        window = windows[w]
        wave = wavepref[i-1]
        print, 'Selected wavelength', wave
    endelse
end else begin                  ;GIS
    window = windows[0]
    wave = 0
endelse
;
;  make sure that the image is big enough to display.
;
aa = gt_windata(a,window)
dd = gt_windesc(a,window)
sz = size(aa)
if sz[0] lt 3 then do_spectra = 1
if ((sz[2] lt 5) or (sz[3] lt 5)) and (a.header.slit_num ne 6) then $
  do_spectra = 1
;
;  Use the Z-buffer.
;
current_device = !d.name
setplot,'z'
device,set_resolution=[128,128]
;
ww = dd.origin[0] + indgen(sz[1])*dd.spacing[0]
if do_spectra then begin
    aa = reform(aa)
    sz = size(aa)
    while sz[0] gt 1 do begin
        aa = average(aa, 2, missing=dd.missing)
        sz = size(aa)
    endwhile
    plot, ww, aa, xmargin=[0,0], ymargin=[0,0], /ynozero
end else begin
    load_red
    if a.header.slit_num eq 6 then begin
        if sz[0] eq 4 then aa = average(aa, 4, missing=dd.missing)
        aa = average(aa, 2, missing=dd.missing)
        exptv, sigrange(aa), /nobox, /noexact
    end else begin
        w1 = min(where(ww ge wave-1))
        w2 = max(where(ww le wave+1))
        if (w1 lt 0) or (w2 lt 0) then $
          aa = average(aa,1,missing=dd.missing) else $
          aa = average(aa[w1:w2,*,*], 1, missing=dd.missing)
        cds_clean_image, aa, /nomissing
        exptv, sigrange(aa), scale=abs(dd.spacing[1:2]), /adjust, /nobox, $
          /noexact
    endelse
endelse
;
;  Read in the thumbnail, and form the output filename.
;
b = tvread()
if n_elements(outfile) eq 1 then name = outfile else begin
    break_file, a.header.filename, disk, dir, name
    name = name + '_tn'
endelse
name = form_filename(name, '.gif', directory=outpath)
ssw_write_gif, name, b
print, 'Wrote file ' + name
;
;  Reset the plotting device, and return.
;
setplot, current_device
return
;
;  error handling point.
;
handle_error:
if n_elements(errmsg) ne 0 then errmsg = 'CDS_THUMBNAIL: ' + message else $
  for i=0,n_elements(message)-1 do message, message[i], /continue
;
end
