; $Id: v2a.pro,v 1.14 2012/12/19 17:25:21 mcnutt Exp $
; NAME:
;	V2
;
; PURPOSE:
;	Widgetized wrapper for jmaps2.pro
;
; CATEGORY:
;	JMAPS
;
; CALLING SEQUENCE:
;	V2
;
; INPUTS:
;	None
;
; OPTIONAL INPUTS:
;	None
;	
; KEYWORD PARAMETERS:
;	None
;
; OUTPUTS:
;	A .jmp file is saved.
;
;
; PROCEDURE:
;	Collects various jMap parameters from a widget and uses them 
;	to make the appropriate call to jmaps2.pro
;
; EXAMPLE:
;	V2
;
; MODIFICATION HISTORY:
; 	Written by:	Jeff Walters, Aug 2001
; $Log: v2a.pro,v $
; Revision 1.14  2012/12/19 17:25:21  mcnutt
; replace variable list
;
; Revision 1.13  2011/03/22 21:43:00  sheeley
; nr - fix instrument if file_list empty
;
; Revision 1.12  2011/02/24 23:17:34  nathan
; fix ix bug; update default slit width for c2,c3,cor1
;
; Revision 1.11  2011/02/24 18:44:05  nathan
; Allow user to adjust range, slitwidth, skip frames after selecting the
; movie and running Check Slit
;
; Revision 1.10  2011/02/14 23:26:44  nathan
; extend common v2_common to check chosen instrument matches imported file
;
; Revision 1.9  2010/10/06 21:36:06  nathan
; fix file_list where same tel in different dir
;
; Revision 1.8  2010/06/14 13:01:48  cooper
; Changed default to not defining the satellite
;
; Revision 1.7  2010/01/19 19:12:31  nathan
; minor printed-info change
;
; Revision 1.6  2009/07/15 20:33:19  cooper
; fixed error in checking angles from last update
;
; Revision 1.5  2009/07/08 13:57:29  cooper
; added capability to check position angles
;
; Revision 1.4  2009/06/15 16:16:25  cooper
; modified widget, added satellite info
;
; Revision 1.3  2008/06/26 19:14:59  nathan
; added debug features
;
; Revision 1.2  2008/03/19 16:11:00  nathan
; defined DIR_COMMON and mvi_dir, jmap_dir if not defined
;
; Revision 1.1  2007/11/08 16:56:41  nathan
; moved from adam/jmaps2a
;
;	07.10.26, NRich - Added mvi version to sccmvihdr2struct calls
;-

PRO set_times
COMMON v2_common, main1, jmp, mypath, savepath, file_list, curr_list, savefile, fitsdir, tel_ranges, ranges, width, times, frame_skip, $
	import_fields, file_fields, opt_fields, time_fields, fin_fields, debugon, sats, instrs

	times[2:3] = temporary(times[2:3]) > times[0] < times[1]
	IF(times[2] EQ times[1]) THEN times[2] = times[0]
	IF(times[3] EQ times[0]) THEN times[3] = times[1]
	FOR i=0,1 DO WIDGET_CONTROL, time_fields[i], SET_VALUE=[times[i+2], $
		(i EQ 0) ? times[0] : times[2], (i EQ 1) ? times[1] : times[3]]
	t0 = UTC2STR(TAI2UTC(double(times[2])))
	tpos = strpos(t0, 'T')
	IF(tpos GT 0) THEN t0 = strmid(t0, 0, tpos) + ' ' + strmid(t0, tpos+1)
	t1 = UTC2STR(TAI2UTC(double(times[3])))
	tpos = strpos(t1, 'T')
	IF(tpos GT 0) THEN t1 = strmid(t1, 0, tpos) + ' ' + strmid(t1, tpos+1)
	WIDGET_CONTROL, time_fields[2], SET_VALUE='Start time: ' + t0
	WIDGET_CONTROL, time_fields[3], SET_VALUE='End time: ' + t1
END

PRO MAIN1_Event, Event
COMMON v2_common
COMMON DIR_COMMON, mvi_dir, jmap_dir, median_dir, diff_dir, image_dir

