;
;
;    Copyright (C) 2009 Steven Sourbron
;
;    This program is free software; you can redistribute it and/or modify
;    it under the terms of the GNU General Public License as published by
;    the Free Software Foundation; either version 2 of the License, or
;    (at your option) any later version.
;
;    This program is distributed in the hope that it will be useful,
;    but WITHOUT ANY WARRANTY; without even the implied warranty of
;    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;    GNU General Public License for more details.
;
;    You should have received a copy of the GNU General Public License along
;    with this program; if not, write to the Free Software Foundation, Inc.,
;    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;
;
;


PRO PMI__Display__DimitraKidneyModelsROI::Fit

	Self->GET, Model=Model, Delay=Delay, Time=Time, AifCurve=Aif, RoiCurve=Curve, RoiVolume=Vol
	Self->SET, Message='Fitting...', Sensitive=0

	IF Delay NE 0 THEN DELAY_VALUES=[0,10,time[1]/2]

	CASE Model OF

		'Maximum slope':begin
			Fit = MaximumSlopePerfusion(time, curve, AIF, flow = flow)
			aic = n_elements(time)*alog(total((curve-Fit)^2)/n_elements(time)) + 2D*(1+3)
			Parameters = $
				[{Name:'Blood Flow'		,Units:'ml/100ml/min'	,Value:6000D*flow/(1D -self.Hematocrit),Nr: 0}	]
			end

		'Model-free':begin
			IRF = DeconvolveCurve(time,	curve, aif, dt=dt, Fit=Fit, pc='GCV', wm=1L, m0=0.001, m1=1.0, nm=100L, Quad='O2')
			Fit = interpol(Fit, dt*findgen(n_elements(Fit)), Time)
			aic = n_elements(time)*alog(total((curve-Fit)^2)/n_elements(time)) + 2D*(1+2)
			Parameters = $
				[{Name:'Blood Flow'		,Units:'ml/100ml/min'	,Value:6000D*max(IRF)/(1D -self.Hematocrit)			,Nr: 0} $
				,{Name:'MTT'			,Units:'sec'			,Value:1D*dt*total(IRF)/max(IRF)					,Nr: 1} $
				,{Name:'Volume'			,Units:'ml/100ml'		,Value:100D*dt*total(IRF)	,Nr: 2} ]
			end

		'Patlak':begin
			P = [0.1, 30.0/6000] ;[VP, FE]
			Fit = FitSingleInlet('Patlak',time,aif,curve,P, DELAY_PAR=Pd, DELAY_VALUES=DELAY_VALUES, /NODERIVATIVE, LIMITED_ABOVE=[1,0], AKAIKE_ERROR=aic )
			Parameters = $
				[{Name:'Blood Volume'		,Units:'ml/100ml'		,Value:100D*P[0]/(1D -self.Hematocrit)	,Nr: 2} $
				,{Name:'Tubular Flow'		,Units:'ml/100ml/min'	,Value:6000D*P[1]	,Nr: 4} $
				,{Name:'Regional GFR'		,Units:'ml/min'			,Value:Vol*60D*P[1]	,Nr: 8} $
				,{Name:'Region Volume'		,Units:'ml'				,Value:Vol	,Nr: 10} ]
			IF Delay NE 0 THEN $
				Parameters = [Parameters,{Name:'Arterial Delay', Units:'sec', Value:1D*Pd, Nr:12} ]
			end

		'Modified Tofts':begin
			P = [0.3, 2.0/3, 12.0/6000] 	;[VP+VTapp, VTapp/(VP+VTapp), FE]
			Fit = FitSingleInlet('ModifiedTofts',time,aif,curve,P, DELAY_PAR=Pd, DELAY_VALUES=DELAY_VALUES, /NODERIVATIVE, LIMITED_ABOVE=[0,1,0], AKAIKE_ERROR=aic)
			Parameters = $
				[{Name:'Blood Volume'		,Units:'ml/100ml'		,Value:100D*P[0]*(1-P[1])/(1D -self.Hematocrit)	,Nr: 2} $
				,{Name:'Tubular MTT'		,Units:'min'			,Value:1D*P[0]*P[1]/P[2]/60D		,Nr: 5} $
				,{Name:'Tubular Flow'		,Units:'ml/100ml/min'	,Value:6000D*P[2]	,Nr: 4} $
				,{Name:'Regional GFR'		,Units:'ml/min'			,Value:Vol*60D*P[2]	,Nr: 8} $
				,{Name:'Region Volume'		,Units:'ml'				,Value:Vol	,Nr: 10}]
			IF Delay NE 0 THEN $
				Parameters = [Parameters,{Name:'Arterial Delay', Units:'sec', Value:1D*Pd, Nr:12} ]
			end

		'2C Uptake':begin
			P = [0.1, 120.0/6000, 12/120.] 	;[VP, FP, FT/FP]
			Fit = FitSingleInlet('2CUptakeFiltration',time,aif,curve,P, DELAY_PAR=Pd, DELAY_VALUES=DELAY_VALUES, NODERIVATIVE=0, LIMITED_ABOVE=[1,0,1], AKAIKE_ERROR=aic)
			Parameters = $
				[{Name:'Blood Flow'			,Units:'ml/100ml/min'	,Value:6000D*P[1]/(1D -self.Hematocrit)		,Nr: 0} $
				,{Name:'Blood MTT'				,Units:'sec'			,Value:1D*P[0]/P[1] 		,Nr: 1} $
				,{Name:'Blood Volume'			,Units:'ml/100ml'		,Value:100D*P[0]/(1-self.Hematocrit)		,Nr: 2} $
				,{Name:'Extraction Fraction'	,Units:'%' 				,Value:100D*P[2]	,Nr: 7} $
				,{Name:'Tubular Flow'			,Units:'ml/100ml/min'	,Value:6000D*P[1]*P[2]		,Nr: 4} $
				,{Name:'Regional GFR'			,Units:'ml/min'			,Value:Vol*60D*P[1]*P[2]	,Nr: 8} $
				,{Name:'Region Volume'		,Units:'ml'				,Value:Vol	,Nr: 10}]
			IF Delay NE 0 THEN $
				Parameters = [Parameters,{Name:'Arterial Delay', Units:'sec', Value:1D*Pd, Nr:12} ]
			end


		'2C Filtration':begin
			P = [0.3, 125.0/6000, 2.0/3, 12/120.] ;[VP+VTapp, FP, VTapp/(VP+VTapp), FT/FP]
			Fit = FitSingleInlet('Filtration', Time, Aif, curve, P, DELAY_PAR=Pd, DELAY_VALUES=DELAY_VALUES, NODERIVATIVE=1, LIMITED_ABOVE=[0,0,0,0], AKAIKE_ERROR=aic)
			Parameters = $
				[{Name:'Blood Flow'			,Units:'ml/100ml/min'	,Value:6000D*P[1]/(1D -self.Hematocrit)			,Nr: 0} $
				,{Name:'Blood MTT'			,Units:'sec'			,Value:1D*P[0]*(1-P[2])/P[1]					,Nr: 1} $
				,{Name:'Blood Volume'		,Units:'ml/100ml'		,Value:100D*P[0]*(1-P[2])/(1D -self.Hematocrit)	,Nr: 2} $
				,{Name:'Tubular MTT'		,Units:'min'			,Value:1D*P[0]*P[2]/(P[1]*P[3])/60D	,Nr: 5} $
				,{Name:'Extraction Fraction',Units:'%' 				,Value:100D*P[3]				,Nr: 7} $
				,{Name:'Tubular Flow'		,Units:'ml/100ml/min'	,Value:6000D*P[1]*P[3]			,Nr: 4} $
				,{Name:'Regional GFR'		,Units:'ml/min'			,Value:Vol*60D*P[1]*P[3]		,Nr: 8} $
				,{Name:'Region Volume'		,Units:'ml'				,Value:Vol						,Nr: 10} $
				,{Name:'Chi-Square'		    ,Units:'%'				,Value:100D*total((Fit-curve)^2)/total(curve^2)						,Nr: 14}]

			IF Delay NE 0 THEN $
				Parameters = [Parameters,{Name:'Arterial Delay', Units:'sec', Value:1D*Pd, Nr:12} ]
			end

		'2C Filtration (LLS)':begin
		    RENALMODEL_INVERSE_LLS_METHOD, curve, aif, time, TPrec, TTrec, VPrec, VTrec
		    RENALMODEL_INVERSE_NONLINEAR_FUNC_2_, [time,aif], [TPrec, TTrec, VPrec, VTrec], Fit
			Parameters = $
				[{Name:'Blood Flow'			,Units:'ml/100ml/min'	,Value:6000D*VPrec/TPrec/(1D -self.Hematocrit)			,Nr: 0} $
				,{Name:'Blood MTT'			,Units:'sec'			,Value:1D*TPrec					,Nr: 1} $
				,{Name:'Blood Volume'		,Units:'ml/100ml'		,Value:100D*VPrec/(1D -self.Hematocrit)	,Nr: 2} $
				,{Name:'Tubular MTT'		,Units:'min'			,Value:1D*TTrec/60D	,Nr: 5} $
				,{Name:'Extraction Fraction',Units:'%' 				,Value:100D*(VTrec/TTrec)/(VPrec/TPrec)				,Nr: 7} $
				,{Name:'Tubular Flow'		,Units:'ml/100ml/min'	,Value:6000D*VTrec/TTrec			,Nr: 4} $
				,{Name:'Regional GFR'		,Units:'ml/min'			,Value:Vol*60D*VTrec/TTrec		,Nr: 8} $
				,{Name:'Region Volume'		,Units:'ml'				,Value:Vol						,Nr: 10} $
				,{Name:'Chi-Square'		    ,Units:'%'				,Value:100D*total((Fit-curve)^2)/total(curve^2)						,Nr: 14}]

			end


		'Filtration (plug-flow)':begin
			P = [0.3, 120.0/6000, 2.0/3, 12/120.] ;[VP+VE, FP, VE/(VP+VE), FE/FP]
			Fit = FitSingleInlet('FiltrationPlugFlow', Time, Aif, curve, P, DELAY_PAR=Pd, DELAY_VALUES=DELAY_VALUES, /NODERIVATIVE, LIMITED_ABOVE=[0,0,1,1], AKAIKE_ERROR=aic)
			Parameters = $
				[{Name:'Blood Flow'			,Units:'ml/100ml/min'	,Value:6000D*P[1]/(1D -self.Hematocrit)			,Nr: 0} $
				,{Name:'Blood MTT'			,Units:'sec'			,Value:1D*P[0]*(1-P[2])/P[1]					,Nr: 1} $
				,{Name:'Blood Volume'		,Units:'ml/100ml'		,Value:100D*P[0]*(1-P[2])/(1D -self.Hematocrit)	,Nr: 2} $
				,{Name:'Tubular MTT'		,Units:'min'			,Value:1D*P[0]*P[2]/(P[1]*P[3])/60D	,Nr: 5} $
				,{Name:'Extraction Fraction',Units:'%' 				,Value:100D*P[3]				,Nr: 7} $
				,{Name:'Tubular Flow'		,Units:'ml/100ml/min'	,Value:6000D*P[1]*P[3]			,Nr: 4} $
				,{Name:'Regional GFR'		,Units:'ml/min'			,Value:Vol*60D*P[1]*P[3]		,Nr: 8} $
				,{Name:'Region Volume'		,Units:'ml'				,Value:Vol						,Nr: 10}]
			IF Delay NE 0 THEN $
				Parameters = [Parameters,{Name:'Arterial Delay', Units:'sec', Value:1D*Pd, Nr:12} ]
			end
	endcase

	self.Curve[2] = ptr_new(Fit)
	self.Parameters = ptr_new(Parameters)
	Self->SET, /Sensitive
