;+
; $Id: generic_movie.pro,v 1.97 2013/07/08 13:38:10 mcnutt Exp $
; Project     : SOHO - LASCO/EIT, STEREO - SECCHI
;                   
; Name        : GENERIC_MOVIE
;               
; Purpose     : Load various data formats into pixmaps and call (scc_)PLAYMOVIE for animation.
;               
; Explanation : This procedure is a generic interface to converting data
;		(image files or data cubes) into the LASCO MVI format.
;		The user can then save the movie in MVI format and use
;		routines such as wrunmovie.pro, combine_mvi.pro, mvi2mpg.pro, 
;		put_mvi.pro etc. for MVI manipulation.
;               
; Use         : GENERIC_MOVIE, data[, bmin, bmax], /SXT, /MK3, /TRUECOLOR
;
; Inputs      : data : can be:
;		       - 3 dimensional byte array (nx,ny,len)
;		       - name of file containing names of images
;		       - strarr of names of images [number of frames, number of columns, number of rows]
;		    	(images can be of type: .fits, .gif, .pict, .tiff)
;
; Optional Inputs: bmin, bmax : Minimum and maximum DN for BYTSCL. 
;   	    	If not supplied for non-byte data, select_bytscl() is called.
;               
; Outputs     : None.
;               
; Keywords    : 
;	/SXT	: Data is YOHKOH/SXT FITS files.
;	/MK3    : Data is Mauna-Loa Mark3 Coronagraph rpb files.
;       /PICT   : Data are PICT files
;	PAN=.5  : Resize to half
;	LABELS=	; Set equal to array of labels to put in lower left corner of frames
;	/RDIFF	: Do running difference movie (or pass as RDIFF=n to subtract images n frames apart)
;	/TRUECOLOR  ; Set if images are true color
;   	/DOXCOLORS  ; Allow adjustment of color tables with 8-bit images on 24-bit display (uses RAM)
;   	/TIMES	:   Put timestamp on each frame
;   	/DEBUG  : Print info about each frame header (if FITS)
;   	SAVE=	:name of file to save resulting mvi to; for batch execution
;   	HDRS=	: set equal to array of header structures corresponding to input
;   	NOHDRS=	: Will not generate headers for fits files.
;       MPEGNAME= : name of output mpeg movie will not call (scc_)wrunmovie used in SECCHI pipeline
;   	CHARSIZE=   pass to xyouts for label size (font=-1, charthick=2)
;       selscl  : OBSOLETE run select_bytscl to select bmin and bmax (first frame only) 
;   	LCOLOR=	: color value [0..255] for LABEL or TIMES (or an array of LCOLORS of length=number of frames)
;   	Half = string or string array of (r or l)'s to indicate which side of image will be used in the frame
;   	/GRAYSCALE  Force call of read_jpeg to use /grayscale
;   	ROIFILES=   Filename list of save sets containing 1-D Region-of=interest subscripts for input image files;
;   	    	    If set, outline of ROI is drawn on each image
;       wcscombine= call wcs_combine to combine multiple images from different telescopes into one frame ie ['cor2','cor1','euvi']
;   	frametimes= a array of strings containing the time for each frame, used when the time info is not available from the image hdrs
;
; Calls       : scc_playmovie
;
; Side effects: Creates multiple pixmaps.
;               
; Category    : Image Display/Animation.
;               
; See Also    : Wscc_MKMOVIE.PRO is a widget front-end to making LASCO/EIT movies.
;               
; Prev. Hist. : None.
;
; Written     : Scott Paswaters, NRL, 1996.
;
; $Log: generic_movie.pro,v $
; Revision 1.97  2013/07/08 13:38:10  mcnutt
; define first all_hdr when i eq 0 not by first to work with rdiff movies
;
; Revision 1.96  2013/07/05 17:22:39  mcnutt
; removed last correction
;
; Revision 1.95  2013/07/03 11:51:39  mcnutt
; changed all_hdr filename check to n_elements of all_hdr not to work with rdiff movies
;
; Revision 1.94  2012/09/13 21:25:46  nathan
; scale cdelt2 so sun center is correct
;
; Revision 1.93  2012/08/23 18:57:50  mcnutt
; added keyword definitions
;
; Revision 1.92  2012/08/08 19:40:26  nathan
; do not do grayscale jpg if pan=1
;
; Revision 1.91  2012/08/08 19:18:07  nathan
; set /clobber for sock_get
;
; Revision 1.90  2012/08/08 17:08:42  mcnutt
; defines file_hdr before calling scc_save_mvframe if not defined
;
; Revision 1.89  2012/07/26 12:26:58  mcnutt
; always sets ext2 for combined movie file name
;
; Revision 1.88  2012/07/20 12:32:31  mcnutt
; do not call get_sun_center if AIA
;
; Revision 1.87  2012/07/19 14:58:54  mcnutt
; check for sock_get status to be ge 1
;
; Revision 1.86  2012/07/17 19:41:22  nathan
; retry sock_get if it fails
;
; Revision 1.85  2012/07/17 19:01:00  mcnutt
; corrected error when downloading jpgs and pngs
;
; Revision 1.84  2012/07/17 16:43:56  mcnutt
; corrects AIA filenames if download from web
;
; Revision 1.83  2012/07/13 12:18:16  mcnutt
; deletes tmp sock_get file only if uname is defined
;
; Revision 1.82  2012/07/12 16:21:36  mcnutt
; write tmp web if to home dir
;
; Revision 1.81  2012/07/12 13:14:56  mcnutt
; added sock_get if name start with http: write tmp.ext
;
; Revision 1.80  2012/07/05 15:53:10  cooper
; can input array into LCOLOR
;
; Revision 1.79  2012/06/20 14:32:33  nathan
; in input is bytarr, no select_bytscl
;
; Revision 1.78  2012/06/14 20:11:57  nathan
; reset xcen/ycen for MVI header from FITS header
;
; Revision 1.77  2012/05/31 19:07:53  nathan
; change datecolor to 255 if mdnotbx lt 80 not 120
;
; Revision 1.76  2012/05/02 19:37:50  mcnutt
; sets hdr date obs and tel for wavelet files
;
; Revision 1.75  2012/04/02 20:32:36  nathan
; do convert2secchi first; add ROIFILES=
;
; Revision 1.74  2012/03/28 23:18:58  nathan
; Fix /times
;
; Revision 1.73  2012/03/28 22:44:02  nathan
; move header stuff to convert2secchi.pro; undo Rev. 1.69
;
; Revision 1.72  2012/03/21 19:49:44  mcnutt
; accepts file extentions of .gz allows for zip fits files
;
; Revision 1.71  2011/12/01 14:50:42  mcnutt
; Use select_windows instead of set_plot for cross-platform compatibility
;
; Revision 1.70  2011/11/16 14:09:53  mcnutt
; set inline = len when saving movies
;
; Revision 1.69  2011/11/09 20:58:28  nathan
; do not set hdr.filename from FITS header
;
; Revision 1.68  2011/11/09 19:00:42  mcnutt
; correct window selection if not keyword set mpegname
;
; Revision 1.67  2011/11/08 19:55:34  mcnutt
; sends img into save_frame if doxcolors is set
;
; Revision 1.66  2011/11/03 15:09:26  mcnutt
; add frametimes keyword sets frames time in wcs_combine to avoid using label keyword
;
; Revision 1.65  2011/11/03 14:17:24  mcnutt
; gets frame headers from wcs_combine and sets date_obs to labels if keyword set
;
; Revision 1.64  2011/11/01 12:31:41  mcnutt
; uses scc_save_mvframe when saving movie
;
; Revision 1.63  2011/10/24 16:36:47  mcnutt
; defines outmovie as mpegname if saving a mvi
;
; Revision 1.62  2011/10/17 17:51:01  mcnutt
; set mpegname to *.ffmpg to write a ffmpeg .mg movie
;
; Revision 1.61  2011/10/13 13:41:45  mcnutt
; corrected output movies now writes a mvi, png or gif movie while making frames
;
; Revision 1.60  2011/10/06 17:04:45  nathan
; allow type LONG input array
;
; Revision 1.59  2011/10/03 14:41:31  mcnutt
; add truecolor option for time stamps
;
; Revision 1.58  2011/08/31 21:51:18  nathan
; make sure selscl not set for byte data
;
; Revision 1.57  2011/08/31 21:44:27  nathan
; Change LABEL= to LABELS=; make /SELSCL default if bmin or bmax not input
;
; Revision 1.56  2011/07/22 14:07:23  cooper
; added rdiff=n capability
;
; Revision 1.55  2011/05/18 14:11:18  mcnutt
; defines name when making a wcs_combined movie
;
; Revision 1.54  2011/05/12 17:26:17  mcnutt
; added wcs_combine option
;
; Revision 1.53  2011/04/29 19:31:49  nathan
; Add /GRAYSCALE option for JPEG only; set WAVELNTH in frame header; do not set
; cdelt1 in frame header for non-fits case (this done in convert2secchi.pro)
;
; Revision 1.52  2011/04/29 14:48:08  mcnutt
; check for img size before asigning colors
;
; Revision 1.51  2011/04/29 14:09:18  mcnutt
; checks for png palette
;
; Revision 1.50  2011/04/25 20:06:27  mcnutt
; changed pan to work with truecolor movies and make a truecolor movie if keyword_set
;
; Revision 1.49  2011/04/21 18:53:53  nathan
; fix bug in line 823
;
; Revision 1.48  2011/03/22 20:54:55  mcnutt
; corrected _extra.file_hdr issue
;
; Revision 1.47  2011/03/22 17:58:30  mcnutt
; check _extra.file_hdr datatype before rtheta check
;
; Revision 1.46  2011/03/21 18:31:08  mcnutt
; corrected sun center for rtheta file_hdrs
;
; Revision 1.45  2011/02/14 15:20:31  mcnutt
; added dithercolor keyword to multi image frame read_jpg call
;
; Revision 1.44  2010/12/15 18:03:51  mcnutt
; do not define imgs if mpegframe is set
;
; Revision 1.43  2010/12/09 21:22:59  nathan
; run convert2secchi on HDRS= input (in case non-secchi fits hdrs)
;
; Revision 1.42  2010/11/30 14:45:10  mcnutt
; correct half when pan keyword is set
;
; Revision 1.41  2010/11/30 14:31:30  mcnutt
; added half keyword to display left or right side of image in frame
;
; Revision 1.40  2010/11/10 16:30:46  mcnutt
; will not create hdrs for multiple image frames and if nohdrs keyword is set
;
; Revision 1.39  2010/11/10 15:46:00  nathan
; committed parse_secchi_filename; if png input, assume roll is zero
;
; Revision 1.38  2010/11/10 14:44:13  mcnutt
; added temparary work around for parse_secchi_filename
;
; Revision 1.37  2010/10/05 20:11:20  nathan
; populate frame headers if non-fits name is familiar format
;
; Revision 1.36  2010/09/21 21:10:20  nathan
; add LCOLOR=
;
; Revision 1.35  2010/09/21 20:21:47  nathan
; set dobscl=0 if input is byte
;
; Revision 1.34  2010/08/31 15:19:13  nathan
; lasco sun center done in convert2secchi; make sure to crpix-1 for sun center
;
; Revision 1.33  2010/08/27 19:48:42  nathan
; always assume tile movie is truecolor; call convert2secchi for FITS files
;
; Revision 1.32  2010/08/26 13:26:59  mcnutt
; will read in fits for multi image movie
;
; Revision 1.31  2010/08/11 21:07:59  nathan
; fix error in setting hdr.cdelt1 for cunit=DEG
;
; Revision 1.30  2010/08/04 17:43:44  nathan
; use scc_sun_center if tel not recognized; clarify cunit
;
; Revision 1.29  2010/07/26 16:51:36  mcnutt
; moved populating movie hdrs to after image case statement
;
; Revision 1.28  2010/05/10 20:03:28  nathan
; fix datacube bug
;
; Revision 1.27  2010/05/10 20:02:10  nathan
; fix datacube bug
;
; Revision 1.26  2010/05/07 20:14:29  nathan
; set NOXCOLORS in scc_playmovie call
;
; Revision 1.25  2010/05/07 17:46:49  nathan
; Do FITS header operations if HDRS is set; populate imgs with dimg not img (bug)
;
; Revision 1.24  2010/02/03 20:54:05  nathan
; fix undefined hsize1 for datacube
;
; Revision 1.23  2010/01/11 19:14:16  nathan
; fix bug in multi-frame case
;
; Revision 1.22  2009/12/04 21:29:33  nathan
; force all input to resize to match first image
;
; Revision 1.21  2009/12/02 18:02:06  mcnutt
; del megwin when done
;
; Revision 1.20  2009/11/30 14:26:09  mcnutt
; calls pixmaps2mpeg while creating frames in mpegname keyword is set
;
; Revision 1.19  2009/09/24 19:52:59  mcnutt
; update Common block WSCC_MKMOVIE_COMMON to include textframe used in annotate_image
;
; Revision 1.18  2009/04/27 21:54:46  nathan
; allow gif for multi-dimension string input
;
; Revision 1.17  2009/04/08 17:52:57  nathan
; only set label color once
;
; Revision 1.16  2009/04/08 17:01:47  nathan
; Added CHARSIZE for label or times xyouts; use generic structure name; add rcol/row
; to header structure
;
; Revision 1.15  2009/04/07 15:04:16  mcnutt
; Corected common block swmoviev
;
; Revision 1.14  2009/03/31 14:53:42  mcnutt
; pan now works with multiple image frames
;
; Revision 1.13  2009/03/30 11:55:39  mcnutt
; added keyword mpegname to passed to create mpeg movie without calling scc_wrunmovie
;
; Revision 1.12  2009/03/19 13:51:07  mcnutt
; creates a multiple image frames from an image list array of [nimgs,ncols,nrows] for jpg or png file lists only and truecolor format
;
; Revision 1.11  2009/02/17 22:12:41  nathan
; added HDRS= keyword
;
; Revision 1.10  2008/12/10 19:42:57  nathan
; for FITS use hdr.filename not actual filename (fn saved with index in srem_movie.pro)
;
; Revision 1.9  2008/08/27 19:20:23  nathan
; added _EXTRA to scc_wrunmovie call
;
; Revision 1.8  2008/05/14 17:49:48  mcnutt
; defines hsize and vsize by default
;
; Revision 1.7  2008/05/12 15:27:26  nathan
; fix bug where imgs is already defined
;
; Revision 1.6  2008/05/09 19:28:43  nathan
; took out a stop that I left in
;
; Revision 1.5  2008/05/08 21:45:22  nathan
; fix /RDIF option and add UINT datatype
;
; Revision 1.4  2008/04/16 16:10:13  nathan
; added /DOXCOLORS option to allow color table adjustment (8-bit images only)
;
; Revision 1.3  2008/04/15 20:24:31  nathan
; Added /NOXCOLORS to scc_wrunmovie call. In order to implement XCOLORS, the
; frames need to be loaded into imgs variable. (See scc_wrunmovie.pro)
;
; Revision 1.2  2008/02/15 22:21:08  nathan
; handle truecolor png files
;
; Revision 1.1  2008/01/23 18:51:38  nathan
; moved from secchi/idl/display/movie (also replaces lasco/idl/movie/generic_movie.pro)
;
; Revision 1.3  2008/01/11 16:33:31  nathan
; Permanently moved from dev/movie to secchi/idl/display/movie
;
; Revision 1.13  2008/01/09 21:31:49  nathan
; Fixed LABEL keyword; compute x/ycen in all_hdr for FITS input; fixed
; check for ctype
;
; Revision 1.12  2007/12/20 22:15:36  nathan
; do not init color table
;
; Revision 1.11  2007/12/20 21:59:38  nathan
; fix labelsize if not /times
;
; Revision 1.10  2007/12/07 21:50:19  sheeley
; update debug
;
; Revision 1.9  2007/12/07 20:14:35  nathan
; added /DEBUG
;
; Revision 1.8  2007/12/06 23:40:07  nathan
; Print obs+tel above time; truncate time to second; move some header queries
; for FITS section outside of if/then stmt
;
; Revision 1.7  2007/12/06 20:59:45  nathan
; check hdr for CTYPE1 and CDELT1 in case of old secchi bkg; do maxmin,img
;
; Revision 1.6  2007/11/16 21:39:50  nathan
; use which to determine if scc_wrunmovie is available
;
; Revision 1.5  2007/11/16 16:41:34  nathan
; MDI has r_sun off by 2?
;
; Revision 1.4  2007/11/16 16:10:25  nathan
; use IDL_PATH to determine which wrunmovie to call
;
; Revision 1.3  2007/11/16 15:55:25  nathan
; Generalize for more FITS headers (MDI)
;
; Revision 1.2  2007/10/09 18:15:06  nathan
; Do not scale images with saved color-table
;
; Revision 1.1  2007/08/17 15:17:36  nathan
; modified by Adam Herbst, Summer 2007 from LASCO (currently duplicate name)
;         
; 05/21/07 @(#)generic_movie.pro	1.19 :LASCO IDL LIBRARY
; Modified    : SEP 16 Dec 97 - Added /SXT keyword
;                             - Added /MK3 keyword
;               SEP 06 Jan 98 - Added .pict, .tiff support
;               DW  21 Jan 99 - Y2K Fix for Yohkoh date
;		NBR  9 Apr 99 - Added .jpg support
;		NBR 14 May 99 - Add PICT keyword
;		NBR 15 Sep 99 - Add PAN keyword
;		NBR  7 Jun 01 - Add PNG support
;		NBR  3 Jan 02 - Add LABEL keyword
;		NBR  1 May 02 - Add RDIFF keyword
;		NBR  3 Sep 02 - Add capability for floating point FITS
;		RAH 16 SEP 04 - Flag for true color
;               NBR 17 Mar 05 - Refine criteria for doing REBIN
;               NBR 11 Apr 05 - Use /last keyword for break_file
;               NBR 19 Aug 05 - Handle generic (hopefully) SSW FITS header; tested with MK4 and BBSO
;   	    	NBR 11 May 06 - Revert date-obs and time-obs to LASCO level-0.5 format if time-obs is blank
;   	    	NBR 21 May 07 - Allow other wrunmovie.pro keywords (such as SAVE)
;
;-            

PRO GENERIC_MOVIE, data, bmin, bmax, SXT=sxt, MK3=mk3, PICT=pict, PAN=pan, LABELS=labels, DEBUG=debug, $
	RDIFF=rdiff,TRUECOLOR=truecolor, TIMES=times, _EXTRA=_extra, LOCAL=local, DOBIAS=dobias, $
	DOXCOLORS=doxcolors, HDRS=hdrs,NOHDRS=nohdrs, CharSIZE=charsize, mpegname=mpegname,selscl=selscl, $
	LCOLOR=lcolor,half=half, GRAYSCALE=grayscale,wcscombine=wcscombine,frametimes=frametimes, $
	ROIFILES=roifiles


COMMON WSCC_MKMOVIE_COMMON, swmoviev, debug_on, rgb, imgs, coordsab, findx, textframe
; IF /DOXCOLORS, imgs is necessary for xcolors to work correctly in scc_wrunmovie.pro
undefine,imgs
   IF keyword_set(TRUECOLOR) THEN truecolor=1 else truecolor=0
   IF ~keyword_set(RDIFF) THEN rdiff=0
   local = keyword_set(LOCAL)
   If keyword_set(DEBUG) Then debug_on=1 Else debug_on=0
   ds=0
   d = DATATYPE(data)
   dobscl=1
   CASE (d) OF
      'BYT' : BEGIN
             sz = SIZE(data)
             hsize0=sz(1)
             vsize0=sz(2)
             len = sz(3)
             readflag=0
	     names=string(indgen(len))
	     dobscl=0
         END
      'INT' : BEGIN
             sz = SIZE(data)
             hsize0=sz(1)
             vsize0=sz(2)
             len = sz(3)
             readflag=0
	     names=string(indgen(len))
         END
      'UIN' : BEGIN
             sz = SIZE(data)
             hsize0=sz(1)
             vsize0=sz(2)
             len = sz(3)
             readflag=0
	     names=string(indgen(len))
         END
      'FLO' : BEGIN
             sz = SIZE(data)
             hsize0=sz(1)
             vsize0=sz(2)
             len = sz(3)
             readflag=0
	     names=string(indgen(len))
         END
      'LON' : BEGIN
             sz = SIZE(data)
             hsize0=sz(1)
             vsize0=sz(2)
             len = sz(3)
             readflag=0
	     names=string(indgen(len))
         END
       'STR' : BEGIN
             IF (N_ELEMENTS(data) EQ 1) THEN BEGIN	;** read image names from file
                names = READLIST(data, len)
             ENDIF ELSE BEGIN				;** image names have been passed
                names = data
                ds=size(data)                           ;** allow more then one tel and sc for secchi
		len=ds(1)
             ENDELSE
             readflag=1
         END
      ELSE : BEGIN
             PRINT, '%%GENERIC_MOVIE: Unknown type for data: ', d
             RETURN
         END
   ENDCASE

  win_index = INTARR(len)

;IF keyword_set(HDRS) THEN all_hdr=hdrs ELSE BEGIN
    ;ahdr=def_mvi_strct()
; Id: def_mvi_strct.pro,v 1.4 2007/10/17 18:57:51 nathan Exp 
;   ahdr = {sccmvihdr, $
   ahdr = {filename:'', $
    	  detector:'', $
    	  date_obs:'', $
    	  time_obs:'', $
	  r1col:0, r2col:0, r1row:0, r2row:0, $
    	  filter:'', $
          polar:'', $
    	  wavelnth:'', $
    	  exptime:0.0,  $   	    ; seconds
    	  xcen:0.0, ycen:0.0,  $    ; pixels (FITS coordinates)
    	  cdelt1:0.0,  $    	    ; arcsec/pixel
    	  rsun:0.0,  $	    	    ; arcsec
    	  roll:0.0 }	    	    ; degrees

    all_hdr = REPLICATE(ahdr, len)
;   IF(SECCHI) THEN BEGIN
;;	IF(local) THEN sccload, names, hdrs, data $
;;	ELSE sccload, names, hdrs, data, /nolocal   ;secchi_prep, names, hdrs, data
;	IF(keyword_set(DOBIAS)) THEN BEGIN
;		IF(dobias EQ 1) THEN BEGIN
;;			medpath = median_file(names[0], /month, /min)
;;			bias = sccreadfits(medpath, medhdr)
;			im = sccreadfits(names[0], hdr, /nodata)
;			bias = scc_getbkgimg(hdr,outhdr=medhdr)
;		ENDIF
;;		ENDIF ELSE IF(dobias EQ 2) THEN bias = MIN(data, DIMENSION=3)
;	ENDIF
;stop
;   ENDIF
;ENDELSE
    
    obs=''
    cam=''
    ins=''
    label_1=''
    labelsize=1
    IF keyword_set(TIMES) THEN labelsize=times
    IF keyword_set(CHARSIZE) THEN labelsize=charsize
    bias=0.
   sunxcen=0.0
   sunycen=0.0
   sec_pix=0.0
   rsun=0.
   cunit='arcsec'   ;default
   IF keyword_set(PAN) THEN scale=pan ELSE scale=1.
   IF keyword_set(LABELS) THEN labelstr = labels ELSE labelstr=make_array(len,value='')

r=indgen(256)
;tvlct,r,r,r
first=1
if keyword_set(mpegname) then BREAK_FILE, mpegname, a, outdir, outname, outext

FOR i=0, len-1 DO BEGIN

    IF (readflag EQ 0) THEN BEGIN
	ext='none'
     	img = data[*,*,i]   
	name='x_x_x'
    	IF ((DATATYPE(bmin) EQ 'UND') or (DATATYPE(bmax) EQ 'UND')) and d NE 'BYT' THEN selscl=1 
    ; call select_bytscl()
    	
    ENDIF ELSE BEGIN

        BREAK_FILE, names(i), a, dir, name, ext, /last
	ext = STRLOWCASE(ext)
    ENDELSE
    namesubs=strsplit(name,'_') ; gives locations of subparts
         IF ds(0) le 1 THEN BEGIN

          if strpos(names(i),'http:/') eq 0 then begin
             uname=getenv('HOME')+'/tmp'+ext  
             REPEAT BEGIN
               sock_get,names(i),uname, STATUS=dlstat, /clobber
	       IF dlstat EQ 0 THEN wait,5
	     ENDREP UNTIL dlstat GE 1
          endif else uname=names(i)

          CASE (1) OF

            (ext EQ '.fts') OR (ext EQ '.fits') OR (ext EQ '.gz'): BEGIN

                ;img = READFITS(uname, fhdr)
		mreadfits,uname,fhdr,img,/dash2under
    	    	IF (keyword_set(DOBIAS)) THEN BEGIN
		    IF tag_exist(hdr,'biasmean') THEN bias=hdr.biasmean
		    img = temporary(img) - bias
		ENDIF
    	    	IF ((DATATYPE(bmin) EQ 'UND') or (DATATYPE(bmax) EQ 'UND')) THEN selscl=1 
    	    	; call select_bytscl()

            END

            (ext EQ '.gif') : BEGIN
               READ_GIF, uname, img, r, g, b
               TVLCT, r, g, b
	       dobscl=0
            END

            (ext EQ '.tif') OR (ext EQ '.tiff') : BEGIN
               img = TIFF_READ(uname, r, g, b, ORDER=order)
               IF (DATATYPE(r) NE 'UND') THEN TVLCT, r, g, b
               IF (order EQ 1) THEN img = ROTATE(img, 7)
	       dobscl=0
            END

            (ext EQ '.pct') OR (ext EQ '.pict') OR (ext EQ '.pic') OR keyword_set(PICT): BEGIN
               READ_PICT, uname, img, r, g, b
               IF (DATATYPE(r) NE 'UND') THEN TVLCT, r, g, b
	       dobscl=0
            END

	    (ext EQ '.jpg') : BEGIN
		if scale NE 1. or keyword_set(GRAYSCALE) then begin 
                  message,'/GRAYSCALE set',/info
		  READ_JPEG, uname, img ,/TWO_PASS_QUANTIZE ,/grayscale
                  truecolor=0
		  if i eq 0 then loadct,0
                endif else begin
		  READ_JPEG, uname, img ,/TWO_PASS_QUANTIZE ,ctable,COLORS=!D.N_COLORS-1,DITHER=1
                  r=ctable(*,0) & g=ctable(*,1) & b=ctable(*,2)
                  TVLCT,ctable
                endelse
	        dobscl=0
    	    END

	    (ext EQ '.png') : BEGIN
		  img = READ_PNG(uname,r,g,b)
		    sz0=size(img)
		    IF sz0[0] EQ 2 THEN TVLCT, r,g,b ELSE  BEGIN
		      img=bytscl(img)
		      truecolor=1
		    ENDELSE
	         dobscl=0
	    END
    	    
	    (ext EQ 'none') :       

            (KEYWORD_SET(MK3)):BEGIN	;** Mark3 512x512 bytearr intarr .rpB files ex. 97d296.19_32.ch0.rpB
               OPENR, IN, names(i), /GET_LUN
               a=ASSOC(IN, INTARR(512,512))
               img = a(0)
               CLOSE, IN
               FREE_LUN, IN
               namelen = STRLEN(names(i))
               aname = STRMID(names(i), namelen-20, 20)
               doy = STRMID(aname,3,3)
               yy = STRMID(aname,0,2)
               hh = STRMID(aname,7,2)
               mm = STRMID(aname,10,2)
               ahdr.filename=aname
               ahdr.detector='MK3'
               ahdr.time_obs=hh+':'+mm
               ahdr.date_obs=UTC2STR(DOY2UTC(FIX(doy), FIX(yy)), /DATE_ONLY)
               all_hdr(i) = ahdr
               sunxcen=255.5
               sunycen=255.5
               sec_pix=9.19
            END
    	
            ELSE : BEGIN
                   PRINT, '%%GENERIC_MOVIE: Unsupported file extension: ', ext
                   RETURN
            END

           ENDCASE

           if keyword_set(half) then begin
    	     sz = SIZE(img)
             if strlowcase(half) eq 'l' then img=img(0:(sz(1)/2)-1,0:sz(2)-1) else img=img(sz(1)/2:sz(1)-1,0:sz(2)-1)   
	   endif
	   
    	   ENDIF ELSE BEGIN    ; ds(0) le 1
	 ; added to create a combined png or jpg movie as called from scc_pngplay SECCHI DAILY PRETTIES
    	    	if ~keyword_set(wcscombine) then begin
                  if ds(0) eq 2 then nimg=names[i,0] else nimg=names[i,0,0]
                  if strpos(nimg,'http:') eq 0 then begin
                     uname=getenv('HOME')+'/tmp'+ext  
		     REPEAT BEGIN
                     	sock_get,nimg,uname, STATUS=dlstat, /clobber
			IF dlstat EQ 0 THEN wait,5
		     ENDREP UNTIL dlstat GE 1
		     nimg=uname
                  endif
		  dobscl=0
                  BREAK_FILE, nimg, a, dir, name, ext2, /last
                  if ext2 EQ '.png' then img1 = READ_PNG(nimg,r,g,b)
                  if ext2 EQ '.gif' then READ_GIF,nimg,img1,r,g,b
		  if ext2 EQ '.jpg' then READ_JPEG, nimg, img1, ctable,COLORS=!D.N_COLORS-1,/TWO_PASS_QUANTIZE,DITHER=1
                  if ext2 EQ '.fts' then begin
		     mreadfits,nimg,fhdr,img1,/dash2under
		     ;img1=readfits(nimg,fhdr)
		     img1=bytscl(img1)
                  endif
		  xs1=fix(n_Elements(img1(*,0))*scale) & ys1=fix(n_Elements(img1(0,*))*scale)
                  if keyword_set(half) then xs1=xs1/2
    	    	  ;  IF keyword_set(DOXCOLORS) THEN BEGIN
		  ;** I believe these are always truecolor, no? -nr
    	    	    IF ext2 eq '.fts' THEN BEGIN
		    	if ds(0) eq 2 then img=bytarr(xs1*ds(2),ys1) else img=bytarr(xs1*ds(2),ys1*ds(3)) 
		    ENDIF ELSE BEGIN
			truecolor=1
		    	if ds(0) eq 2 then img=bytarr(3,xs1*ds(2),ys1) else img=bytarr(3,xs1*ds(2),ys1*ds(3)) 
		    ENDELSE
		  if ds(0) eq 2 then ds3=1 else ds3=ds(3)
                  for ds_3=0,ds3-1 do begin
		    for ds_2=0,ds(2)-1 do begin                  
                         if ds(0) eq 1 then nimg=names[i,ds_2] else nimg=names[i,ds_2,ds_3]
                         BREAK_FILE, nimg, a, dir, name, ext2, /last
                         if nimg ne '' then begin  
                           if strpos(nimg,'http:/') eq 0 then begin
                              uname=getenv('HOME')+'/tmp'+ext2  
                              REPEAT BEGIN
                     	       sock_get,nimg,uname, STATUS=dlstat, /clobber
			       IF dlstat EQ 0 THEN wait,5
		              ENDREP UNTIL dlstat GE 1
		              nimg=uname
                           endif
                           if ext2 EQ '.png' then img1 = READ_PNG(nimg,r,g,b)
                           if ext2 EQ '.gif' then READ_GIF,nimg,img1,r,g,b
                           if ext2 EQ '.jpg' then begin
		              READ_JPEG, nimg, img1,  ctable, COLORS=!D.N_COLORS-1,/TWO_PASS_QUANTIZE,DITHER=1
                              r=ctable(*,0) & g=ctable(*,1) & b=ctable(*,2)
                           endif
                           if ext2 EQ '.fts' then begin
			      mreadfits,nimg,fhdr,img1,/dash2under
			      ;img1=readfits(nimg,fhdr)
		              img1=bytscl(img1)
                          endif
			      if keyword_set(pan) and ~keyword_set(half) then img1=congrid(img1,xs1,ys1)
			      if keyword_set(half) then begin
			           if keyword_set(pan) then img1=congrid(img1,xs1*2,ys1) 
				   if ds(0) eq 1 then hf=half(ds_2) else hf=half(ds_2,ds_3)
				   if strlowcase(hf) eq 'l' then img1=img1(0:xs1-1,0:ys1-1) else img1=img1(xs1:(xs1*2)-1,0:ys1-1)  
                              endif
			      ;IF keyword_set(DOXCOLORS) THEN $
			      IF ext2 eq '.fts' THEN $
			      	img[ds_2*xs1:(ds_2+1)*xs1-1,ds_3*ys1:(ds_3+1)*ys1-1]=img1 $
			      ELSE BEGIN
    	    	    	    	img(0,ds_2*xs1:(ds_2+1)*xs1-1,ds_3*ys1:(ds_3+1)*ys1-1)=r(img1(*,*))
                              	img(1,ds_2*xs1:(ds_2+1)*xs1-1,ds_3*ys1:(ds_3+1)*ys1-1)=g(img1(*,*))
                              	img(2,ds_2*xs1:(ds_2+1)*xs1-1,ds_3*ys1:(ds_3+1)*ys1-1)=b(img1(*,*))
			      ENDELSE
                         endif
                     endfor
                   endfor
    	    	endif else begin
		    if ds(0) eq 2 then nimg=names[i,*] else nimg=names[i,*,*]
                    BREAK_FILE, nimg[0], a, dir, name, ext2, /last
                    if keyword_set(frametimes) then frametime=frametimes(i) else frametime=0
		    img=wcs_combine(nimg,file_hdr,frame_hdr,truecolor=truecolor,vsize=vsize,first=first, frametime=frametime,_EXTRA=_extra)
                    all_hdr(i)=frame_hdr
    	    	endelse
    	    ENDELSE

    	sz = SIZE(img)

	 
         IF (sz(0) EQ 3) THEN BEGIN
            truecolor=1
            hsize0=sz(2)
            vsize0=sz(3)
         ENDIF ELSE BEGIN
            ;truecolor=0
            hsize0=sz(1)
            vsize0=sz(2)
         ENDELSE
       
      ;ENDELSE	; not a data cube

    	IF i EQ 0 THEN BEGIN
	    IF ds[0] LE 1 THEN BEGIN
    	    	hsize=fix(hsize0*scale)
    	    	vsize=fix(vsize0*scale)
	    ENDIF ELSE BEGIN
	    ; resize happens in 'combined png or jpg movie' above
    	    	hsize=hsize0
    	    	vsize=vsize0
	    ENDELSE
    	ENDIF ; all frames should be the same size; if not, then fix it.

    ; Generic SSW FITS header (hopefully)

        IF keyword_set(HDRS) or (ext EQ '.fts') OR (ext EQ '.fits') OR (ext EQ '.gz') then begin ;  populate hdrs if defined
    	    	IF keyword_set(HDRS) THEN fhdr=hdrs[i] 

		hdr=convert2secchi(fhdr)
		; Correct values in FITS header for PAN
		hdr.naxis1=hdr.naxis1*scale
		hdr.naxis2=hdr.naxis2*scale
		hdr.crpix1=hdr.crpix1*scale
		hdr.crpix2=hdr.crpix2*scale
		hdr.cdelt1=hdr.cdelt1/scale
		hdr.cdelt2=hdr.cdelt2/scale
		hdr.summed=(alog(hdr.summed/scale)/alog(2))+1
		
		; reset xcen/ycen with MVI values.
		; sccwrite_disk_mvi.pro expects this.
		;if hdr.instrume ne 'AIA' then begin
		  cxy=get_sun_center(hdr) 
		  hdr.xcen=cxy.xcen
		  hdr.ycen=cxy.ycen
		;endif

		label_1=hdr.obsrvtry+' '+hdr.detector
		IF keyword_set(TIMES) and ~keyword_set(labels) THEN BEGIN
			labelstr[i] = fhdr.date_obs
		ENDIF
		IF keyword_set(DEBUG) THEN help,/str,hdr
		IF i eq 0 THEN all_hdr=hdr ELSE all_hdr=[all_hdr,hdr]

         endif $; populate hdrs defined
    	 ELSE IF n_elements(namesubs) EQ 3 or n_elements(namesubs) EQ 4 and ds(0) le 1  and ~(keyword_set(nohdrs))THEN $
	 IF namesubs[1] EQ 9 THEN BEGIN
    	    	; assume name is of format 20100101_000921_tbh2B parse_secchi
                if strpos(names(i),'http://sdo') eq 0 then name=name+'i'
    	    	parse_secchi_filename, name, dobs, det, sc, wvl
                ;stop
		;hdr0=convert2secchi(hdrin)
		IF debug_on THEN help,dobs,det,sc
		all_hdr[i].detector=det
		all_hdr[i].wavelnth = wvl
		all_hdr[i].date_obs=strmid(dobs,0,10)
		all_hdr[i].time_obs=strmid(dobs,11,8)
		all_hdr[i].roll = 0.
		;arcsec=(2048./sz[1])*getsccsecpix(det,sc,/fast,/silent,/arcsec)
		; assuming square FFV
		;message,'Assuming input is square FFV and roll=0.',/info
		;help,arcsec
		;all_hdr[i].cdelt1=arcsec
	 ENDIF

    	IF strlen(all_hdr[i].filename) LT 4 THEN all_hdr[i].filename=name+ext ;check last all_hdr i does not work if keyword rdiff is set
	
	IF keyword_set(RDIFF) THEN BEGIN
    	    	
		IF i EQ 0 THEN BEGIN  ;need an array of previous images if rdiff>1
; 		IF rdiff GT 1 THEN BEGIN
		dims=size(img,/dim) 
		prev=fltarr(dims[0],dims[1],rdiff)
		ENDIF
		IF i LT rdiff THEN BEGIN
			;mdn = median(img)
			;mn = MIN(img, max=mx)
			;timg = BYTSCL(img,mn + (mdn-mn)/2.,mdn + (mx-mdn)/2.)
			;dimg = timg-128
			nimg=float(img)
		ENDIF ELSE nimg = float(img)-prev[*,*,0]
		IF rdiff EQ 1 THEN prev=img ELSE BEGIN
			prev=shift(prev,0,0,-1)
			prev[*,*,rdiff-1]=img
		ENDELSE
		img = nimg
	ENDIF

	IF (keyword_set(PAN) or hsize0 NE hsize) and ds(0) le 1 THEN BEGIN ;and ~keyword_set(truecolor)
		IF ((hsize0 mod hsize) EQ 0 $
                and (vsize0 mod vsize) EQ 0 ) $
                THEN img = REBIN(TEMPORARY(img),hsize,vsize) $
                ELSE img = CONGRID(TEMPORARY(img),hsize,vsize,/interp)
		;all_hdr[i].NAXIS1 = fix(all_hdr[i].NAXIS1 * pan)
		;all_hdr[i].NAXIS2 = fix(all_hdr[i].NAXIS2 * pan)
                sec_pix = sec_pix/scale
                sunxcen=sunxcen*scale
                sunycen=sunycen*scale
	ENDIF
	IF(~keyword_set(RDIFF) OR i GE RDIFF) THEN BEGIN
                IF keyword_set(mpegname) and first THEN BEGIN
		    WINDOW, XSIZE = hsize, YSIZE = vsize, /PIXMAP, /FREE
		    mpegwin = !D.WINDOW
	        ENDIF
                IF ~keyword_set(mpegname) THEN BEGIN
		    WINDOW, XSIZE = hsize, YSIZE = vsize, /PIXMAP, /FREE
		    win_index(i) = !D.WINDOW
	        ENDIF else wset,mpegwin
		maxmin,img
                IF keyword_set(selscl) and (first) THEN BEGIN
                    bmax = MAX(img)
                    bmin = MIN(img)
		    bimg=select_bytscl(img,bmin,bmax,/noscl)
		ENDIF
                IF (dobscl) and ~keyword_set(TRUECOLOR) THEN dimg=BYTSCL(img,bmin,bmax) ELSE dimg=img
   	        IF keyword_set(TRUECOLOR) and ds(0) le 1 and (sz(0) EQ 2) THEN BEGIN 
                   dimg=bytarr(3,hsize,vsize)
   	 	   dimg(0,*,*)=r(img(*,*))
   	           dimg(1,*,*)=g(img(*,*))
    	           dimg(2,*,*)=b(img(*,*))
    	        ENDIF
		TV,dimg,TRUE=truecolor 
		IF debug_on THEN print,'!D.WINDOW=',!d.window
		IF labelstr[0] NE '' THEN BEGIN
		    IF keyword_set(DOXCOLORS) and ~keyword_set(TRUECOLOR) THEN BEGIN
		    ; use zbuffer to retain byte values with added label
    	    	    	set_plot,'z'     
    	    	    	device,set_resolution=[hsize,vsize]
	    	    	TV,dimg
		    ENDIF 

		    IF ~keyword_set(TRUECOLOR) THEN begin
		      mdnotbx=median(dimg[10:10+(hsize/6),10:10+20])
		      IF keyword_set(LCOLOR) THEN BEGIN
		      	IF n_elements(lcolor) EQ 1 THEN datecolor=lcolor ELSE datecolor=lcolor[i]
		      	ENDIF ELSE $
    		      IF first THEN IF mdnotbx GT 80 THEN datecolor=0 ELSE datecolor=255	
                    ENDIF ELSE BEGIN
 		      IF keyword_set(LCOLOR) THEN datecolor=lcolor ELSE DATECOLOR='FFFFFF'x
		    ENDELSE
		    
		    IF labelsize LE 1 THEN fontnum=0 ELSE fontnum=-1
		    cthick=2
    		    XYOUTS, 10, 10, labelstr[i], /DEVICE, CHARSIZE=labelsize, FONT=fontnum, CHARTHICK=cthick,COLOR=datecolor

		    cyouts=10+ labelsize*10 + 5
    		    XYOUTS, 10, cyouts, label_1, /DEVICE, CHARSIZE=labelsize, FONT=fontnum, CHARTHICK=cthick,COLOR=datecolor

    	    	    IF keyword_set(ROIFILES) THEN BEGIN
		    	restore,roifiles[i]
			plot_roi,roi,hsize,vsize
		    ENDIF
			
        	    IF keyword_set(DEBUG) THEN help,xouts,youts,times,mdnotbx,datecolor,labelsize,fontnum,labelstr
		    IF keyword_set(DOXCOLORS) and ~keyword_set(TRUECOLOR) THEN BEGIN
		    	img=tvrd()
			select_windows ;set_plot,'x'
		        tv,img
		    ENDIF
    	    	ENDIF
                IF keyword_set(mpegname) THEN begin
                IF keyword_set(DOXCOLORS) then saveimg=img else saveimg=mpegwin
		    if datatype(file_hdr) ne 'STC' then begin
		       def_mvi_hdr,file_hdr
		       file_hdr.nx=hsize
		       file_hdr.ny=vsize
		       file_hdr.truecolor=truecolor
		    endif
		    scc_save_mvframe,i,mpegname, saveimg, all_hdr(i),file_hdr,first=first,inline=len,_EXTRA=_extra
                ENDIF
		IF(~keyword_set(RDIFF)) THEN print,'Done with image ', i+1, ' of ', len $
		ELSE print, 'Done with image ', i, ' of ', len-1
		first=0
	  IF keyword_set(DOXCOLORS) and ~keyword_set(TRUECOLOR) and ~keyword_set(mpegname) THEN BEGIN
	    IF [i eq 1 and keyword_set(RDIFF)] or [i LE 0 and ~keyword_set(RDIFF)] THEN imgs=bytarr(hsize,vsize,len)  
	    imgs[*,*,i]=dimg	
          ENDIF 
	  IF keyword_set(DOXCOLORS) and keyword_set(TRUECOLOR) and ~keyword_set(mpegname) THEN BEGIN
	    IF [i eq 1 and keyword_set(RDIFF)] or [i LE 0 and ~keyword_set(RDIFF)] THEN imgs=bytarr(3,hsize,vsize,len)  
	    imgs[*,*,*,i]=dimg	
	  ENDIF
	ENDIF
	undefine, img
   ENDFOR   ; FOR i=0, len-1


if ds(0) gt 1 then names=names(*,0,0) ;use only first file names SECCHI scc_pngplay

   IF(keyword_set(RDIFF)) THEN BEGIN
	win_index = win_index[rdiff:*]
	all_hdr = all_hdr[rdiff:*]
	names = names[rdiff:*]
        IF keyword_set(DOXCOLORS) then imgs=imgs[*,*,rdiff:*]
    ENDIF

   IF datatype(_extra) eq 'STC' THEN BEGIN
     IF tag_exist(_extra,'file_hdr') THEN IF datatype(_extra.file_hdr) eq 'STC' THEN BEGIN
      if _extra.file_hdr.rtheta gt 0 then begin
         sunxcen=_extra.file_hdr.sunxcen
         sunycen=_extra.file_hdr.sunycen
       endif
     ENDIF
   ENDIF

IF ~(debug_on) THEN if datatype(uname) ne 'UND' then if uname eq getenv('HOME')+'/tmp'+ext then file_delete,uname
help,sec_pix,sunxcen,mdnotbx
IF sunxcen EQ 0 and datatype(sunc) NE 'UND' THEN print,sunc
if keyword_set(debug) then wait,2
IF ~keyword_set(mpegname) THEN BEGIN
  which,'scc_playmovie',outfile=sccpros
  IF sccpros[0] NE '' THEN BEGIN
     print, 'Calling SCC_playmovie'
     SCC_PLAYMOVIE, win_index, SUNXCEN=sunxcen, SUNYCEN=sunycen, SEC_PIX=sec_pix, NOXCOLORS=~keyword_set(DOXCOLORS), $
	HDRS=all_hdr, NAMES=names, truecolor=truecolor, DEBUG=debug, file_hdr=file_hdr,_EXTRA=_extra
  ENDIF ELSE BEGIN
     print, 'Calling WRUNMOVIE'
     WRUNMOVIE, win_index, SUNXCEN=sunxcen, SUNYCEN=sunycen, SEC_PIX=sec_pix,$
	HDRS=all_hdr, NAMES=names, truecolor=truecolor, _EXTRA=_extra
  ENDELSE

ENDIF else wdel,mpegwin 
;   IF(SECCHI) THEN undefine, data

END