IF datatype(mvi_dir) EQ 'UND' THEN mvi_dir='./' 
IF datatype(jmap_dir) EQ 'UND' THEN jmap_dir='./' 
    
  IF(datatype(event) EQ 'UND') THEN RETURN

  START_STR = '___V2_____________________________________________________'
  FM_STR='___V2______ '

  WIDGET_CONTROL,Event.Id,GET_UVALUE=Ev
  CASE Ev OF 

  'import': BEGIN
	IF (DATATYPE(mypath) eq 'UND') THEN path = mvi_dir ELSE path = mypath
	curr_list = dialog_pickfile(filter = '*.mvi', path = path, GET_PATH=mypath,/MULTIPLE_FILES)
;	curr_list=list
	ncur=n_elements(curr_list)
	;IF(list[0] NE '') THEN BEGIN
	;	IF(curr_list[0] EQ '') THEN curr_list = list $
	;		ELSE curr_list = [curr_list, list]
	;	;WIDGET_CONTROL, import_fields[11], /SENSITIVE
	;ENDIF
	;END tjc 6/12/09
  ;'finalize': BEGIN
	IF(curr_list[0] NE '') THEN BEGIN
		instr = WIDGET_INFO(import_fields[0], /DROPLIST_SELECT)
		this_range = fltarr(2)
		WIDGET_CONTROL, import_fields[3], GET_VALUE=tmp
		this_range[0] = FLOAT(tmp)
		WIDGET_CONTROL, import_fields[4], GET_VALUE=tmp
		this_range[1] = FLOAT(tmp)
		WIDGET_CONTROL, import_fields[6], GET_VALUE=tmp
		this_width = FLOAT(tmp[0])
		WIDGET_CONTROL, import_fields[9], GET_VALUE=tmp
		this_skip = fix(tmp[0])

		FOR i=0,n_elements(curr_list)-1 DO BEGIN
			openr, lu, curr_list[i], /get_lun
			sccread_mvi, lu, file_hdr, ihdrs, imgs, swapflag
			
			FOR j=0,1 DO BEGIN
				img_hdr = sccmvihdr2struct(ihdrs[j*(file_hdr.nf-1)],file_hdr.ver) ; nbr, 10/26/07
				; changed to sccmvihdr2struct - nbr,10/16/07
    	    	    	    	instr = WIDGET_INFO(import_fields[0], /DROPLIST_SELECT)
				IF instrs[instr] NE img_hdr.detector THEN BEGIN
				    message,'',/info
				    message,'Please select correct Instrument and desired Range.',/info
				    message,'',/info
				    return
				ENDIF 
				str = STRING(img_hdr.date_obs) + ' ' + STRING(img_hdr.time_obs)
				curr_tai = LONG(UTC2TAI(STR2UTC(str)))
				IF(curr_tai*(2*j-1) GT times[j]*(2*j-1)) THEN BEGIN
					IF(times[j+2] EQ times[j]) THEN times[j+2] = curr_tai
					times[j] = curr_tai
				ENDIF
			ENDFOR
			close, lu
			free_lun, lu
		ENDFOR
		set_times

		dir = ''
		IF(file_list[0] EQ '') THEN BEGIN
			file_list = reform(curr_list, 1, n_elements(curr_list))
			ranges = transpose(this_range)
			width = this_width
			frame_skip = this_skip
			fitsdir = dir
		ENDIF ELSE BEGIN
			file_size = size(file_list)
			
			; test for existing telescope in file_list by upper range value
			telind=where(ranges[*,1] EQ this_range[1],nt)
			IF nt GT 0 THEN BEGIN
			    new_files = strarr(file_size[1],     file_size[2]+ncur)
			    new_files[*,0:file_size[2]-1]=file_list
			    new_files[telind,file_size[2]:*]=curr_list
			ENDIF ELSE BEGIN
			    new_files = strarr(file_size[1] + 1, file_size[2] > n_elements(curr_list))
			    new_files[0:file_size[1]-1,0:file_size[2]-1] = file_list
			    new_files[file_size[1],0:n_elements(curr_list)-1] = curr_list
			    ranges = [ranges, transpose(this_range)]
			    width = [width, this_width]
			    frame_skip = [frame_skip, this_skip]
			    fitsdir = [fitsdir, dir]
			ENDELSE
			file_list = new_files
			undefine, new_files
		ENDELSE
		file_size = size(file_list)
		IF(file_size[0] EQ 1) THEN file_list = reform(file_list, file_size[1], 1)
		curr_list = ''
		IF(file_list[0] NE '') THEN BEGIN
			wlist = file_list[where(file_list NE '')]
			WIDGET_CONTROL, file_fields[1], SET_VALUE=wlist
		ENDIF
		;WIDGET_CONTROL, import_fields[11], SENSITIVE=0
	ENDIF
      END
  'instrument': BEGIN