END

PRO PMI__Display__DimitraKidneyModelsROI::Plot

	Self->GET, OnDisplay=OnDisplay

	top=0.9 & dy=0.04 & x0=0.525 & charsize=1.0 & charthick=1.0

	CASE OnDisplay OF

		'ROI':begin
			Self -> GET, Time=Time, RoiCurve=Y, RoiName=RoiName, Units=Units
			Self -> SET, /Erase
 			plot, /nodata, position=[0.1,0.2,0.5,0.9]  $
			, 	[0,max(time)], [min(Y),max(Y)] $
			, 	/xstyle, /ystyle $
			, 	background=255, color=0 $
			, 	xtitle = 'Time (sec)', ytitle=Units $
			, 	charsize=1.5, charthick=2.0, xthick=2.0, ythick=2.0
			oplot, time, Y, color=6*16, linestyle=0, thick=2
			xyouts, x0, top-0*dy, 'Region Of Interest: ' + RoiName, color=6*16, /normal, charsize=1.5, charthick=1.5
			end

		'AIF':begin
			Self -> GET, Time=Time, AifCurve=Y, AifName=AifName, Units=Units
			Self -> SET, /Erase
 			plot, time, Y, position=[0.1,0.2,0.5,0.9]  $
			, 	/xstyle, /ystyle $
			, 	background=255, color=0 $
			, 	xtitle = 'Time (sec)', ytitle=Units $
			, 	linestyle=0, thick=2 $
			, 	charsize=1.5, charthick=2.0, xthick=2.0, ythick=2.0
			xyouts, x0, top-1*dy, 'Arterial Input Function: ' + AifName	, color=0, /normal, charsize=1.5, charthick=1.5
			end

		'FIT':BEGIN
			Self -> GET, RoiCurve=Curve, Time=Time, Fit=Fit, Model=Model, RoiName=RoiName, AifName=AifName, Units=Units
			Self -> SET, /Erase

 			plot, /nodata, position=[0.1,0.2,0.5,0.9]  $
			, 	[0,max(time)], [min([min(Curve),min(Fit)]),max([max(Curve),max(Fit)])] $
			, 	/xstyle, /ystyle $
			, 	background=255, color=0 $
			, 	xtitle = 'Time (sec)', ytitle=Units $
			, 	charsize=1.5, charthick=2.0, xthick=2.0, ythick=2.0
			oplot, time, Curve, color=6*16, psym=4, thick=2
			oplot, time, Fit, color=12*16, linestyle=0, thick=2

			xyouts, x0, top-0*dy, 'Region Of Interest: ' + RoiName		, color=6*16, /normal, charsize=1.5, charthick=1.5
			xyouts, x0, top-1*dy, 'Arterial Input Function: ' + AifName	, color=0, /normal, charsize=1.5, charthick=1.5
			xyouts, x0, top-3*dy, 'Tissue Model: ' + Model				, color=12*16, /normal, charsize=1.5, charthick=1.5

			P = *self.Parameters

			for i=0L,n_elements(P)-1 do xyouts $
				, x0, top-dy*(5+P[i].Nr) $
				, P[i].Name + ' = ' + PMI__Round(P[i].Value,3,/string) + ' ' + P[i].Units $
				, color=0, /normal, charsize=charsize, charthick=charthick
			END
	ENDCASE

