; Copyright (c) 1998-2012 A.P. Hitchcock  All rights reserved
;+
;NAME:
;		LN_NORM.PRO
;
;LAST CHANGED: ----------------------------------- 	03-Feb-12
;
; PURPOSE:
;	This procedure  normalizes each line of a linescan or image
;  to a H or V subset  or to Io from an aXis buffer (if neither Horiontal or Vertical keywords were selected)
;
; CATEGORY:
;	Linescan processing
;
; CALLING SEQUENCE:
;	LN_NORM, HORIZONTAL = HORIZONTAL, VERTICAL = VERTICAL
;
; INPUTS:
;	All input parameters are passed as keywords.
;
; KEYWORDS:
;	HORIZONTAL - if set, normalize image horizontally from user selected buffer
;	VERTICAL   -  if set, normalize image vertically from user selected bufferif set
;  in each case, the line to mormalize is usually obtained by linescan~add (horizontal, or vertical)
;
; OUTPUTS: modified image in buffer 9
;
; COMMON BLOCKS:
;	AXIS_COM	standard set of common blocks
;
; SIDE EFFECTS: NONE
;
; MODIFICATION HISTORY:
; (19-jun-98 aph) isolated from AXIS_C to make space
; (01-jan-99 aph) renamed to be consistent with other ln_xx files
; (11-jan-99 aph) allow normalization along vertical axes
; (23-feb-00 aph) added groupID to buffer call
; (21-mar-00 aph) correct axis_ID for buffer call !
; (04-dec-00 aph) add horizontal option
; (03-feb-11 aph) correct header format; use axis_log
; (10-dec-11 aph) add energy to 2d-normalization; make horizontal normalize preserve intensity
; (29-Jan-12 aph) Correct 10-dec-11 change to limitonly to line-horizontal, NOT normalize to Io !!
; (03-Feb-12 aph) added question re mean normalization of V, H lines
;-

PRO ln_norm, vertical=vertical, horizontal=horizontal
@axis_com
on_error,2

HANDLE_VALUE, Data(CurBuf), tmp     ;Get the data
IF n_tags(tmp) EQ 0 THEN RETURN
IF tmp.t EQ '2d' THEN BEGIN
	IF keyword_set(vertical) then begin
		test = string(format='("Line normalise VERTICAL",/,"avg*(image/Vline)",A)','')
		axis_log, test
		SetGraf, 'MainImg'
	   	bt = Buffer(group = axis_ID)  	;Get buffer containing Io from user
		IF bt(0) NE -1 THEN BEGIN
			HANDLE_VALUE, Data(bt(0)),tmp2
			IF n_tags(tmp2) ne 0 THEN BEGIN
				WIDGET_CONTROL, /Hourglass
			    yd = tmp.d(0,*)                                  ; set up first line
			    tmp1 = {t:'1d', x:tmp.y, d:yd, xl:tmp.yl, dn:yd, dl:tmp.dl}
; Interpolate line signal to data range of linescan
				xmin = fltarr(2) & xmax = fltarr(2)               ; identify common range
				xmin(0) = min(tmp1.x) & xmin(1) = min(tmp2.x)
				xmax(0) = max(tmp1.x) & xmax(1) = max(tmp2.x)
				xmin = max(xmin) & xmax = min(xmax)
;				print, 'Interpolate: xmin,xmax ', xmin, xmax
				xval1 = where(tmp1.x GE xmin AND tmp1.x LE xmax, nt1)   ; check there is in-range data
				xval2 = where(tmp2.x GE xmin AND tmp2.x LE xmax, nt2)   ; in both buffers
;				print, 'Y-size-1, Y-size-2, in-range sizes:' , cnt1, cnt2, nt1, nt2
;				print, ' steps', (ymax-ymin)/nt1, (ymax-ymin)/nt2
				if nt1(0) NE 0 AND nt2(0) NE 0 then BEGIN
					Xvals1 = where(tmp1.x GE xmin AND tmp1.x LE xmax)
					Xvals2 = where(tmp2.x GE xmin AND tmp2.x LE xmax)
					x1 = tmp1.x(Xvals1)   ; trim arrays to common range
					d1 = tmp1.d(Xvals1)   ; NB must use intermediate arrays!!
					x2 = tmp2.x(Xvals2)
					d2 = tmp2.d(Xvals2)
					y2 = Interpol(d2, x2, x1)        ; mesh to linescan data set
				endif  else begin
					axis_log, 'No common y-range values'
					goto, nogo
				endelse
; set up structure for modified data on [xmin,xmax] range
	            new = {t:'2d',x:tmp.x,y:x1,e: tmp.e, xl:tmp.xl,yl:tmp.yl,d:tmp.d(*,Xvals1),dl:tmp.dl}