;
;--Refresh range, slit width, skip frames with current values for top of stack.
;
    	sif=n_elements(file_list)
	
	ix=sif-1
	IF file_list[ix] NE '' THEN BEGIN
	    this_range = fltarr(2)
	    WIDGET_CONTROL, import_fields[3], GET_VALUE=tmp
	    this_range[0] = FLOAT(tmp)
	    WIDGET_CONTROL, import_fields[4], GET_VALUE=tmp
	    this_range[1] = FLOAT(tmp)
	    WIDGET_CONTROL, import_fields[6], GET_VALUE=tmp
	    this_width = FLOAT(tmp[0])
	    WIDGET_CONTROL, import_fields[9], GET_VALUE=tmp
	    this_skip = fix(tmp[0])
    	    ranges[ix,*]=this_range
	    width[ix]=this_width
	    frame_skip[ix]=this_skip
    	ENDIF
	instr = WIDGET_INFO(import_fields[0], /DROPLIST_SELECT)
	WIDGET_CONTROL, import_fields[3], SET_VALUE = STRTRIM(STRING(tel_ranges[0,instr]),2)
	WIDGET_CONTROL, import_fields[4], SET_VALUE = STRTRIM(STRING(tel_ranges[1,instr]),2)
	CASE instr OF
    	;  instrs=['C2', 'C3', 'EUVI', 'COR1', 'COR2', 'HI1', 'HI2']
		0: curr_width = 0.2
		1: curr_width = 1.0
		2: curr_width = 0.12
		3: curr_width = 0.15
		4: curr_width = 1.0
		5: curr_width = 2.5
		6: curr_width = 3.6
	ENDCASE

        SWITCH instr of
                0:
		1: BEGIN
		   WIDGET_CONTROL, import_fields[1], SET_DROPLIST_SELECT=0
		   BREAK
                   END
                2:
		3:
		4:
		5:
		6: WIDGET_CONTROL, import_fields[1], SET_DROPLIST_SELECT=1
        ENDSWITCH
	WIDGET_CONTROL, import_fields[6], SET_VALUE = STRTRIM(STRING(curr_width), 2)
	END
  'time0': IF(file_list[0] NE '') THEN BEGIN
	WIDGET_CONTROL, time_fields[0], GET_VALUE=tmp
	times[2] = tmp[0]
	set_times
	ENDIF
  'time1': IF(file_list[0] NE '') THEN BEGIN
	WIDGET_CONTROL, time_fields[1], GET_VALUE=tmp
	times[3] = tmp[0]
	set_times
	ENDIF
  'options': BEGIN
      IF Event.Select THEN Sel = 1 ELSE Sel = 0
      CASE Event.Value OF
      0: BEGIN
            END
      1: BEGIN
            jmp.point_filter = Sel
            END
      2: BEGIN
            jmp.contrast = Sel
            END
      3: BEGIN
            jmp.chop = Sel
            END
      ELSE: Message,'Unknown button pressed'
      ENDCASE
      END
  'pa': BEGIN
      END
  'save': BEGIN
	IF (DATATYPE(savepath) eq 'UND') THEN path = jmap_dir ELSE path=savepath
	savefile = [savefile, dialog_pickfile(PATH = path, filter='*.jmp',$
		title='Select jMap Filename', GET_PATH=savepath)]
	PRINT, fm_str,'filenames = ', savefile
	END
  'start': BEGIN
	s = where(savefile NE '')
	IF(s[0] LT 0) THEN BEGIN
		savefile = dialog_pickfile(PATH = jmap_dir, filter='*.jmp',$
		title='Select jMap Filename')
		s = where(savefile NE '')
		IF(s[0] LT 0) THEN BEGIN
			message, 'No save file selected', /informational
			RETURN
		ENDIF
	ENDIF
	savefile = savefile[s]