END




FUNCTION PMI__Display__DimitraKidneyModelsROI::Event, ev

	Uname = widget_info(ev.id,/uname)

	if Uname Eq 'FITbttn' then begin
		widget_control, ev.id, sensitive=0
		widget_control, widget_info(self.id,find_by_uname='AIFbttn'), sensitive=1
		widget_control, widget_info(self.id,find_by_uname='ROIbttn'), sensitive=1
		list = widget_info(self.id,find_by_uname='FIT')
		widget_control, list, sensitive=1
		widget_control, widget_info(self.id,find_by_uname='Delay'), sensitive = widget_info(list,/droplist_select) GT 1
		self->plot
		return, 0B
	endif

	if Uname Eq 'ROIbttn' then begin
		widget_control, ev.id, sensitive=0
		widget_control, widget_info(self.id,find_by_uname='AIFbttn'), sensitive=1
		widget_control, widget_info(self.id,find_by_uname='FITbttn'), sensitive=1
		widget_control, widget_info(self.id,find_by_uname='FIT'), sensitive=0
		widget_control, widget_info(self.id,find_by_uname='Delay'), sensitive=0
		self->plot
		return, 0B
	endif

	if Uname Eq 'AIFbttn' then begin
		widget_control, ev.id, sensitive=0
		widget_control, widget_info(self.id,find_by_uname='ROIbttn'), sensitive=1
		widget_control, widget_info(self.id,find_by_uname='FITbttn'), sensitive=1
		widget_control, widget_info(self.id,find_by_uname='FIT'), sensitive=0
		widget_control, widget_info(self.id,find_by_uname='Delay'), sensitive=0
		self->plot
		return, 0B
	endif

	i = where(Uname Eq ['ROI','AIF'], cnt)
	If cnt eq 1 then begin
		ptr_free, Self.Curve[i], Self.Curve[2], self.parameters
		self->plot
		return, 0B
	endif

	if Uname Eq 'FIT' then begin
		widget_control, widget_info(self.id,find_by_uname='Delay'), sensitive=widget_info(ev.id,/droplist_select) GT 1
		ptr_free, Self.Curve[2], self.parameters
		self -> Plot
		return, 0B
	endif

	i = where(Uname Eq ['SIG','Delay'], cnt)
	if cnt eq 1 then begin
		ptr_free, Self.Curve[2], self.parameters
		self -> Plot
		return, 0B
	endif

	i = where(Uname Eq ['Export','Export As'], cnt)
	if cnt eq 1 then begin
		Self->GET, Time=Time, RoiCurve=RoiCurve, Fit=Fit, Model=Model, Roiname=Roiname
		if Uname eq 'Export' then begin
			PMI__Info, ev.top, Stdy=Stdy
			Path = Stdy->Datapath() + 'Kidney Models (ROI)'
			file_mkdir, Path
			File = Path + '\' + Roiname + '__SI_' + Model
		endif else begin
			PMI__Info, ev.top, State=State
			if not State -> Get_file(file, file=cleanstr(Roiname + '__' + Model), title='Save as..', filter='.tif') then return,0B
			File = strmid(file,0,strlen(file)-4)
		endelse
		Write_tiff, File + '.tif', reverse(tvrd(/true),3)
		PMI__WritePlot, File + '__Curve.txt', Time, RoiCurve
		PMI__WritePlot, File + '__Fit.txt', time, Fit
		PMI__WritePlot, File + '__Parameters.txt' $
		, 	Xname = 'Parameters', (*self.Parameters).Name + '  (' + (*self.Parameters).Units + ')' $
		, 	Yname = 'Fitted Values', (*self.Parameters).Value
		return, 0B
	endif

	Menu = widget_info(widget_info(ev.top,/child),/all_children)
	for i=0L,n_elements(Menu)-1 do widget_control, Menu[i], /sensitive
	PMI__Control, ev.top, Viewer = 'PMI__DISPLAY__2DVIEW'
	PMI__Control, ev.top, /refresh
	return, 0B
