pro scc_synoptic, flist, times, datacube, COORDS=coords, NCOORDS=ncoords, SCALE=scale, BOTH=both, ALL=all, $
    	APPLYCORR=applycorr,HDRS=hdrs,MVIHDR=mvihdr,STONYHURST=stonyhurst,DOCOLOR=docolor,NOEXPCORR=noexpcorr, $
	DISPLAY=display, MOMENTS=moments, SAVEFILE=savefile, $
	MOVIEOUT=movieout, bminmax=bminmax, DOXCOLORS=doxcolors, LOUD=loud, DEBUG=debug
    
;+
; $Id: scc_synoptic.pro,v 1.12 2013/08/22 23:08:52 nathan Exp $
; NAME:;	scc_synoptic
;
; PURPOSE:
;	Converts input FITS files (EUVI-A,EUVI-B,AIA or combination) into constant-lat/lon projection.
;
; CATEGORY: movie analysis  
;
; CALLING SEQUENCE:
;	
;
; INPUTS:
;   flist   STRARR[n]  List of FITS files. EUVI, EIT, MDI, AIA or HMI. May be sub-fields.
;   
; KEYWORD inputs:
;   COORDS= 	FLTARR[4] having vertices of square [x1,x2,y1,y2] in units of carrington longitude (x) and latitude (y)
;   SCALE= 	Carrington degrees per pixel default = .1
;   	EIT center FFV      = 0.155
;   	EUVI-A center FFV   = 0.094
;   	EUVI-B center FFV   = 0.103 
;   BOTH=     if 1 use synced image from other SC if 2 use previous image from other SC (SECCHI only)
;   NOCORR=   average not subtracted from datacube
;   ALL = include AIA and nearest osc
;   APPLYCORR = return time-averaged difference of input 
;   STONYHURST = map using stonyhurst coords
;   DOCOLOR= load secchi color table
;   DISPLAY=  saves frames in bytarr format for display (pretty pictures)
;   NOEXPCORR= no exposure correction
;   MOVIEOUT= movie save name used by scc_playmovie
;   bminmax= bmin and bmax values for generic_movie
;   SAVEFILE=	Name of file to save flist, times, datacube, coords, ncoords, scale, hdrs, moments
;   /LOUD   Print processing messages
;
; OUTPUTS:
;   times   STRARR[n]  Times of each input image
;   datacube	DBLARR[len,wid,n]   Difference of ROI in constant lat/lon projection 
;
; KEYWORD outputs:
;   MOMENTS=	structure[n].spmean, varianc, skew, kurtosi
;   NCOORDS=	DBLARR[2,len,wid]   Coordinates of each pixel in output
;   HDRS=  fits headers to match input file list
;   MVIHDR=  movie header for input secchi movie routines rtheta=3 for 
;
; COMMON:   
;
; Calls from LASCO :  
;
; SIDE EFFECTS:
;	None
;
; RESTRICTIONS:
;
; PROCEDURE:
;   Each image is processed as appropriate for that instrument. The ROI is put in a
;   constant lon-lat projection. 
;   If /APPLYCORR, over all images, an average is computed for each 
;   pixel in the projected ROI. Then this average is subtracted from each image
;   and each image returned, along with moment data in a saveset.
;
; MODIFICATION HISTORY:
;
; $Log: scc_synoptic.pro,v $
; Revision 1.12  2013/08/22 23:08:52  nathan
; for EIT, unset NO_CALIBRATE so degrid works and do convert2secchi
;
; Revision 1.11  2013/08/22 15:41:56  nathan
; Add info messages; save avgpixels in sav file; compute better minmax for bytdata;
; change default scale from .25 to .1
;
; Revision 1.10  2012/10/09 17:35:42  nathan
; correct description in header
;
; Revision 1.9  2011/04/25 16:44:47  nathan
; do not use convert2secchi because of undefined wcs.position values
;
; Revision 1.8  2011/04/20 22:03:52  nathan
; add /LOUD, MOMENTS=, SAVEFILE=; print info
;
; Revision 1.7  2011/04/20 16:11:39  nathan
;  change format of coords input
;
; Revision 1.6  2011/03/31 19:07:28  mcnutt
; changed applycorrs byte scaling
;
; Revision 1.5  2011/03/24 13:05:13  mcnutt
; correct coord values for stonyhurst maps
;
; Revision 1.4  2011/03/23 18:26:02  avourlid
; Removed automax keyword, added option (DISPLAY) for saving movie in Byte or Float format. removed unnecessary loops.
;
; Revision 1.3  2011/03/18 16:52:51  mcnutt
; correct theta and radius values and automax
;
; Revision 1.2  2011/03/10 20:00:15  mcnutt
; corrected keywords
;
; Revision 1.1  2011/03/09 19:48:27  mcnutt
; first run
;