; process through all lines
			    for i = 0, n_elements(tmp.x)-1 do begin
			    	yd = tmp.d(i,Xvals1)
					d = yd/y2
; assemble modified image  - will need to compensate for changing line lengths
					new.d(i,*) = d
				endfor
; multiply by average value
				avg = moment(tmp.d)
				new.d = new.d * avg(0)
				new.dl = 'Vnorm ' + new.dl
				HANDLE_VALUE,Data(0),new,/set
				CurBuf = 0
				PlotBuf,CurBuf
		  	endif
		ENDIF
	ENDIF ELSE BEGIN
; code for EITHER Io normalization or horizontal normalization
; inform user which one
		IF keyword_set(horizontal) then begin
			test = string(format='("Line normalise HORIZONTAL",/,"avg*(image/Hline)",A)','')
			axis_log, test
		ENDIF ELSE 	axis_log, 'Linescan normalise: -ln(IMAGE/Io)'
		SetGraf, 'MainImg'
	   	bt = Buffer(group = axis_ID)  	;Get buffer containing Io or horizontal norm line from user
		IF bt(0) NE -1 THEN BEGIN
			HANDLE_VALUE, Data(bt(0)),tmp2
			IF n_tags(tmp2) ne 0 THEN BEGIN
				WIDGET_CONTROL, /Hourglass
			    yd = tmp.d(*,0)                                  ; set up first line
			    tmp1 = {t:'1d', x:tmp.x, d:yd, xl:tmp.xl, dn:yd, dl:tmp.dl}
; Interpolate Io signal to data range of linescan
				xmin = fltarr(2) & xmax = fltarr(2)               ; identify common range
				xmin(0) = min(tmp1.x) & xmin(1) = min(tmp2.x)
				xmax(0) = max(tmp1.x) & xmax(1) = max(tmp2.x)
				xmin = max(xmin) & xmax = min(xmax)
;				print, 'Interpolate: xmin,xmax ', xmin, xmax
				xval1 = where(tmp1.x GE xmin AND tmp1.x LE xmax, nt1)   ; check there is in-range data
				xval2 = where(tmp2.x GE xmin AND tmp2.x LE xmax, nt2)   ; in both buffers
;				nt1=where(tmp1.x,cnt1)  & nt2=where(tmp2.x,cnt2)
;				print, 'size-1, size-2, in-range sizes:' , cnt1, cnt2, nt1, nt2
;				print, ' steps', (xmax-xmin)/nt1, (xmax-xmin)/nt2
				if nt1 NE 0 AND nt2 NE 0 then BEGIN
					Xvals1 = where(tmp1.x GE xmin AND tmp1.x LE xmax)
					Xvals2 = where(tmp2.x GE xmin AND tmp2.x LE xmax)
					x1 = tmp1.x(Xvals1)   ; trim arrays to common range
					d1 = tmp1.d(Xvals1)   ; NB must use intermediate arrays!!
					x2 = tmp2.x(Xvals2)
					d2 = tmp2.d(Xvals2)
					y2 = Interpol(d2, x2, x1)        ; mesh to linescan data set
				endif  else begin
					axis_log, 'No common horizontal or energy values'
					goto, nogo
				endelse
; set up structure for modified data on [xmin,xmax] range
	            new = {t:'2d',x:x1,y:tmp.y,xl:tmp.xl,yl:tmp.yl, e: tmp.e, d:tmp.d(Xvals1,*),dl:tmp.dl}
; process through all lines
				IF keyword_set(horizontal) OR keyword_set(vertical) then begin
					t=dialog_message('Normalize to mean value of line ?',/question, /default_no)
   					if t EQ 'Yes' then begin
						for i = 0, n_elements(tmp.y)-1 do new.d(*,i) = tmp.d(Xvals1,i)/y2
						IF keyword_set(horizontal) then new.dl = 'Hnorm ' + new.dl else new.dl = 'Vnorm ' + new.dl
					endif
				ENDIF else begin
				    for i = 0, n_elements(tmp.y)-1 do begin
				    	yd = tmp.d(Xvals1,i)
						d = alog(y2/yd)
; assemble modified image  - will need to compensate for changing line lengths
						new.d(*,i) = d
					endfor
					new.dl = 'Abs ' + new.dl
				ENDELSE
; multiply by average value - IF Line HORIZONTAL was the requested action ---------
			IF keyword_set(horizontal) then begin
				avg = moment(tmp.d)
				new.d = new.d * avg(0)
			ENDIF
			HANDLE_VALUE,Data(0),new,/set
			CurBuf = 0
			PlotBuf,CurBuf
		  	endif
		ENDIF
	ENDELSE
ENDIF ELSE WIDGET_CONTROL, UPrompt, Set_Value = 'Linescan.normalize - only for images'

 nogo:
RETURN
END