END

FUNCTION PMI__Display__Event__DimitraKidneyModelsROI, ev

	widget_control, ev.handler, get_uvalue=self
	return, Self -> Event(ev)
END

FUNCTION PMI__Display__DimitraKidneyModelsROI::Conc, Region
	case Region of
		'ROI':Signal=*Self.Curve[0]
		'AIF':Signal=*Self.Curve[1]
	endcase
	Self -> GET, SignalModel=SignalModel
	S0 = total(Signal[0:self.baseline-1])/self.baseline
	If SignalModel eq 0 then return, Signal-S0
	If SignalModel eq 1 then return, 100*(Signal-S0)/S0
	relaxivity = 3.6
	case Region of
		'ROI':R10=1.0
		'AIF':R10=1/1441.
	endcase
	if SignalModel eq 2 then return, (1000*R10/relaxivity)*(Signal-S0)/S0
	TR = self.series->GETVALUE('0018'x,'0080'x)
	FA = self.series->GETVALUE('0018'x,'1314'x)
	return, Concentration_SPGRESS(Signal, S0, 1/R10, FA, TR, relaxivity)
END

FUNCTION PMI__Display__DimitraKidneyModelsROI::GetCurve, Region

	Self -> GET, Time=Time, Stdy=Stdy, Region=Region
	Self -> SET, Message = 'Loading ' + Region->Name() + ' curve', Sensitive=0
	Signal = PMI__RoiCurve(Stdy->DataPath(), Self.Series, Region, cnt=cnt)
	Self -> SET, /Sensitive
	if cnt eq 0 then return, Time*0
	return, Signal