;-

debugon= keyword_set(LOUD)
IF keyword_set(DEBUG) THEN debugon=1 

       if keyword_set(mvihdr) then mkmvihdr=1 else mkmvihdr=0
       if keyword_set(movieout) or keyword_set(display) then begin
          ;display=1
          mkmvihdr=1
       endif
       if keyword_set(movieout) or keyword_set(doxcolors) then xcolors=1 else xcolors=0
;       if keyword_set(automax) then begin
;          automax=1 
;          dohdrs=1
;       endif else automax=0
       if keyword_set(stonyhurst) then carrington=0 else carrington=1
       if keyword_set(all) then begin
          both=2 ;use closest for osc if all is selected
          all=1 
          if getenv('AIA_SYNOPTIC') eq '' then begin
	    all=0
            print,'******* AIA_SYNOPTIC not defined; using SECCHI A and B only ***************'
          endif
       endif else all=0
       mreadfits,flist(0),h00,image,/dash2underscore,/silent
       instrume=h00.INSTRUME
       isse= (instrume eq 'SECCHI')
       IF isse THEN fichar=reform(byte(strmid(h00.filename,16,1))) ELSE fichar=0
       IF (fichar LE 57 AND fichar GE 48) or keyword_set(level1) THEN isl1=1 else isl1=0
       IF not isse or isl1 THEN h0=convert2secchi(h00,/NOCORRECTION) else h0=h00
       cam=strlowcase(h0.detector)
       IF isse THEN aorb=STRMID(h0.obsrvtry,7,1) ELSE aorb=h0.TELESCOP
       IF aorb EQ 'B' THEN ab=1 ELSE ab=0
	    iseu= (cam eq 'euvi')
	    isai= (cam eq 'aia')
	    isei= (h0.INSTRUME eq 'EIT')
       wavel=strlowcase(h0.WAVELNTH)
       name2prev=''
       if keyword_set(scale) then scale=scale else scale=.1
       if keyword_set(coords) then coords=coords else coords=[0.,360.,-90.,90.]
       if coords[0] gt coords[1] then coords[1]=coords[1]+360
       if coords[2] gt coords[3] then coords[2:3]=[coords[3],coords[2]]

       nx = 1 + (coords[1]-coords[0]) / scale
       lon = scale*findgen(nx) +coords[0]
       ny = 1 + (coords[3]-coords[2]) / scale
       lat = scale*findgen(ny) + coords[2]

       if keyword_set(stonyhurst) then begin
          carrington=0
          coords[0:1]=coords[0:1]-180
          lon = lon - 180
       endif else carrington=1