;
;--Refresh range, slit width, skip frames with current values for top of stack.
;
    	sif=size(file_list)
	ix=sif[1]-1
	this_range = fltarr(2)
	WIDGET_CONTROL, import_fields[3], GET_VALUE=tmp
	this_range[0] = FLOAT(tmp)
	WIDGET_CONTROL, import_fields[4], GET_VALUE=tmp
	this_range[1] = FLOAT(tmp)
	WIDGET_CONTROL, import_fields[6], GET_VALUE=tmp
	this_width = FLOAT(tmp[0])
	WIDGET_CONTROL, import_fields[9], GET_VALUE=tmp
	this_skip = fix(tmp[0])
    	ranges[ix,*]=this_range
	width[ix]=this_width
	frame_skip[ix]=this_skip

	WIDGET_CONTROL, opt_fields[3], GET_VALUE=angle
	WIDGET_CONTROL, opt_fields[0], GET_VALUE=opts_vector
	WIDGET_CONTROL, opt_fields[2], GET_VALUE=proj_type
      
	pa = strsplit(angle, ' ,.;', /extract)
	ang_range = fix(strsplit(pa[0], '-', /extract))
	IF(n_elements(ang_range) EQ 2) THEN BEGIN
		IF(n_elements(pa) GT 1) THEN diff = fix(pa[1]) ELSE diff = 1
		pa = ang_range[0]
		next_ang = pa + diff
		WHILE(next_ang LE ang_range[1]) DO BEGIN
			pa = [pa, next_ang]
			next_ang = next_ang + diff
		ENDWHILE
	ENDIF ELSE pa = fix(temporary(pa))
	print,''
	print, 'Saving position angles: ', pa
	wait,2
	jmp.no_movie = opts_vector(0)
	jmp.point_filter = opts_vector(1)
	jmp.contrast = opts_vector(2)
	jmp.chop = opts_vector(3)
    	help,proj_type
	jmp.proj_type = proj_type

	width = (width/215.) * (180./!pi) ;from solar radii to degrees
        get_sat=WIDGET_INFO(import_fields[10],/button_set)

       IF (get_sat EQ 1) THEN BEGIN
	jmaps2a, mvi_files = file_list, time0=times[2], time1=times[3], ranges = ranges, fitsdir = fitsdir1, $
	pa = pa, savefile = savefile, pfilter = jmp.point_filter, debug=debugon, $
	dfilter = jmp.contrast, chop = jmp.chop, proj_type = jmp.proj_type, width=width, frame_skip=frame_skip, $
	telescope=sats[WIDGET_INFO(import_fields[1],/DROPLIST_SELECT)]
	ENDIF ELSE BEGIN
	jmaps2a, mvi_files = file_list, time0=times[2], time1=times[3], ranges = ranges, fitsdir = fitsdir1, $
	pa = pa, savefile = savefile, pfilter = jmp.point_filter, debug=debugon, $
	dfilter = jmp.contrast, chop = jmp.chop, proj_type = jmp.proj_type, width=width, frame_skip=frame_skip
        ENDELSE
	PRINT, START_STR
	WIDGET_CONTROL, MAIN1, /DESTROY
	END
   'check':BEGIN