END

FUNCTION PMI__Display__DimitraKidneyModelsROI::GetName, Region

	self->GET, Region=Region
	return, Region -> Name()
END


PRO PMI__Display__DimitraKidneyModelsROI::GET, $
 	CursorPos = CursorPos, $
	Model=Model, Delay=Delay, $
	Time=Time, Fit=Fit, Units=Units, SignalModel=SignalModel, $
 	RoiCurve=RoiCurve, AifCurve=AifCurve, $
	RoiName=RoiName, AifName=AifName, $
 	OnDisplay=OnDisplay, $
	RoiVolume=RoiVolume, $
	Region = Region, Stdy=Stdy

	if arg_present(CursorPos) then CursorPos=self.CursorPos

	if arg_present(Model) then begin
		list = widget_info(self.id,find_by_uname='FIT')
		widget_control, list, Get_Value=Models
		Model = Models[widget_info(list,/droplist_select)]
	endif

	if arg_present(Delay) then $
		Delay = widget_info(widget_info(self.id,find_by_uname='Delay'),/Button_set)

	if arg_present(Time) then begin
		t = Self.Series -> c(1)
		Time = t-t[0]
	endif

	if arg_present(RoiName) then RoiName=Self->GetName('ROI')
	if arg_present(AifName) then AifName=Self->GetName('AIF')

	if arg_present(RoiCurve) then begin
		if not ptr_valid(Self.Curve[0]) then Self.Curve[0] = ptr_new(Self->GetCurve('ROI'))
		RoiCurve = self->Conc('ROI')
	endif

	if arg_present(AifCurve) then begin
		if not ptr_valid(Self.Curve[1]) then Self.Curve[1] = ptr_new(Self->GetCurve('AIF'))
		AifCurve = Self->Conc('AIF')/(1-self.Hematocrit)
	endif

	if arg_present(FIT) then begin
		if not ptr_valid(Self.Curve[2]) then Self->Fit
		FIT = *Self.Curve[2]
		endif

	if arg_present(units) then begin
		Self -> GET, SignalModel=tmp
		case tmp of
		0:units = 'Concentration (a.u.)'
		1:units = 'Concentration (%)'
		2:units = 'Concentration (mM)'
		3:units = 'Concentration (mM)'
		endcase
	endif

	if arg_present(SignalModel) then begin
		id = widget_info(self.id,find_by_uname='SIG')
		SignalModel = widget_info(id,/droplist_select)
	endif

	if arg_present(OnDisplay) then begin
		OnDisplay = ''
		List = ['AIF','ROI','FIT']
		for i=0L,2 do $
		if 0 eq widget_info(widget_info(self.id,find_by_uname=List[i]+'bttn'),/sensitive) then OnDisplay=List[i]
	endif

	if arg_present(Stdy) then PMI__Info, tlb(self.id), Stdy=Stdy

	if n_elements(Region) ne 0 then begin
		Self->GET, Stdy=Stdy
		Region = Stdy->Obj(1,widget_info(widget_info(self.id,find_by_uname=Region),/droplist_select))
	endif

	if arg_present(RoiVolume) then begin
		Region='ROI'
		Self->GET, Stdy=Stdy, Region=Region
		v = PMI__RoiValues(Stdy->DataPath(), self.series, Region, cnt=npix)
		thick = self.Series->GetValue('0018'x,'0050'x)
		pixel = self.Series->GetValue('0028'x,'0030'x)
		RoiVolume = npix*(thick[0]/10D)*(pixel[0]/10D)^2
	endif
