;+
;NAME:
;	eis_define_fit.pro
;PURPOSE:
;	Makes fitting templates for EIS data.
;	Especially good for very large wavelength windows (by setting the view keyword).
;	After running, the user can modify either the template & wvl_select structures or the text files.
;
;INPUTS:
;	input_data (str or struct) == filename of a Level-1 EIS fits file, or a windata structure
;	iwin (int) == window number within EIS fits file (irrelevant if windata is the input_data)
;KEYWORDS:
;	offset (fltarr) == array of wavelength offsets created by eis_update_fitdata.pro
;	outdir (str) == directory to use for outputted files
;	no_out (/) == set to not output the text files
;	subwin (/) == set to split wavelength window into subsets, and choose a subset (only necessary for full CCD observations)
;			(intarr) == set first index as number of subsets, and second as index of subset to use
;	view (int) == number of chunks to break a window into for easier identification of spectral lines
;OUTPUTS:
;	template (struct) == structure created by eis_fit_template.pro
;	wvl_select (struct) == structure created by eis_wvl_select.pro
;	A text file for each output structure is also written to outdir, unless the no_out keyword is set.
;
;EXAMPLES:
;IDL> eis_define_fit, 'eis_l1_20070116_143113.fits.gz', 2
;IDL> eis_define_fit, windata, view=8
;IDL> eis_define_fit, 'eis_l1_20070116_143113.fits.gz', 2, tem_2_0, wvl_2_0, view=4, subwin=[2,0], /no_out
;
;CONTACT:
;	Gary Kilper (GSFC/ORAU; garyk1@gmail.com)
;	Apr 14, 2011: Initial public version
;-

pro eis_define_fit, input_data, iwin, template, wvl_select, offset=offset, $
			outdir=outdir, subwin=subwin, view=view, no_out=no_out


;examples of how to set parameters and do line-tying within the template struct
;IDL> template.nback = 1
;IDL> template.lines(1).cen_tie = 0
;IDL> template.lines(1).cen_tie_val = .083
;IDL> template.lines(1).wid_tie = 0
;IDL> template.lines(1).peak_tie = 0
;IDL> template.lines(1).peak_tie_val = .40


;read in windata structure and set output string
if size(input_data, /type) EQ 8 then begin
	windata = input_data
	iwin = windata.iwin(0)
endif else windata = eis_getwindata(input_data, iwin, refill=1)
if ~keyword_set(offset) then offset = windata.wave_corr
mreadfits, input_data, fits_index
iwin_id = strmid(fits_index.date_obs,0,10) + '_' + strmid(fits_index.date_obs,11,2) + $
		strmid(fits_index.date_obs,14,2) + strmid(fits_index.date_obs,17,2) + '_eis_' + strtrim(iwin,2)


;check whether to use a subwindow
if keyword_set(subwin) then begin
	if n_elements(subwin) NE 2 then begin
		read, subwin_0, prompt='Enter number of subwindows to split windata into: '
		read, subwin_1, prompt='Enter index of subwindow to use: '
		subwin = [subwin_0, subwin_1]
	endif
	sub_id = '_' + strtrim(subwin(1),2)
	nl = fix(windata.nl / subwin(0))
	windata.nl = nl
	windata = rep_tag_value(windata, windata.int[subwin(1)*nl:(subwin(1)+1)*nl-1,*,*], 'int')
	windata = rep_tag_value(windata, windata.err[subwin(1)*nl:(subwin(1)+1)*nl-1,*,*], 'err')
	windata = rep_tag_value(windata, windata.wvl[subwin(1)*nl:(subwin(1)+1)*nl-1], 'wvl')
endif else sub_id = ''


;set output directory
if keyword_set(outdir) then begin
	if ~file_test(outdir, /dir) then mk_dir, outdir
	outdir = outdir + !delimiter 
endif else outdir = ''


;set the template for each subwindow, then combine
if keyword_set(view) then begin
	nl = fix(windata.nl / view)
	dl = windata.wvl(1) - windata.wvl(0)

	for isub = 0, view - 1 do begin
		;break windata into smaller pieces
		windata_sub = rep_tag_value(windata, windata.int[isub*nl:(isub+1)*nl-1,*,*], 'int')
		windata_sub = rep_tag_value(windata_sub, windata.err[isub*nl:(isub+1)*nl-1,*,*], 'err')
		windata_sub = rep_tag_value(windata_sub, windata.wvl[isub*nl:(isub+1)*nl-1], 'wvl')
		windata_sub.nl = nl

		;user defines the template and wavelength selection
		print, 'Set spectral lines for the fitting template (or none to skip).' 
		eis_fit_template, windata_sub, template, offset=offset
		print, 'De-select any wavelengths to be excluded from the fit.'
		eis_wvl_select, windata_sub, wvl_select, offset=offset

		;set overall wavelength limits, and skip this subwindow if no lines are identified
		if isub EQ 0 then limit = [wvl_select.limit(0), 100.] $
		else if isub EQ view - 1 then limit(1) = wvl_select.limit(1)
		if size(template, /type) NE 8 then continue

		;create/combine variables for the output structures
		if ~keyword_set(init) then begin
			init = template.init
			lines = template.lines
			nback = template.nback
			null_value = template.null_value
			refpix = template.refpix
			max_wvl = wvl_select.max
			min_wvl = wvl_select.min
			rast_id = wvl_select.rast_id
		endif else begin
			init = [init(where(init)), template.init]
			lines = [lines, template.lines]
			if max(max_wvl) + dl*1.5 GT wvl_select.min(0) then begin		;if no break in wavelength range, extend previous one
				max_wvl(max(where(max_wvl))) = wvl_select.max(0)
				wvl_select.max(0) = 0.
				wvl_select.min(0) = 0.
			endif
			if n_elements(where(wvl_select.max)) GE 1 then begin		;if other wavelength ranges, add those
				max_wvl(max(where(max_wvl))+1) = wvl_select.max(where(wvl_select.max))
				min_wvl(max(where(min_wvl))+1) = wvl_select.min(where(wvl_select.min))
			endif
		endelse
		print, '% EIS_DEFINE_FIT: Number of wavelength ranges so far (10 max):  ', strtrim(n_elements(where(max_wvl)),2)
	endfor

	;re-create output structures
	template = create_struct('init', init, 'lines', lines, 'nback', nback, $
			'ngauss', n_elements(lines), 'null_value', null_value, 'refpix', refpix)
	wvl_select = create_struct('limit', limit, 'max', max_wvl, 'min', min_wvl, $
			'n', n_elements(where(max_wvl)), 'rast_id', rast_id)


;set template and wavelength selection for a whole window at once
endif else begin
	print, 'Set spectral lines for the fitting template: ', windata.line_id
	eis_fit_template, windata, template, offset=offset
	print, 'De-select any wavelengths to be excluded from the fit.'
	eis_wvl_select, windata, wvl_select, offset=offset
endelse


;output the text files 
if size(template, /type) EQ 8 and ~keyword_set(no_out) then begin
	eis_write_template, outdir+'fit_template_'+iwin_id+sub_id+'.txt', template
	eis_write_wvl_select, wvl_select, outfile=outdir+'fit_wvlselect_'+iwin_id+sub_id+'.txt'
	print, '% EIS_DEFINE_FIT: ngauss= ', template.ngauss
	print, '% EIS_DEFINE_FIT: Line 0 centroid= ', template.lines(0).centroid
endif else print, '% EIS_DEFINE_FIT: Error: Not a valid spectral template.'


return
end