;
;--Refresh range, slit width, skip frames with current values for top of stack.
;
    	sif=size(file_list)
	ix=sif[1]-1
	;ix=n_elements(file_list)-1
	this_range = fltarr(2)
	WIDGET_CONTROL, import_fields[3], GET_VALUE=tmp
	this_range[0] = FLOAT(tmp)
	WIDGET_CONTROL, import_fields[4], GET_VALUE=tmp
	this_range[1] = FLOAT(tmp)
	WIDGET_CONTROL, import_fields[6], GET_VALUE=tmp
	this_width = FLOAT(tmp[0])
	WIDGET_CONTROL, import_fields[9], GET_VALUE=tmp
	this_skip = fix(tmp[0])
    	ranges[ix,*]=this_range
	width[ix]=this_width
	frame_skip[ix]=this_skip

	WIDGET_CONTROL, opt_fields[3], GET_VALUE=angle
	WIDGET_CONTROL, opt_fields[0], GET_VALUE=opts_vector
	WIDGET_CONTROL, opt_fields[2], GET_VALUE=proj_type
	pa = strsplit(angle, ' ,.;', /extract)
	ang_range = fix(strsplit(pa[0], '-', /extract))
	IF(n_elements(ang_range) EQ 2) THEN BEGIN
		IF(n_elements(pa) GT 1) THEN diff = fix(pa[1]) ELSE diff = 1
		pa = ang_range[0]
		next_ang = pa + diff
		WHILE(next_ang LE ang_range[1]) DO BEGIN
			pa = [pa, next_ang]
			next_ang = next_ang + diff
		ENDWHILE
	ENDIF ELSE pa=fix(temporary(pa))
	jmp.proj_type = proj_type
	tmpwidth = (width[ix]/215.) * (180./!pi) ;from solar radii to degrees
	
	x=jmap_construct2a(file_list[ix], pa, fitsdir=fitsdir1, width=tmpwidth, proj_type=proj_type, range=ranges[ix,*], /check_angs, DEBUG=debugon)
	END

	ELSE: ;default event
  ENDCASE
END


; DO NOT REMOVE THIS COMMENT: END MAIN1
; CODE MODIFICATIONS MADE BELOW THIS COMMENT WILL BE LOST.