END

PRO PMI__Display__DimitraKidneyModelsROI::SET, $
	PMI__REFRESH=pmi__refresh, PMI__RESIZE=pmi_resize, $
	Refresh=Refresh, Erase=Erase, $
	Message=Message, Sensitive=Sensitive, $
	xsize=xsize, ysize=ysize, $
	Set_droplist_select = Set_droplist_select, $
	Series=Series, Baseline=Baseline, Hematocrit=Hematocrit, $
	OnDisplay=OnDisplay

	if keyword_set(pmi_resize) then begin
		gpmi = widget_info(/geometry, tlb(self.id))
		self -> Set, xsize=gpmi.xsize, ysize=gpmi.ysize
		self->plot
	endif

	if n_elements(Series) 	ne 0 then Self.Series = Series
	if n_elements(Baseline) 	ne 0 then self.Baseline = Baseline
	if n_elements(Hematocrit) 	ne 0 then self.Hematocrit = Hematocrit
	if n_elements(Message) 	ne 0 then begin
		Self->Set, /Erase
		xyouts, 0.1,0.9, Message, color=0,/normal,charsize=1.5,charthick=2.0
	endif
	if n_elements(Sensitive) ne 0 then widget_control, self.id, sensitive=sensitive
	if n_elements(Set_droplist_select) ne 0 then begin
		List = ['ROI','AIF']
		for i=0,1 do widget_control, $
			widget_info(self.id,find_by_uname=List[i]), $
			Set_droplist_select=Set_droplist_select[i]
	endif
	if n_elements(xsize) ne 0 $
	or n_elements(ysize) ne 0 then begin
		widget_control, self.DrawId, xsize=xsize, ysize=ysize-40
		xs = floor((xsize - 750)/2E)
		if xs lt 50 then xs = 50
		List = ['AIF','ROI']
		for i=0,1 do widget_control, widget_info(self.id,find_by_uname=List[i]), xsize=xs
	endif

	if keyword_set(Erase) then begin
		widget_control, self.DrawId, get_value = win
		wset, win & erase, 255
	endif

	if n_elements(OnDisplay) ne 0 then begin

		List = ['AIF','ROI','FIT']
		for i=0,2 do $
		widget_control, widget_info(self.id,find_by_uname=List[i]+'bttn'), Sensitive=List[i] ne OnDisplay
 		widget_control, widget_info(self.id,find_by_uname='Export')		, Sensitive=OnDisplay eq 'FIT'
		widget_control, widget_info(self.id,find_by_uname='Export As')	, Sensitive=OnDisplay eq 'FIT'
	endif

	if keyword_set(Refresh) then begin
		Menu = widget_info(widget_info(tlb(self.id),/child),/all_children)
		for i=0L,n_elements(Menu)-1 do widget_control, Menu[i], sensitive=0
		Self -> Plot
	endif