IF (carrington) THEN system='Carrington' ELSE system='Stonyhurst'

       w=where(lon gt 360.,count)
       if count gt 0 then lon[w] = lon[w]-360.

       lon = rebin(reform(lon,nx,1), nx, ny)
       lat = rebin(reform(lat,1,ny), nx, ny)


       len=n_Elements(flist)
       datacube=fltarr(nx,ny,len)
       ncoords=fltarr(2,nx,ny)
       ncoords(0,*,*)=lon
       ncoords(1,*,*)=lat
       times=strarr(len)
       thesum=fltarr(nx,ny) +0
       divisorm=intarr(nx,ny) +0
    	maxs=fltarr(len)
    	mins=maxs	    ; for bytscl
 
       for i=0,len-1 do begin
    	    print,'Processing ',trim(i),' of ',trim(len-1),': ',flist[i]
          if iseu then $
    	    	secchi_prep, flist(i), hdr, image, silent=~debugon, noexpcorr=noexpcorr,/update_hdr_off ELSE $
          if isei then begin 
    	    	EIT_PREP,  flist(i), fitshdr, image, /RESP, /NRL, /FLOAT, /FILTER, /NO_ROLL, $
    	    	     NO_CALIBRATE=0, FILL=fltarr(32,32), VERBOSE=debugon
		; Do not do roll correction - done by interpolate below
		hdr = convert2secchi(fitshdr)
		;hdr=fitshead2struct(fitshdr,/dash2underscore)
		;image=image/hdr.exptime
		IF ~keyword_set(NOEXPCORR) THEN image=image/hdr.exptime
          endif ELSE BEGIN
	    ;see scc_euvi_synoptic for more AIA options such as ssc_get_nearest_aia and 171 correction factors to apply.
                 mreadfits,flist(i),hdr,image,/dash2underscore,silent=~debugon
		 ;hdr = convert2secchi(fitshdr)
		 if ~keyword_set(noexpcorr) then image=image/hdr.exptime
	  ENDELSE
          times(i)=hdr.date_obs
          wcs= fitshead2wcs(hdr)

          wcs_convert_to_coord, wcs, coord, 'hg', lon, lat, carrington=carrington
          pixel = wcs_get_pixel(wcs, coord)

          map = interpolate(image, reform(pixel[0,*,*]), reform(pixel[1,*,*]), missing=!values.f_nan, _extra=_extra)
	  
          if iseu and (keyword_set(both) or all eq 1) then begin
	       name2 = scc_find_synced(flist(i))
	       IF name2 EQ '' and both gt 1 THEN name2=name2prev  ; use previous image if matching image is missing
               IF name2 NE '' then begin
                 secchi_prep, name2, hdro, image, /silent
                 wcso= fitshead2wcs(hdro)
                 wcs_convert_to_coord, wcso, coordo, 'hg', lon, lat, carrington=carrington
                 pixel = wcs_get_pixel(wcso, coordo)
                 map_o = interpolate(image, reform(pixel[0,*,*]), reform(pixel[1,*,*]), missing=!values.f_nan, _extra=_extra)
                 w = where_missing(map)
                 map[w] = map_o[w]
                 dist1 = total((coord/hdr.rsun)^2, 1)
                 dist2 = total((coordo/hdro.rsun)^2, 1)
                 w = where(dist2 lt dist1, count)
                 if count gt 0 then map[w] = map_o[w]
                 name2prev=name2
               ENDIF
               IF all eq 1 then begin
                  undefine,hc
	          scc_get_nearest_aia_synoptic, hdr.date_obs, hc, image, wavelength=hdr.WAVELNTH ,/wladj
                  if datatype(hc) eq 'STC' then begin
                      wcs_c = fitshead2wcs(hc)
                      lon_c = lon
                      wcs_convert_diff_rot, wcs, wcs_c, lon_c, lat, carrington=carrington
                      wcs_convert_to_coord, wcs_c, coord_c, 'hg', lon_c, lat, carrington=carrington
                      pixel_c = wcs_get_pixel(wcs_c, coord_c)
                      map_c = interpolate(image, reform(pixel_c[0,*,*]), reform(pixel_c[1,*,*]), missing=!values.f_nan, _extra=_extra)
                      rsun_c = 648000.d0 * wcs_rsun() / (!dpi * wcs_c.position.dsun_obs)
                      dist_c = total((coord_c/rsun_c)^2, 1)
                      w = where(((dist_c lt dist1) or (not finite(dist1))) and $
                                      ((dist_c lt dist2) or (not finite(dist2))) and finite(dist_c),count)
                      if count gt 0 then map[w] = map_c[w]
		  endif else print,'closest AIA image not found '+ hdr.date_obs
	       ENDIF

          endif   
	     
          w =  where_not_missing(map, count)
          if count gt 0 then begin
    	    thesum(w)=thesum(w)+map(w)
            divisorm(w)=divisorm(w)+1
          endif
          datacube(*,*,i) =map
	  if i eq 0 then hdrs=hdr else hdrs=[hdrs,hdr]
      endfor 

      if keyword_set(applycorr) then begin
         avgpixels=thesum/divisorm
         for k=0,len-1 do begin
            map=datacube(*,*,k)
            w=where_not_missing(map,wnm)
	    IF wnm GT 1 THEN map(w)=map(w)-avgpixels(w) ELSE BEGIN
		print,'No valid data for ',flist[k]
	    	help,k
	    ENDELSE
	    datacube(*,*,k)=map     	    ;;; = pixel fluctuations = difference images
         endfor
	 
      endif

    moments=make_array(len,value={spmean:0d,varianc:0d,skew:0d,kurtosi:0d})
    FOR k=0,len-1 DO BEGIN
    	mk=moment(datacube[*,*,k],/nan)
	moments[k].spmean =mk[0]    	    ;;; spatial average
	moments[k].varianc=mk[1]    	    ;;; variance sigma^2
	moments[k].skew   =mk[2]    	    ;;; skew
	moments[k].kurtosi=mk[3]    	    ;;; kurtosis	
    	mins[k]=min(datacube[*,*,k],max=mmax)
    	maxs[k]=mmax
	    	
    ENDFOR
    
      if keyword_set(docolor) then begin 
	device, decomposed=0
	load_secchi_color,hdr
      endif 

      if mkmvihdr then begin
         def_mvi_hdr,file_hdr
         file_hdr.NF = n_Elements(datacube(0,0,*))
         file_hdr.NX = n_Elements(datacube(*,0,0)) 
         file_hdr.NY = n_Elements(datacube(0,*,0))
         file_hdr.SEC_PIX  =scale
         if keyword_set(stonyhurst) then file_hdr.RTHETA  =4 else file_hdr.RTHETA  =3
         file_hdr.RADIUS0 =coords(2)	; latitude
         file_hdr.RADIUS1 =coords(3)
         file_hdr.THETA0  =coords(0)	; longitude
         file_hdr.THETA1  =coords(1)
    	 file_hdr.sunycen =0.0
    	 file_hdr.sunxcen =0.0
	 mvihdr=file_hdr
      endif

     ; if binmax is not passed then automax is assumed
      if ~keyword_set(applycorr) then begin
        bytdata = bytarr(nx,ny,len) 
        if ~keyword_set(bminmax) then begin
          tmin=0.5 & tmax=3.5
          if wavel eq 171 then tmax=3.37503
          if wavel eq 195 then tmax=3.43486
          if wavel eq 284 then tmax=3.27
          if wavel eq 304 then tmax=4.09605
	  bminmax=[0, 255]
        endif else begin
	  tmin=bminmax(0) & tmax=bminmax(1)
        endelse
        image= datacube
        tz= where (~Finite(image))      
	if tz(0) gt -1 then image(where (~Finite(image)))=0
        image = ALOG10(image+3)>0
        bytdata = BYTE(((image > tmin < tmax)-tmin)*(!D.TABLE_SIZE-1)/(tmax-tmin))
	image = 0
      endif else begin
      	tmax=median(maxs)
	tmin=median(mins)
        bytdata=bytscl(datacube,min=tmin,max=tmax)
        bminmax=[tmin,tmax]
	 wnd,20,avgpixels<tmax>tmin
	 xyouts,5,5,'avgpixels',/device
      endelse
      
     print,''
    print,"Using flist=['"+arr2str(flist,"', '")+"']"
   print,''
    message,system+' Coordinates [x1,x2,y1,y2]: '+arr2str(trim(coords),','),/info
    wait,3

    if keyword_set(display) then BEGIN
    	;help,tmin,tmax
	
	generic_movie, bytdata, hdrs=hdrs,file_hdr=mvihdr,save = movieout, doxcolors=xcolors 
    	print,''
    	message,'scaled mvi from '+trim(tmin)+' to '+trim(tmax)+' over '+trim(!D.TABLE_SIZE-1),/info
    ENDIF
    
    IF keyword_set(SAVEFILE) THEN BEGIN
	break_file,savefile,disk,dir,root,ext
	if ext ne '.sav' then savefile=root+'.sav'	
	print,'Saving in ',savefile,':'
	print,'avgpixels= average of each pixel in ROI over all frames'
	print,'datacube = ROI with avgpixels subtracted from each'
	print,'ncoords	= Carrington coords of each pixel in ROI'
	print,'coords	= Carrington coords of vertices of ROI'
	print,'scale	= Carrington degree per pixel'
	print,'hdrs 	= header structure of flist'
	print,'flist	= list of FITS files'
	print,'times	= date-obs of flist'
	print,'moments	= structure for each frame {spmean,varianc,skew,kurtosi}'
	print,''
	save,filename=savefile,flist, times, datacube, coords, ncoords, scale, hdrs, moments, avgpixels
    ENDIF

    IF iseu THEN message,'EUVI units of datacube are Detected Photons',/info
    IF isei THEN message,'EIT units of datacube are corrected DN/sec',/info
    IF isai THEN message,'AIA units of datacube are uncorrected DN/sec',/info
end
