;+
; Project     : SOHO - LASCO/EIT
;                   
; Name        : MKMOVIE
;               
; Purpose     : Load FITS files into pixmaps and call WRUNMOVIE for animation.
;               
; Explanation : This procedure sorts the images by time, reads them, and 
;		normalizes to the exposure time of the first image.
;		WRUNMOVIE is called to start a widget interface for the 
;		animation sequence.  The on_off_diff keyword results in a movie
;               where each on line image is displayed with a nearby offband image
;               subtracted.
;               
; Use         : MKMOVIE, list, bmin, bmax, /TIMES, /DIFF, /NO_NORMAL, /NO_SORT, $
;                        UNSHARP=unsharp, PAN=pan, COORDS=coords, BOX=box, $
;                        /RATIO, /USE_MODEL,/FLAT_FIELD,/ON_OFF_DIFF,/MASK_OCC,/LG_MASK_OCC
;                        /RUNNING_DIFF, /RADIAL, /DEGRID, /FIXGAPS, /LOG_SCL, /SQRT_SCL, $
;			 FILL_COL=fill_col, SAVE=save
;
;      Example: IDL> MKMOVIE, 'list960123', -100, 100, /DIFF
;
;      Example: If you want to display BYTARR images straight from the FITS files without
;		any scaling use:
;               IDL> MKMOVIE, 'list', 0, 255, /NO_NORMAL, /NO_SORT
;    
; Inputs      : list : Name of file containing names of FITS files.
;		       Or a STRARR of the image names.
;               bmin, bmax : Minimum and maximum DN for BYTSCL.
;               
; Outputs     : None.
;               
; Keywords    : The following keywords apply to all telescopes (C1,C2,C3,EIT)
;
;		/AUTOMAX   : Compute bmin and bmax based on median
;		/LEEFILT   : Apply Leefilt function to filter noise.
;               /TIMES     : Set this keyword to display date and time in images.
;		/DIFF      : Set this keyword to make a difference movie.  The 
;			     first image is subtracted from all subsequent images.
;		/RUNNING_DIFF  : Make a difference movie, subracting the preceding image.
;		/NO_NORMAL : Don't normalize exposure times to that of the first image.
;		/NO_SORT   : Don't sort by time in header.
;               UNSHARP    : Set this keyword to make a movie of unsharp masked images.
;                            The value of the keyword if any is set to the size of the
;                            unsharp mask, default=25
;                            Example:  A value of 9 would form a 9x9 unsharp mask
;		/RATIO     : If using diff or running_diff display data as ratio of image/reference frame
;               /MASK_OCC  : applies a sun sized circle and removes the internal part of the image
;               /LG_MASK_OCC:applies a sun sized circle and removes the part of the field to 1.2Rsun
;                            for C1 (especially good for the longer 100s exposures).  
;			     For C3 the pylon is masked
;		/LOG_SCL   : Applies ALOG10() function to image before byte scaling
;		/SQRT_SCL  : Applies SQRT() function to image before byte scaling
;		/FIXGAPS   : Set to 1 to fill data gaps in image with color specified by FILL_COL
;		             Set to 2 to fill data gaps in image with values from previous image
;		FILL_COL   : Set this keyword to the color index to use for data gaps and occ masks.
;		SAVE       : For use in batch mode.  Set this keyword to the name of the .mvi file
;			     to save as.  Routine will save movie and then exit.
;		PAN        : Default is to resize images to pixel size of the first image.  Set this
;			     keyword to perform additional scaling.  Example: set to 0.5 for 2x2 rebinning.
;		COORDS     : Set to 4 element array of image coordinates to use relative to 1024x1024 image.
;			     Example: COORDS=[0,1023,128,895] for C2 Equatorial Field
;		BOX        : Set to 4 element array of image coordinates to use for box normalization 
;			     relative to 1024x1024 image. Images are scaled relative to average counts
;			     in box of first image. Example: BOX=[461,560,641,740]
;		REF_BOX    : Set to avg counts specified in BOX otherwise first image is used
;
;             : The following keywords apply only to C1
;
;               /ON_OFF_DIFF: differences each on line image with an image taken at a continuum wavelength
;               /FLAT_FIELD : normalizes each image by a door closed image to remove the solar spectrum
;               /RADIAL	    : applies a radial filter
;
;             : The following keywords apply only to C2 and C3
;
;		/USE_MODEL : If using diff or running_diff use background corona model
;			     as base frame.  USE_MODEL=1 for overall yearly model
;					     USE_MODEL=2 for closest monthly model
;
;             : The following keywords apply only to EIT
;
;               /DEGRID	    : applies the degridding algorithm
;
; Calls       : WRUNMOVIE
;
; Side effects: Creates multiple pixmaps.
;               
; Category    : Image Display.
;               
; See Also    : WMKMOVIE.PRO is a widget front-end to this procedure.
;               GENERIC_MOVIE.PRO reads in bytescaled fits or gif files and creates a movie.
;               
; Prev. Hist. : None.
;
; Written     : Scott Paswaters, NRL, Jan 1996.
;               
; Modified    : SEP 29 May 96 - Place frames into multiple pixmaps instead of 1 large
;				pixmap because of limitations on window size in IDL.
;               SEP  9 Jul 96 - Read in img headers as structures and pass to wrunmovie
;               SEP 18 Oct 96 - Add option to pass in STRARR of image names instead of filename.
;               SEP 24 Oct 96 - added /RATIO and /USE_MODEL options
;               RAH 13 Dec 96 - added check for daily median image which doesn't have bias
;               CMK 16 Feb 97 - added all C1 related features and changed the procedure name to mkc1movie2
;           RAH/SEP 14 Mar 97 - integrated mkc1movie2 features into mkmovie
;               SEP 21 Mar 97 - corrected bias subtraction for LEB summed images
;               SEP 01 Oct 97 - added /SUM keyword to OFFSET_BIAS call
;               SEP 22 Oct 97 - fixed divide by zero error for /RATIO option
;               SEP 31 Oct 97 - Binned images are scaled (/bin^2) for level_05 images only
;               SEP 13 Nov 97 - Added /FLAT_FIELD for EIT, added /NEW flag to EIT_DEGRIDN
;               RAH 02 Feb 98 - Now normalizes to calculated exposure time (if data exists).
;		NBR 06 Nov 98 - Change default fillcol to median(image); change LG_MASK_OCC for c3 to use C3clearmask2.dat
;		NBR 16 Dec 98 - Add LEEFILT keyword
;		NBR  8 Feb 99 - Add AUTOMAX keyword
;		NBR 11 Feb 99 - Move up first call of REDUCE_STD_SIZE
;			      - Hardwire in 256 colors
;
; Version     : 
;
; SCCS variables for IDL use
; 
; @(#)mkmovie.pro	1.12 02/11/99 :NRL Solar Physics
;
;-            
 
;____________________________________________________________________________
;

PRO MKMOVIE, list, bmin, bmax, LEEFILT=leefilt, DIFF=diff, TIMES=times, $
RUNNING_DIFF=running_diff, NO_NORMAL=no_normal, AUTOMAX=automax, $
NO_SORT=no_sort, UNSHARP=unsharp, RATIO=ratio, USE_MODEL=use_model, $
MASK_OCC=mask_occ, FIXGAPS=fixgaps, DEGRID=degrid, LOG_SCL=log_scl, $
ON_OFF_DIFF=on_off_diff,FLAT_FIELD=flat_field,LG_MASK_OCC=lg_mask_occ,$
RADIAL=radial, SQRT_SCL=sqrt_scl, FILL_COL=fill_col, PAN=pan, COORDS=coords, $
BOX=box, SAVE=save, REF_BOX=box_ref, USE_SHARP=use_sharp, SHARP_FACTOR=sharp_factor

   csize = 1.5

   IF (N_ELEMENTS(list) EQ 1) THEN BEGIN	;** read names from file
      str = STRARR(1)
      OPENR, UNIT, list, /GET_LUN
      READF, UNIT, str
      names = str
      WHILE (NOT EOF(UNIT)) DO BEGIN
         READF, UNIT, str
         names = [names, str]
      ENDWHILE
      CLOSE, UNIT
      FREE_LUN, UNIT
   ENDIF ELSE BEGIN
      names = list
   ENDELSE
   len = N_ELEMENTS(names)

   tai_all = DBLARR(len)
   exp_all = FLTARR(len)
   bias_all = FLTARR(len)
   fpwvl_all=fltarr(len)
   filter_all=strarr(len)
   ;** sort on date/time in header
   ;** and save exposure time for normalizing
   FOR i = 0, len-1 DO BEGIN
      junk = LASCO_READFITS(names(i), hdr, /NO_IMG)
      IF (DATATYPE(hdr) EQ 'STC') THEN BEGIN
         exp_cmd = hdr.expcmd    		;** commanded exposure time
         exp_dur = hdr.exp0		;** actual delay measure by OBE
         date_obs = hdr.date_obs
         time_obs = hdr.time_obs
         IF (GET_EXP_FACTOR(hdr,efac,bias) NE 0)  THEN BEGIN
            PRINT,'Exposure factor not found for '+date_obs+' '+time_obs
            efac = 1.
         ENDIF
         IF (exp_all(i) LT 0)    THEN hdr.exptime=hdr.exptime+32
         exp_all(i) = hdr.exptime*efac        	;** actual delay measure by OBE
         bias_all(i) = bias
         fpwvl=hdr.waveleng
         filter=hdr.filter
         fpwvl_all(i)=fpwvl
         filter_all(i)=filter
         IF (DATATYPE(time_obs) EQ 'STR') THEN BEGIN
            tai = UTC2TAI(STR2UTC(date_obs + ' ' + time_obs))
            tai_all(i) = tai
         ENDIF
         IF (exp_cmd NE exp_dur) THEN $
            PRINT, '%%MKMOVIE: Warning. file: ', names(i), ' ', time_obs, ' exp_cmd:', $
                exp_cmd, ' NE  exp_dur:', exp_dur, ' Exposure time error in header.'
         IF (i EQ 0) THEN all_hdr = REPLICATE(hdr, len)
         all_hdr(i) = hdr
      ENDIF
   ENDFOR

   IF KEYWORD_SET(SHARP_FACTOR) THEN sharp_fact = sharp_factor ELSE sharp_fact = 0.015
   
   IF NOT(KEYWORD_SET(NO_SORT)) THEN BEGIN
      ind = SORT(tai_all)
      names = names(ind)
      tai_all = tai_all(ind)
      exp_all = exp_all(ind)
      all_hdr = all_hdr(ind)
      fpwvl_all=fpwvl_all(ind)
      filter_all=filter_all(ind)
      bias_all = bias_all(ind)
   ENDIF

   IF KEYWORD_SET(TIMES) THEN times = UTC2STR(TAI2UTC(tai_all), /ECS, /TRUNCATE)
   label = STRARR(N_ELEMENTS(names))
   FOR i=0, N_ELEMENTS(names)-1 DO BEGIN
      pos = RSTRPOS(names(i), '/')
      IF (pos GE 0) THEN $
         label(i) = STRMID(names(i), pos+1, STRLEN(names(i))-pos) $
      ELSE $
         label(i) = names(i)
   ENDFOR

   ind0 = -1
   ind00 = -1
   PRINT, '%%MKMOVIE: Processing file: ', 1 , ' of: ', len
   image = LASCO_READFITS(names(0), hdr)
   cam = TRIM(hdr.detector)

   ;** save rebin params and image coords
   IF KEYWORD_SET(PAN) THEN img_pan=pan ELSE img_pan=1
   IF (hdr.sumcol GT 1) OR (hdr.lebxsum GT 1) OR (img_pan LT 1) $
	THEN DOFULL=0 ELSE DOFULL=1

   image = REDUCE_STD_SIZE(image, hdr, FULL=DOFULL)   
				;** make all images 1024x1024 or 512x512

   img0_pan=(1./(hdr.sumcol>1))*(1./(1>hdr.lebxsum))*img_pan
   IF KEYWORD_SET(COORDS) THEN BEGIN
      img0_x1=coords(0)
      img0_x2=coords(1)
      img0_y1=coords(2)
      img0_y2=coords(3)
   ENDIF ELSE BEGIN	;** use coordinates from first image
      img0_x1=hdr.r1col-20
      img0_x2=hdr.r2col-20
      img0_y1=hdr.r1row-1
      img0_y2=hdr.r2row-1
   ENDELSE
   hsize = img0_x2-img0_x1+1
   vsize = img0_y2-img0_y1+1

   IF KEYWORD_SET(BOX) THEN BEGIN
      box_x1=box(0)
      box_x2=box(1)
      box_y1=box(2)
      box_y2=box(3)
   ENDIF

   IF (hdr.sumcol GT 1) OR (hdr.lebxsum GT 1) OR (img_pan LT 1) THEN BEGIN
      fhsize=512
      fvsize=512
      hsize=hsize/2
      vsize=vsize/2
      img0_pan = img0_pan*2
      img0_x2=img0_x2/2
      img0_x1=img0_x2-hsize+1
      img0_y2=img0_y2/2
      img0_y1=img0_y2-vsize+1
      IF KEYWORD_SET(BOX) THEN BEGIN
         box_x1=box_x1/2
         box_x2=box_x2/2
         box_y1=box_y1/2
         box_y2=box_y2/2
      ENDIF
   ENDIF ELSE BEGIN
      fhsize=1024
      fvsize=1024
   ENDELSE

   sunc = GET_SUN_CENTER(hdr, FULL=fhsize, /NOCHECK)
   arcs = GET_SEC_PIXEL(hdr, FULL=fhsize)
   asolr = GET_SOLAR_RADIUS(hdr)
   r_sun = asolr/arcs

   hsize=hsize*img0_pan
   vsize=vsize*img0_pan
   sunxcen=(sunc.xcen-img0_x1)*img0_pan
   sunycen=(sunc.ycen-img0_y1)*img0_pan
   sec_pix=arcs/img0_pan

   IF (KEYWORD_SET(FLAT_FIELD) AND (STRLOWCASE(hdr.detector) EQ 'c1')) THEN BEGIN
      IF filter NE 'Fe XIV' THEN BEGIN
         factoroff = 1.0
         factoron = 1.0
         PRINT, '%%MKMOVIE: FLAT_FIELD option currently only works for C1 Fe XIV'
      ENDIF ELSE BEGIN
      offband=5309
      ;find on band wavelength
      flag=0
      dummy_count=0
      WHILE flag ne 1 DO BEGIN
         IF FIX(fpwvl_all(dummy_count)) ne offband THEN BEGIN 
            onband=fpwvl_all(dummy_count)
            flag=1
         ENDIF
         dummy_count=dummy_count+1
         IF dummy_count EQ len THEN BEGIN
            flag=1
            print,'no onband wavelengths found'
         ENDIF
      ENDWHILE
      CD,GETENV('NRL_LIB')+'/lasco/data/calib',curr=currdir
      IF onband EQ 5302.4222 THEN flaton=readfits('12014004.fts',flatonhdr)
      IF onband EQ 5302.7273 THEN flaton=readfits('12014017.fts',flatonhdr)
      IF offband EQ 5309 THEN flatoff=readfits('12014005.fts',flatoffhdr)
      CD,currdir
      offset=369
      flfldon =(FLOAT(flaton-offset)/FXPAR(flatonhdr,'exptime'))/25.0
      flfldoff=(FLOAT(flatoff-offset)/FXPAR(flatoffhdr,'exptime'))/25.0

      b=where(flfldon le 0.0,count)
      IF count ne 0 THEN flfldon(b)=1.0
      b=where(flfldoff le 0.0,count)
      IF count ne 0 THEN flfldoff(b)=1.0

      factoroff=1.0/flfldoff
      factoron=1.0/flfldon
      factoroff = REDUCE_STD_SIZE(factoroff, flatoffhdr, FULL=DOFULL);** make all images 1024x1024 or 512x512
      factoron = REDUCE_STD_SIZE(factoron, flatonhdr, FULL=DOFULL);** make all images 1024x1024 or 512x512

      ENDELSE
   ENDIF
   IF KEYWORD_SET(RADIAL) THEN BEGIN
       CD,GETENV('NRL_LIB')+'/lasco/data/calib',curr=currdir
       radial=readfits('C1_radial.fts', radialhdr)
       CD,currdir
       radial=float(radial) / 100
       radial = REDUCE_STD_SIZE(radial, radialhdr, FULL=DOFULL);** make all images 1024x1024 or 512x512
   ENDIF
   

   ind0 = WHERE(image EQ 0)

;   imgbias = OFFSET_BIAS(hdr, /SUM)
    imgbias = bias_all(0)
print, 'imgbias = ', imgbias
   BREAK_FILE, names(0), a, dir, name, ext
   IF NOT(KEYWORD_SET(NO_NORMAL)) AND $
   ( (STRMID(name(0),1,2) NE 'd_') AND (STRMID(name(0),1,2) NE 'm_') ) THEN BEGIN
         image = image - imgbias 
         IF (ind0(0) NE -1) THEN image(ind0) = 0
   ENDIF
   IF KEYWORD_SET(DEGRID) THEN image = EIT_DEGRIDN(image, STRUCT2FITSHDR(hdr), /NEW)
   IF (KEYWORD_SET(FLAT_FIELD) AND (STRLOWCASE(hdr.detector) EQ 'eit')) THEN $
          image = EIT_FLATN(image, STRUCT2FITSHDR(hdr))
   ind0 = WHERE(image EQ 0)
   ;** if file is a level_05 image then counts are in DN and we need to account for pixel summing
   ;** file is level_05 if name is tsxxxxxx and t <=4 and s <=3
   IF ( (STRLEN(name) EQ 8) AND (VALID_NUM(STRMID(name,1,1)) ) AND (VALID_NUM(STRMID(name,0,1)) ) ) THEN BEGIN
      IF ( (FIX(STRMID(name,1,1)) LE 3) AND (FIX(STRMID(name,0,1)) LE 4) ) THEN BEGIN
         IF (hdr.sumcol NE 0) THEN image = image/(hdr.sumcol)^2
         IF (hdr.lebxsum NE 0) THEN image = image/(hdr.lebxsum)^2
      ENDIF
   ENDIF

   IF (KEYWORD_SET(MASK_OCC)) OR KEYWORD_SET(LG_MASK_OCC) THEN BEGIN
      CASE STRLOWCASE(hdr.detector) OF
      'c1' : BEGIN
                r_occ = r_sun * 1.1
                IF KEYWORD_SET(LG_MASK_OCC) THEN r_occ=r_sun * 1.2
                r_occ_out = r_sun * 3.0
             END
      'c2' : BEGIN
                r_occ = r_sun * 2.1
                IF KEYWORD_SET(LG_MASK_OCC) THEN r_occ=r_sun * 2.2
                r_occ_out = r_sun * 7.0
             END
      'c3' : BEGIN
                r_occ = r_sun * 4.3
                r_occ_out = r_sun * 32.0
                c3mask=-1
                IF KEYWORD_SET(LG_MASK_OCC) THEN BEGIN
                   CD,GETENV('NRL_LIB')+'/lasco/data/calib',curr=currdir
                   c3mask=READFITS('c3clearmask2.fts')
                   c3mask = REBIN(c3mask, hsize, vsize)
                   CD,currdir
                ENDIF
             END
      ELSE :
      ENDCASE
   ENDIF
 
   WINDOW, 0, XSIZE=hsize, YSIZE=vsize   ; window to display each frame
   WINDOW, 2, XSIZE=fhsize, YSIZE=fvsize, /PIXMAP


;**
;** START C1
;**
   IF KEYWORD_SET(ON_OFF_DIFF) THEN BEGIN
        IF KEYWORD_SET(FILL_COL) THEN fillcol=fill_col ELSE fillcol=10
	;find which filter was used
	filter=STRTRIM(filter_all(1),2)
        ;set off-band wavelength
	IF filter EQ 'Fe XIV' THEN offband=5309
	IF filter EQ 'Fe X' THEN offband=6380
	IF (filter ne 'Fe XIV') and (filter ne 'Fe X') THEN print,'filter not recognized'
	;find first offband wavelength image
	flag=0
	count=0
	while flag ne 1 DO BEGIN
		IF FIX(fpwvl_all(count)) EQ offband THEN flag=1
		count=count+1
			IF count EQ (len-1) THEN BEGIN
				flag=1
				print,'no offband images found'
			ENDIF
	endwhile
	ref=L1_RDFTS(names(count-1),hdr)
        ref = REDUCE_STD_SIZE(ref, hdr, FULL=DOFULL)   ;** make all images 1024x1024 or 512x512
        IF KEYWORD_SET(FIXGAPS) THEN ind0 = WHERE(ref EQ 0)
	first_onband=0
	while flag ne 1 DO BEGIN
		IF FIX(fpwvl_all(first_onband)) ne offband THEN flag=1
		first_onband=first_onband+1
			IF count EQ (len-1) THEN BEGIN
				flag=1
				print,'no onband images found'
			ENDIF
	endwhile
	total_off=0
	flag=0
	;count all offband images
	FOR i=0,len-1 DO BEGIN
		IF FIX(fpwvl_all(i)) EQ offband THEN total_off=total_off+1
	ENDFOR
	lblcount=0
	IF filter EQ 'Fe X' THEN factor=0.975 ELSE factor=1.00
	IF KEYWORD_SET(FLAT_FIELD) THEN factor=factor*factoroff
	ref=ref*factor*exp_all(0)
	win_index=intarr(len-total_off)
	new_label=strarr(len-total_off)
	c1hdr_ind=bytarr(len)
	yloc=0
        prev = -1
	image=L1_RDFTS(names(first_onband), hdr)*exp_all(0)-ref
        image = REDUCE_STD_SIZE(image, hdr, FULL=DOFULL)   ;** make all images 1024x1024 or 512x512
	FOR i=0,len-1 DO BEGIN
	      	PRINT, '%%MKMOVIE: Processing file: ', i+1 , ' of: ', len
		new_image = L1_RDFTS(names(i), hdr)*exp_all(0)
                new_image = REDUCE_STD_SIZE(new_image, hdr, FULL=DOFULL)   ;** make all images 1024x1024 or 512x512
		IF FIX(fpwvl_all(i)) EQ offband THEN ref=factor*new_image ELSE BEGIN
                        IF KEYWORD_SET(FIXGAPS) THEN ind00 = WHERE(new_image EQ 0)
			IF (i lt len-1) THEN BEGIN
				IF FIX(fpwvl_all(i+1)) EQ offband THEN BEGIN
                                   ref=(L1_RDFTS(names(i+1),hdr))*exp_all(0)
                                   ref = REDUCE_STD_SIZE(ref, hdr, FULL=DOFULL)   ;** make all images 1024x1024 or 512x512
                                   ref = ref*factor
                                   IF KEYWORD_SET(FIXGAPS) THEN ind0 = WHERE(ref EQ 0)
				ENDIF
			ENDIF
                        IF KEYWORD_SET(FLAT_FIELD) THEN new_image=new_image*factoron

                        IF KEYWORD_SET(BOX) THEN BEGIN	 ;** normalize to counts in box
                           box_img = DOUBLE(ref(box_x1:box_x2,box_y1:box_y2))
                           good = WHERE(box_img GT 0)
                           IF (good(0) GE 0) THEN box_ref=TOTAL(box_img(good))/N_ELEMENTS(good)
                           box_img = DOUBLE(new_image(box_x1:box_x2,box_y1:box_y2))
                           good = WHERE(box_img GT 0)
                           IF (good(0) GE 0) THEN BEGIN
                              box_avg=TOTAL(box_img(good))/N_ELEMENTS(good)
                              new_image = TEMPORARY(new_image) * (box_ref/box_avg)
                           ENDIF
                        ENDIF

			new_image=new_image-ref
			IF KEYWORD_SET(LOG_SCL) THEN BEGIN
				new_image=new_image+10
				b=where(new_image le 0,dummy)
				IF dummy ne 0 THEN new_image(b)=1
				new_image=alog10(new_image)*100
			ENDIF
                        IF KEYWORD_SET(SQRT_SCL) THEN BEGIN
                           new_image = SQRT((new_image+10)>0)
                        ENDIF
			IF KEYWORD_SET(RUNNING_DIFF) THEN BEGIN
				dummy=new_image
				new_image=new_image-image
				image=dummy
                                IF KEYWORD_SET(FIXGAPS) THEN ind0=ind00
			ENDIF
                        IF KEYWORD_SET(RADIAL) THEN new_image=new_image/radial
			new_image=fix(new_image)
			new_image= BYTE(((new_image > bmin < bmax)-bmin)*(!D.N_COLORS-1)/(bmax-bmin))
			IF KEYWORD_SET(MASK_OCC) OR KEYWORD_SET(LG_MASK_OCC) THEN BEGIN
                           tmp_img = new_image & tmp_img(*) = 0 & WSET,2 & TV,tmp_img
                           TVCIRCLE, r_occ_out,sunc.xcen,sunc.ycen, /FILL, COLOR=1
                           tmp_img = TVRD(0,0,fhsize,fvsize)
                           ind1 = WHERE(tmp_img NE 1)
                           IF (ind1(0) NE -1) THEN new_image(ind1) = fillcol
                        ENDIF

                        IF KEYWORD_SET(FIXGAPS) THEN BEGIN
                           IF (ind0(0) NE -1) THEN BEGIN			;** gaps in ref image
                              IF ((fixgaps EQ 1) OR (i EQ 0) OR (prev(0) EQ -1)) THEN image(ind0) = fillcol $
                              ELSE new_image(ind0) = prev(ind0)	;** fill gaps with prev image
                           ENDIF
                           IF (ind00(0) NE -1) THEN BEGIN			;** gaps in this image
                              IF ((fixgaps EQ 1) OR (i EQ 0) OR (prev(0) EQ -1)) THEN image(ind00) = fillcol $
                              ELSE new_image(ind00) = prev(ind00)	;** fill gaps with prev image
                           ENDIF
                        ENDIF

                        WSET, 2
                        TV, new_image
                        prev = new_image
			IF KEYWORD_SET(MASK_OCC) OR KEYWORD_SET(LG_MASK_OCC) THEN BEGIN
                           TVCIRCLE, r_occ, sunc.xcen, sunc.ycen, /FILL, COLOR=fillcol
                           TVCIRCLE, r_sun, sunc.xcen, sunc.ycen, COLOR=255, THICK=2
                        ENDIF
                        image = TVRD()
                        image = image(img0_x1:img0_x2,img0_y1:img0_y2)
                        image = REBIN(image, hsize, vsize)

			WINDOW, XSIZE = hsize, YSIZE = vsize, /PIXMAP, /FREE 
                        win_index(yloc) = !D.WINDOW
                        TV, image

			IF KEYWORD_SET(TIMES) THEN XYOUTS, 10, 10, cam+'  ' +times(i), /DEVICE, CHARSIZE=csize
			new_label(lblcount)=label(i)
			lblcount=lblcount+1
			c1hdr_ind(i)=1
			WSET, 0 & DEVICE, COPY = [0, 0, hsize, vsize, 0, 0, win_index(yloc)]
			yloc = yloc + 1
		ENDELSE
	ENDFOR
	label=new_label
        goodhdr = WHERE(c1hdr_ind EQ 1) & IF (goodhdr(0) NE -1) THEN all_hdr = all_hdr(goodhdr)
   ENDIF ELSE BEGIN
;**
;** END C1
;**
   IF KEYWORD_SET(FILL_COL) THEN fillcol=fill_col ELSE fillcol=median(image)
   yloc = 0
   ref_exp = exp_all(0)
   startind = 1
   IF (KEYWORD_SET(DIFF) OR KEYWORD_SET(RUNNING_DIFF) OR KEYWORD_SET(RATIO)) THEN BEGIN
      IF (KEYWORD_SET(USE_MODEL)) THEN BEGIN
         IF (use_model EQ 1) THEN all=1 ELSE all=0
         IF (use_model EQ 2) THEN any_year=0 ELSE any_year=1
         imgm = GETBKGIMG(hdr, hdrm, ALL=all, /FFV, ANY_YEAR=any_year)
         imgm = REBIN(imgm, fhsize, fvsize)
         IF (N_ELEMENTS(imgm) EQ 1) THEN BEGIN
            PRINT, '%%%MKMOVIE: Model not found'
         ENDIF ELSE BEGIN
            startind = 0
            image = imgm
            ref_exp = hdrm.exptime
            win_index = INTARR(len)
            ind0=WHERE(imgm EQ 0)
         ENDELSE
      ENDIF
      ref = image
      IF (startind EQ 1) THEN BEGIN	;** first frame is base -- not using model
         label = label(1:len-1)
         IF KEYWORD_SET(TIMES) THEN times = times(1:len-1)
         IF KEYWORD_SET(all_hdr) THEN all_hdr = all_hdr(1:len-1)
         win_index = INTARR(len-1)
      ENDIF
      IF KEYWORD_SET(BOX) AND NOT(KEYWORD_SET(BOX_REF)) THEN BEGIN
         box_img = DOUBLE(image(box_x1:box_x2,box_y1:box_y2))
         good = WHERE(box_img NE 0)
         IF (good(0) GE 0) THEN box_ref=TOTAL(box_img(good))/N_ELEMENTS(good) ELSE box=0
      ENDIF
   ENDIF ELSE BEGIN
      IF KEYWORD_SET(BOX) AND NOT(KEYWORD_SET(BOX_REF)) THEN BEGIN
         box_img = DOUBLE(image(box_x1:box_x2,box_y1:box_y2))
         good = WHERE(box_img NE 0)
         IF (good(0) GE 0) THEN box_ref=TOTAL(box_img(good))/N_ELEMENTS(good) ELSE box=0
      ENDIF
      IF KEYWORD_SET(UNSHARP) AND NOT(KEYWORD_SET(USE_SHARP)) THEN BEGIN
         IF (unsharp EQ 1)   THEN uns=25 ELSE uns=unsharp
         tmp = SMOOTH(image,uns)
         image = TEMPORARY(image) - tmp
      ENDIF
      IF KEYWORD_SET(LOG_SCL) THEN BEGIN
	 image=image
	 b=where(image le 0,dummy)
	 IF dummy ne 0 THEN image(b)=1
	 image=ALOG10(image)
      ENDIF
      IF KEYWORD_SET(SQRT_SCL) THEN BEGIN
         image = SQRT((image)>0)
      ENDIF
      win_index = INTARR(len)
;stop
      image =  BYTE(((image > bmin < bmax)-bmin)*(256-1)/(bmax-bmin))
;      image =  BYTE(((image > bmin < bmax)-bmin)*(!D.N_COLORS-1)/(bmax-bmin))
;stop
      IF KEYWORD_SET(MASK_OCC) OR KEYWORD_SET(LG_MASK_OCC) THEN BEGIN
        IF (STRLOWCASE(hdr.detector) EQ 'c3') AND (KEYWORD_SET(LG_MASK_OCC)) THEN BEGIN
         ind1 = WHERE(c3mask EQ 0)
         IF (ind1(0) NE -1) THEN image(ind1) = 0
	 ind2 = where (c3mask EQ 2)
         IF (ind2(0) NE -1) THEN image(ind2) = fillcol
        ENDIF ELSE BEGIN
         tmp_img = image & tmp_img(*) = 0 & WSET,2 & TV,tmp_img
         TVCIRCLE, r_occ_out,sunc.xcen,sunc.ycen, /FILL, COLOR=1
         tmp_img = TVRD()
         ind1 = WHERE(tmp_img NE 1)
         IF (ind1(0) NE -1) THEN image(ind1) = fillcol
        ENDELSE
      ENDIF
      IF KEYWORD_SET(FIXGAPS) THEN IF (ind0(0) NE -1) THEN image(ind0) = fillcol
      ind0=-1

      TV, image
      prev=image

      IF KEYWORD_SET(MASK_OCC) OR KEYWORD_SET(LG_MASK_OCC) THEN BEGIN
         TVCIRCLE, r_occ, sunc.xcen, sunc.ycen, /FILL, COLOR=fillcol
         TVCIRCLE, r_sun, sunc.xcen, sunc.ycen, COLOR=255, THICK=2
      ENDIF

      image = TVRD()
      image = image(img0_x1:img0_x2,img0_y1:img0_y2)
      image = REBIN(image, hsize, vsize)
      WINDOW, XSIZE = hsize, YSIZE = vsize, /PIXMAP, /FREE 
      win_index(0) = !D.WINDOW
      TV, image

      IF KEYWORD_SET(TIMES) THEN XYOUTS, 10, 10, cam+'  '+times(yloc), /DEVICE, CHARSIZE=csize

      WSET, 0 & DEVICE, COPY = [0, 0, hsize, vsize, 0, 0, win_index(yloc)]

      yloc = yloc + 1
   ENDELSE

   FOR i = startind, len-1 DO BEGIN
      PRINT, '%%MKMOVIE: Processing file: ', i+1 , ' of: ', len
      image = LASCO_READFITS(names(i), hdr)
      ind00 = WHERE(image EQ 0)
;      imgbias = OFFSET_BIAS(hdr, /SUM)
      imgbias = bias_all(i)
      BREAK_FILE, names(i), a, dir, name, ext
      IF NOT(KEYWORD_SET(NO_NORMAL)) AND $
      ( (STRMID(name(0),1,2) NE 'd_') AND (STRMID(name(0),1,2) NE 'm_') ) THEN BEGIN
         image = image - imgbias 
         IF (ind00(0) NE -1) THEN image(ind00) = 0
      ENDIF
      IF KEYWORD_SET(DEGRID) THEN image = EIT_DEGRIDN(image, STRUCT2FITSHDR(hdr), /NEW)
      IF (KEYWORD_SET(FLAT_FIELD) AND (STRLOWCASE(hdr.detector) EQ 'eit')) THEN $
          image = EIT_FLATN(image, STRUCT2FITSHDR(hdr))
      image = REDUCE_STD_SIZE(image, hdr, FULL=DOFULL)   ;** make all images 1024x1024 or 512x512
      ind00 = WHERE(image EQ 0)
      ;** if file is a level_05 image then counts are in DN and we need to account for pixel summing
      ;** file is level_05 if name is tsxxxxxx and t <=4 and s <=3
      IF ( (STRLEN(name) EQ 8) AND (VALID_NUM(STRMID(name,1,1)) ) AND (VALID_NUM(STRMID(name,0,1)) ) ) THEN BEGIN
         IF ( (FIX(STRMID(name,1,1)) LE 3) AND (FIX(STRMID(name,0,1)) LE 4) ) THEN BEGIN
            IF (hdr.sumcol NE 0) THEN image = image/(hdr.sumcol)^2
            IF (hdr.lebxsum NE 0) THEN image = image/(hdr.lebxsum)^2
         ENDIF
      ENDIF
      IF KEYWORD_SET(BOX) THEN BEGIN
         box_img = DOUBLE(image(box_x1:box_x2,box_y1:box_y2))
         good = WHERE(box_img NE 0)
         IF (good(0) GE 0) THEN BEGIN
            box_avg=TOTAL(box_img(good))/N_ELEMENTS(good)
            image = TEMPORARY(image) * (box_ref/box_avg)	;** normalize to counts in box
help, box_ref
         ENDIF
      ENDIF ELSE $
      IF NOT(KEYWORD_SET(NO_NORMAL)) THEN $
         image = TEMPORARY(image) * (ref_exp/exp_all(i))	;** normalize to reference exposure
      IF KEYWORD_SET(DIFF) THEN $
         image = TEMPORARY(image) - ref				;** subtract reference image
      IF KEYWORD_SET(RATIO) THEN BEGIN
         IF KEYWORD_SET(USE_SHARP) THEN BEGIN
            image = SHARPEN(image/ref_exp, ref/ref_exp, sharp_fact, BOX_SIZE=UNSHARP) 
         ENDIF ELSE $
         IF KEYWORD_SET(SQRT_SCL) THEN image = SQRT(TEMPORARY(image)>0) / SQRT(ref>0) ELSE $
         IF KEYWORD_SET(LOG_SCL) THEN BEGIN
            image = ALOG10(TEMPORARY(image)>1) / ALOG10(ref>1) 
         ENDIF ELSE BEGIN 					;** divide by reference image
            nonzero = WHERE(ref NE 0)
            image(nonzero) = TEMPORARY(image(nonzero)) / ref(nonzero)				
         ENDELSE
      ENDIF
      IF KEYWORD_SET(RUNNING_DIFF) THEN BEGIN
         tmp = image
         image = TEMPORARY(image) - ref				;** subtract reference image
         ref = tmp
      ENDIF
      IF KEYWORD_SET(UNSHARP) AND NOT(KEYWORD_SET(USE_SHARP)) THEN BEGIN
         tmp = SMOOTH(image,uns)
         image = TEMPORARY(image) - tmp                         ;** subtract smoothed image
      ENDIF
      IF KEYWORD_SET(RADIAL) THEN image=image/radial
      IF ( KEYWORD_SET(LOG_SCL) AND NOT(KEYWORD_SET(RATIO)) ) THEN BEGIN
	 image=image
	 b=where(image le 0,dummy)
	 IF dummy ne 0 THEN image(b)=1
	 image=ALOG10(image)
      ENDIF
      IF ( KEYWORD_SET(SQRT_SCL) AND NOT(KEYWORD_SET(RATIO)) ) THEN BEGIN
         image = SQRT((image)>0)
      ENDIF
   IF keyword_set(AUTOMAX) THEN BEGIN
	md = median(image)
	IF hdr.detector EQ 'C3' THEN BEGIN
		bmin = md * 0.95
		bmax = md * 1.13
	ENDIF ELSE BEGIN
		bmax = md * 1.24
		bmin = md * 0.82
	ENDELSE
   ENDIF
;stop
      ;image= BYTE(((image > bmin < bmax)-bmin)*(!D.N_COLORS-1)/(bmax-bmin))
      image= BYTE(((image > bmin < bmax)-bmin)*(256-1)/(bmax-bmin))

      IF KEYWORD_SET(LEEFILT) THEN image = LEEFILT(temporary(image),13,7)

   IF KEYWORD_SET(FILL_COL) THEN fillcol=fill_col ELSE fillcol=median(image)


      IF KEYWORD_SET(MASK_OCC) OR KEYWORD_SET(LG_MASK_OCC) THEN BEGIN
        IF (STRLOWCASE(hdr.detector) EQ 'c3') AND (KEYWORD_SET(LG_MASK_OCC)) THEN BEGIN
         ind1 = WHERE(c3mask EQ 0)
         IF (ind1(0) NE -1) THEN image(ind1) = 0
	 ind2 = where (c3mask EQ 2)
         IF (ind2(0) NE -1) THEN image(ind2) = fillcol
        ENDIF ELSE BEGIN
         tmp_img = image & tmp_img(*) = 0 & WSET,2 & TV,tmp_img
         TVCIRCLE, r_occ_out,sunc.xcen,sunc.ycen, /FILL, COLOR=1
         tmp_img = TVRD()
         ind1 = WHERE(tmp_img NE 1)
         IF (ind1(0) NE -1) THEN image(ind1) = fillcol
        ENDELSE
      ENDIF
      IF KEYWORD_SET(FIXGAPS) THEN BEGIN
         IF (ind0(0) NE -1) THEN image(ind0) = fillcol	;** gaps in reference img
         IF (ind00(0) NE -1) THEN BEGIN			;** gaps in this image
            IF ((fixgaps EQ 1) OR (yloc EQ 0)) THEN image(ind00) = fillcol $
            ELSE BEGIN
               image(ind00) = prev(ind00)	;** fill gaps in this img with prev image
            ENDELSE
         ENDIF
      ENDIF

      WSET, 2
      TV, image
      prev=image

      IF KEYWORD_SET(MASK_OCC) OR KEYWORD_SET(LG_MASK_OCC) THEN BEGIN
         TVCIRCLE, r_occ, sunc.xcen, sunc.ycen, /FILL, COLOR=fillcol
         TVCIRCLE, r_sun, sunc.xcen, sunc.ycen, COLOR=255, THICK=2
      ENDIF

      image = TVRD()
      image = image(img0_x1:img0_x2,img0_y1:img0_y2)
      image = REBIN(image, hsize, vsize)
      WINDOW, XSIZE = hsize, YSIZE = vsize, /PIXMAP, /FREE 
      win_index(yloc) = !D.WINDOW
      TV, image


      IF KEYWORD_SET(TIMES) THEN XYOUTS, 10, 10, cam+'  '+times(yloc), /DEVICE, CHARSIZE=csize

      WSET, 0 & DEVICE, COPY = [0, 0, hsize, vsize, 0, 0, win_index(yloc)]

      yloc = yloc + 1
      IF (KEYWORD_SET(RUNNING_DIFF)) and (KEYWORD_SET(FIXGAPS)) THEN BEGIN
         ind0 = ind00
      ENDIF
   ENDFOR
ENDELSE

   WDELETE,0            ; Added by SHH 7/12/96 to destroy viewing window
   WDELETE,2

   WRUNMOVIE, win_index, NAMES=label, HDRS=all_hdr, SUNXCEN=sunxcen, SUNYCEN=sunycen, SEC_PIX=sec_pix, $
      SAVE=save

END