END





PRO PMI__Display__DimitraKidneyModelsROI::Cleanup
	widget_control, self.id, /destroy
	ptr_free, Self.Curve, self.Parameters
	loadct, 0
END

FUNCTION PMI__Display__DimitraKidneyModelsROI::Init, parent, CursorPos, xsize=xsize, ysize=ysize

	if n_elements(CursorPos) ne 0 then self.CursorPos = CursorPos

	loadct, 12

	PMI__Info, tlb(parent), Stdy=Stdy

	self.id = widget_base(parent,/column,map=0,event_func='PMI__Display__Event__DimitraKidneyModelsROI')
	Controls = widget_base(self.id,/row,ysize=40,/base_align_center,space=5)
	self.DrawId	= widget_draw(self.id,/retain)

		v = ['ROI','AIF']
		for i=0,1 do begin
			Base = widget_base(Controls,/row,/frame,/base_align_center)
			id = widget_button(Base, xsize=25, ysize=19, value=v[i], uname=v[i]+'bttn')
  			id = widget_droplist(Base,/dynamic_resize, value=Stdy->Names(1), uname=v[i])
  		endfor

		Base = widget_base(Controls,/row,/frame,/base_align_center)
		    id = widget_droplist(Base,/dynamic_resize, uname='SIG',value = ['Linear (a.u.)','Linear (%)','Linear (mM)'])
		;	id = widget_droplist(Base,/dynamic_resize, uname='SIG',value = ['Linear (a.u.)','Linear (%)','Linear (mM)', 'Non-linear (mM)'])
  			widget_control, id, set_droplist_select = 0

		Base = widget_base(Controls,/row,/frame,/base_align_center)
			id = widget_button(Base, xsize=25, ysize=19, value='FIT', uname='FITbttn')