PRO v2a, GROUP=Group, debug=debug
COMMON v2_common

  IF N_ELEMENTS(Group) EQ 0 THEN GROUP=0
  IF keyword_set(DEBUG) THEN debugon=1 ELSE debugon=0
  
  junk   = { CW_PDMENU_S, flags:0, name:'' }
  START_STR = '___V2__________________________________________________________'

   TEL_RANGES = [[0.0,1.68],[1.07,7.99],[0.0,0.45],[0.0,1.07],[0.0,4.2],[3.28,24.5],[18.36,88.36]] ; C2, C3, EUVI, COR1, COR2, HI1, HI2 ranges in degrees along ecliptic (estimates from STEREO mission description)
  
  strct = {point_filter:0, contrast:0, no_movie:0, chop:0, proj_type:0}
  jmp = replicate(strct, 1)
  jmp.proj_type = 0		; nbr, 11/7/07 - default is spherical projection - nrs changed back to 0 again
  file_list = ''
  curr_list = ''
  savefile = ''
  ranges = 0.0
  times = [1e+100, -1e+100, 0, 0]  ; start and end times of selected movies; and selected interval within those
  frame_skip = 0
  sats=['SOHO', 'A', 'B']
  instrs=['C2', 'C3', 'EUVI', 'COR1', 'COR2', 'HI1', 'HI2']
  
  MAIN1 = WIDGET_BASE(GROUP_LEADER=Group, COLUMN=4, SPACE=25, MAP=1, TITLE='jMaps2', UVALUE='MAIN1')

  import_base = WIDGET_BASE(MAIN1, COLUMN=1, SPACE=20, XPAD=5, YPAD=15, FRAME=4, MAP=1, TITLE='import_base', UVALUE='BASE2')
  base21 = widget_base(import_base, row=1, map=1, uvalue='base21')
  base22 = widget_base(import_base, row=1, map=1, uvalue='base22')
  base23 = widget_base(import_base, row=1, map=1, uvalue='base23')
  base26 = widget_base(import_base, row=1, map=1, uvalue='base26')
  base24 = widget_base(import_base, row=1, map=1, uvalue='base24')
  base25 = widget_base(import_base, column=1, map=1, uvalue='base25')

  import_fields= WIDGET_DROPLIST(base21, UVALUE = 'instrument', VALUE = instrs, title='Instrument')
  import_fields = replicate(import_fields, 11) 
  import_fields[1] = WIDGET_DROPLIST(base21, UVALUE='sat', VALUE=sats, title='Satellite')
  import_fields[2] = WIDGET_LABEL(base22, UVALUE='range_label', VALUE='Range (degrees along ecliptic):')
  import_fields[3] = WIDGET_TEXT(base22, UVALUE = 'range1', XSIZE = 5, YSIZE = 1, /EDITABLE)
  import_fields[4] = WIDGET_TEXT(base22, UVALUE = 'range2', XSIZE = 5, YSIZE = 1, /EDITABLE)
  WIDGET_CONTROL, import_fields[3], SET_VALUE = STRTRIM(STRING(tel_ranges[0,0]),2)
  WIDGET_CONTROL, import_fields[4], SET_VALUE = STRTRIM(STRING(tel_ranges[1,0]),2)
  import_fields[5] = WIDGET_LABEL(base23, UVALUE='width_label', VALUE='Slit width (solar radii):')
  import_fields[6] = WIDGET_TEXT(base23, UVALUE = 'width', value='0.4', XSIZE = 5, YSIZE = 1, /EDITABLE)
  import_fields[8] = WIDGET_LABEL(base26, VALUE='Frames to skip')
  import_fields[9] = WIDGET_TEXT(base26, UVALUE='frame_skip', VALUE='1', XSIZE=4, /EDITABLE)
  import_fields[7] = WIDGET_BUTTON(base24, UVALUE='import', VALUE='Import File(s)')
  ;import_fields[11] = WIDGET_BUTTON(base24, UVALUE='finalize', VALUE='Finish', SENSITIVE=0)
  buttonbase = widget_base(base24, row=1, map=1, uvalue='buttonbase',/NONEXCLUSIVE)
  import_fields[10]= WIDGET_BUTTON(buttonbase, UVALUE='sat?', VALUE='Define Satellite')

  file_fields = WIDGET_LABEL(base25, VALUE='Selected Files')
  file_fields = replicate(file_fields, 2)
  file_fields[1] = WIDGET_LIST(base25, value='', XSIZE=36, YSIZE=4, EVENT_PRO='event_pro')

  opt_base = WIDGET_BASE(MAIN1, COLUMN=1, FRAME=1, MAP=1, TITLE='options', UVALUE='opt_base')

  opt_fields = CW_BGROUP(opt_base, ['No Movie', 'Point Filter', 'Contrast Enhance', 'Chop'], NONEXCLUSIVE=1, $
      LABEL_TOP='Options', UVALUE='options', SET_VALUE = [0, 0, 0, 0])
  opt_fields = replicate(opt_fields, 5)
  opt_fields[1] = WIDGET_LABEL(opt_base, VALUE='Projection')
  opt_fields[2] = CW_BGROUP(opt_base, ['None', 'Spherical'], /EXCLUSIVE, UVALUE='proj_type', SET_VALUE=1)

  time_fields = WIDGET_LABEL(opt_base, VALUE='Start time: none                     ')
  time_fields = replicate(time_fields, 4)
  time_fields[0] = CW_FSLIDER(opt_base, MINIMUM=0.0, MAXIMUM=1.0, VALUE=0.0, UVALUE='time0', $
	XSIZE=200, SCROLL=.005, /SUPPRESS_VALUE)
  time_fields[3] = WIDGET_LABEL(opt_base, VALUE='End time: none                     ')
  time_fields[1] = CW_FSLIDER(opt_base, MINIMUM=0.0, MAXIMUM=1.0, VALUE=1.0, UVALUE='time1', $
	XSIZE=200, SCROLL=.005, /SUPPRESS_VALUE)

  fin_base = WIDGET_BASE(MAIN1, COLUMN=1, SPACE=20, XPAD=5, YPAD=15, FRAME=5, MAP=1, TITLE='final', UVALUE='fin_base')

  opt_fields[3] = CW_FIELD(fin_base, VALUE='', ROW=1, /RETURN_EVENTS, FRAME=2, TITLE='Angle(s)', UVALUE='pa', XSIZE=10)
  opt_fields[4] = WIDGET_BUTTON(fin_base, VALUE='Check Slits', UVALUE='check')

  fin_fields = WIDGET_BUTTON(fin_base, UVALUE='save', VALUE='Select Save File', YSIZE=35)
  fin_fields = replicate(fin_fields, 2)
  fin_fields[1] = WIDGET_BUTTON(fin_base, FRAME=1, UVALUE='start', VALUE='Build jMap', XSIZE=15, YSIZE=50)

  WIDGET_CONTROL, MAIN1, /REALIZE
  
  PRINT, START_STR
  XMANAGER, 'MAIN1', MAIN1

END
