;+
; NAME:
;	qLine_FitPlot
; PURPOSE:
;
; CATEGORY:
;	Widget qLine
; CALLING SEQUENCE:
	PRO qLine_FitPlot, state, iy, x, y
; INPUTS:
; OPTIONAL INPUT PARAMETERS:
; OUTPUTS:
; OPTIONAL OUTPUT PARAMETERS:
; INCLUDE:
	@compile_opt.pro		; On error, return to caller
; CALLS:
;	IsTime, lsqNormalFit, TimeScale, TimeGet
; PROCEDURE:
; MODIFICATION HISTORY:
;	FEB-2001, Paul Hick (UCSD/CASS; pphick@ucsd.edu)
;-

widget_control, state.wid_fit[iy], get_uvalue=set

IF set THEN BEGIN

	widget_control, state.wid_degree, get_value=ndegree, get_uvalue=range
	range = (range > min(!x.crange)) < max(!x.crange)

	IF finite(range[0]) THEN BEGIN
		plots, range[0]*[1,1], !y.crange

		IF finite(range[1]) THEN BEGIN
			plots, range[1]*[1,1], !y.crange

			CASE IsTime(x) OF
			0: xx = x
			1: xx = TimeScale(x, t0=t0, tu=tu)
			ENDCASE

			tmp = where(range[0] LT xx AND xx LT range[1])
			IF tmp[0] NE -1 THEN BEGIN

				widget_control, state.wid_scalefit, get_value=scale

				x0 = !x.crange[0]

				xn = xx[tmp]-x0
				yn = y [tmp]

				CASE ndegree OF
				-1  : BEGIN
					R = lsqNormalFit(xn, yn, /oplot, yfit=yfit)

					print, 'normal fit params:', reform(R)
				END
				ELSE: BEGIN
					R = poly_fit(xn, yn, ndegree, yfit)

					CASE IsTime(x) OF
					0: cfit = 'x0='+strcompress(x0,/rem)
					1: cfit = 't0='+TimeGet(t0,/ymd)+' ('+TimeUnit(tu)+')'
					ENDCASE

					cfit = cfit+', y='+strcompress(R[0],/rem)+strjoin( ([' +',' '])[R[1:ndegree] lt 0]+	$
								strcompress(R[1:ndegree],/rem)+' x^'+strcompress(1+indgen(ndegree),/rem) )

					print, 'curve',strcompress(iy),': ',cfit
				END
				ENDCASE

				oplot, xx[tmp], yfit
				IF scale NE 0 THEN oplot, xx[tmp], yfit+(y[tmp]-yfit)*scale, linestyle=3

			ENDIF
		ENDIF
	ENDIF
ENDIF

RETURN  &  END