;		id = widget_droplist(Base,/dynamic_resize, uname='FIT',value = ['Maximum slope','Model-free','Patlak','Modified Tofts','2C Uptake','2C Filtration','Filtration (plug-flow)'])
		    id = widget_droplist(Base,/dynamic_resize, uname='FIT',value = ['Maximum slope','Model-free','Patlak','Modified Tofts','2C Uptake','2C Filtration','2C Filtration (LLS)'])
;			id = widget_droplist(Base,/dynamic_resize, uname='FIT',value = ['Maximum slope','Model-free','Patlak','Modified Tofts','2C Uptake','2C Filtration'])
  			widget_control, id, set_droplist_select = 5

		Base = widget_base(Controls,/row,/frame,/nonexclusive)
		id = widget_button(Base, value='Delay', uname='Delay')

		v = ['Export','Export As','Close']
		Base = widget_base(Controls,/row,/frame,/base_align_center)
		for i=0,2 do id = widget_button(Base, xsize=50, ysize=22, value=v[i], uname=v[i])

	self -> Set, xsize=xsize, ysize=ysize, OnDisplay='FIT'
	widget_control, self.id, set_uvalue = self, /map
	return, 1
END

PRO PMI__Display__DimitraKidneyModelsROI__Define

	SingleInletPatlak
	SingleInletModifiedTofts
	SingleInlet2CUptakeFiltration
	SingleInletFiltration
	SingleInletFiltrationPlugFlow

	Struct = {PMI__Display__DimitraKidneyModelsROI 	$
	,	id: 0L 	$
	,	DrawId: 0L $
	,	CursorPos:lonarr(4)	$
	,	Curve:ptrarr(3) $ ;RoiCurve, AifCurve, Fit
	,	Parameters: ptr_new() $
	,	Series: obj_new() $
	,	Baseline: 0L $
	,	Hematocrit: 0E $
	}
END


pro PMI__Button__Event__DimitraKidneyModelsROI, ev

	PMI__Info, ev.top, Stdy=Stdy

    Series = Stdy->Names(0,ns,DefDim=3,ind=ind,sel=sel)
    Regions = Stdy->Names(1,nr)

	v = PMI__Form(ev.top, Title='Perfusion analysis setup', [$
		ptr_new({Type:'DROPLIST',Tag:'series', Label:'Dynamic series', Value:Series, Select:sel}), $
		ptr_new({Type:'DROPLIST',Tag:'aif'	 , Label:'Arterial Region', Value:Regions, Select:stdy->sel(1)}), $
		ptr_new({Type:'DROPLIST',Tag:'roi'	 , Label:'Tissue Region', Value:Regions, Select:stdy->sel(1)}), $
		ptr_new({Type:'VALUE'	,Tag:'nbase' , Label:'Length of baseline (# of dynamics)', Value:1L}),$
		ptr_new({Type:'VALUE'	,Tag:'hct'	 , Label:'Patients hematocrit', Value:0.45})])
	IF v.cancel THEN return

	PMI__Control, ev.top, Viewer = 'PMI__Display__DimitraKidneyModelsROI', Display=Display

	Display -> Set, /Refresh, $
		Series = Stdy->Obj(0,ind[v.series]), $
		Baseline = v.nbase, $
		Hematocrit = v.hct, $
		set_droplist_select = [v.roi,v.aif]
end

pro PMI__Button__Control__DimitraKidneyModelsROI, id, v

	PMI__Info, tlb(id), Stdy=Stdy
	if obj_valid(Stdy) then begin
		Series = Stdy->Names(0,ns,DefDim=3)
		Regions = Stdy->Names(1,nr)
		sensitive = (ns gt 0) and (nr gt 1)
	endif else sensitive=0
    widget_control, id, sensitive=sensitive
end

function PMI__Button__DimitraKidneyModelsROI, parent,value=value, separator=separator

	PMI__Display__DimitraKidneyModelsROI__Define

	if n_elements(value) eq 0 then value = 'Renal filtration models (ROI)'

	return, widget_button(parent, $
		value = value,	$
		event_pro = 'PMI__Button__Event__DimitraKidneyModelsROI',	$
		pro_set_value = 'PMI__Button__Control__DimitraKidneyModelsROI', $
	 	separator = separator )
end
