; Copyright (c) 1998-2005 A.P. Hitchcock  All rights reserved
; Copyright (c) 1995, ALS SpectroMicroscopy Facility, er, jdd
;+
;NAME: WIN2TIF
;
;LAST CHANGED: ----------------------------------- 02-dec-05 (aph)
;
; PURPOSE:
;   This function reads contents of WNUM graphics window
; into a TIFF file
;
; CATEGORY: graphics utility; standalone
;
; CALLING SEQUENCE:
;   RESULT = WIN2TIF, FileName
;
; INPUTS:
; WNUM  number of window to read (optional; current window is default)
;    wnum is specified either as number
;    or as a 5-element array [num, x0, y0, xwid, ywid] for a subset of the window
;
; KEYWORDS: none
;
; OUTPUTS: none
;
; COMMON BLOCKS: none
;
; fct READWIN [, wnum]  -- read window into bytscal array
;
; MODIFICATION HISTORY:
; (30-nov-00 cgz) Separated from WINDOW.PRO
; (04-jan-01 cgz) Migrated READWIN from WINDOWS.PRO
; (12-mar-03 aph) get to read 3-color from true color display; tiff_write (IDL$) => write_tiff (idl5)
; (02-dec-05 aph) flip image for IDL after 6.0
;-
;;;;;;;

function READWIN, wnum
;------------- aph (12-mar-03) - attempt to get write to work using /true parameter in tvrd
; -------------------------------- caution, may only work in 5.2 and higher
on_error, 2
owin=!d.window
if n_elements(wnum) eq 0 then wnum=!d.window
wset, wnum(0)
wshow, wnum(0)   ;send to front if partially hidden
if n_elements(wnum) eq 1 then $
   im=tvrd(/true) $
else $
   im=tvrd( wnum(1), wnum(2), wnum(3), wnum(4),/true )
wset, owin
wshow, owin
return, im
end
;;;;;;;;;
pro WIN2TIF, file, wnum, WIN=win, GRAY=gray
;-------------------------------------
;saves window (see readWin for details) to a tiff file, including colors
;UNIX:  xv changes white(255) to be 254  (doesn't do this for gif files)
COMMON COLORS, r_orig, g_orig, b_orig, r_curr, g_curr, b_curr
dummy=ct_luminance() ;put current pallette into common block
on_error, 2
if n_elements(file) eq 0 then begin
   gpath=''
   file=PICKFILE(FILE='*.tif', FILTER='*.tif', /FIX_FILTER, $
     TITLE='Input file name (w/o path)', GET_PATH=gpath )
   file=gpath+file
endif
file=strlowcase(file)
if (strpos(file,'.') eq -1) then file=file+'.tif'
if keyword_set(win) then wnum=win
imag=readwin(wnum)     ; get 3-dimension image (R,G,B as separate channels)
if float(!version.release) GT 6. then $
    imag=REVERSE(imag, 3)  ; flip image upside down
sz=size(imag)
if keyword_set(gray) eq 1 then $
  WRITE_TIFF, file, imag, 1 $
else $
  WRITE_TIFF, file, imag           ; , r=r_curr, g=g_curr, b=b_curr, 1
;print, 'Saved: ', file, ' (',num2str(sz(1),'i4'),'x',num2str(sz(2),'i4'),')'
print, 'Saved: ', file, ' (',strtrim(string(sz(1),format='(i4)'),2),'x', $
                 strtrim(string(sz(2),format='(i4)'),2),')'
end
