.

(* code - DO NOT DELETE*)

$HistoryLength=0;


(******  buttons at the top ******)

DynamicModule[{buttons},
buttons=Row[{
Button["Start / Reset",FrontEndTokenExecute["EvaluateInitialization"];PrintTemporary["Starting FMSfit ..."];,ImageSize->150],
(*Button["Delete all output",FrontEndTokenExecute["DeleteGeneratedCells"],ImageSize->150],*)
Button["Abort evaluation",FrontEndTokenExecute["EvaluatorAbort"],ImageSize->150],
Button["Quit kernel",FrontEndTokenExecute["EvaluatorQuit"],ImageSize->150]
}];
CurrentValue[EvaluationNotebook[],{"DockedCells"}]=Cell[BoxData[ToBoxes[buttons]],"DockedCell"]
];

(******  import all files and packages needed ******)

SetDirectory[NotebookDirectory[]];
Get[FileNameJoin[{NotebookDirectory[],"SpectralFittingHemCorrectOxygenation_JBP.m"}]];
(*Get[FileNameJoin[{NotebookDirectory[],"lib","NelderMeadMinimize.m"}]];*)
lctfCorrectionFileName=FileNameJoin[{NotebookDirectory[],"LctfCamera.dat"}];
hemSpectraData=FileNameJoin[{NotebookDirectory[],"hemSpectra.dat"}];
IlluminationProfileCorrectionFileName=FileNameJoin[{NotebookDirectory[],"IlluminationProfile.tif"}];

(******  set low priority to all processes  ******)


CloseKernels[];
Needs["Parallel`Developer`"];
Unprotect[Parallel`Developer`$InitCode];
$InitCode=Hold[System`SetSystemOptions["ProcessPriority"->-2]];
LaunchKernels[];

(*CloseKernels[];
Needs["SubKernels`LocalKernels`"];
Block[{$mathkernel=$mathkernel<>" -threadpriority=-2"},LaunchKernels[]];*)

(**************************************************************)
(*                         MANIPULATE                         *)
(**************************************************************)


Block[{lctfCorrectionFileName,
cropPoint,crop,cropBackground,
importResult,
importFolder,name,images,imagesBackgroundSubtracted,intensityData,imageIntensity,intensityHistogram,lambdaSample,exposureTime,randomSampling,experimentData,
bleachRefMode,bleachRefImages,bleachRefImagesBackgroundSubtracted,bleachRefLambda,bleachRefFrameNumbers,bleachRefLambdaPosition,
noise,parametersPoint,plotSpectrum,plotBleachRef,parametersPointTable,spectraPoint,spectraPoints,
backgroundSpectrum,backgroundBleachRefLambda,
hemSpectra,data,
fileNameBackgCode,fileNamesBackg,imagesDataPop,lambdaRef,expTimeRef,imageIntensityOriginal,intensityDataOriginal,task,taskDone,
IlluminationProfileData,IlluminationProfile,IlluminationProfileMax,
fitSwitches,initialValues,parameterLimits,manualSettingsToUpdate,
parameters,imagesCC,imagesCCshow,plotHistograms,plotsFitSpectra,imageIntensityCropAligned,selectedPointsToLabel,
batchStartQ,backgroundSubtractQ,backgroundSubtractBlank,blankSampleData,namesBatch,monitorBatch,iBatch,
colorLimits,
parameterSymbols,variableParameters,
exportName,exportFolder,
nameParameters,nameImagesCC,nameHistograms,nameSpectra,nameAllTogether,
t,
bookmarks,
buttonSize=195
},




Manipulate[

(************************* CALCULATIONS *************************)

Quiet[

(*transform locator positions into {{xmin,ymin},{xmax,ymax}}*)
crop={Min[xyCrop1[[#]],xyCrop2[[#]]]&/@{1,2},Max[xyCrop1[[#]],xyCrop2[[#]]]&/@{1,2}};
cropPoint={xySpectrum-(fitAveragingPix-1)/2,xySpectrum+(fitAveragingPix-1)/2};
cropBackground={Min[xyCropBackground1[[#]],xyCropBackground2[[#]]]&/@{1,2},Max[xyCropBackground1[[#]],xyCropBackground2[[#]]]&/@{1,2}};


(*************************** OUTPUT ***************************)

imageIntensity=IntensityImage[intensityData,{adjustContrastMin,adjustContrastMax}];
(*imageIntensityOriginal=IntensityImage[intensityDataOriginal,{adjustContrastMinOriginal,adjustContrastMaxOriginal}];*)


Column[{
name,
Grid[
Join[
{{Show[imageIntensity,Frame->True,FrameLabel->{"x [pix]","y [pix]"},LabelStyle->{FontSize->14},FrameTicks->{{All,None},{All,None}},(*PlotLabel->Style["green point: "<>ToString@xySpectrum,14],*)Epilog->{Transparent,EdgeForm[Green],Rectangle@@cropPoint,EdgeForm[Red],Rectangle@@(crop-{1,0}),EdgeForm[Blue],Rectangle@@(cropBackground-{1,0})},ImageSize->400](*,
Show[imageIntensityOriginal,Frame->True,ImageSize->300]
}]*)
,Column[{
Show[intensityHistogram,Epilog->{Gray,Line[{{#,-13.5},{#,0}}]&/@{adjustContrastMin,adjustContrastMax}}],
plotSpectrum},
Spacings->0,Alignment->Bottom]
,Column[{
imageIntensityCropAligned,
plotBleachRef},
Spacings->0,Alignment->Bottom]
}},
imagesCCshow,
plotHistograms]
,Alignment->{Left,Top},Spacings->{2,1},ItemSize->Full],

plotsFitSpectra},
{Left,Bottom},Spacings->2,ItemSize->Full]

]

(**************************************************************)
(************************** CONTROLS **************************)
(**************************************************************)

(*locators for spectrum (green), crop (red), background (blue)*)
,{{xySpectrum,{256,256}},{1,1},{512,512},{1,1},Locator,Enabled->imagesLoadedQ}
,{{xyCrop1,{1,1}},{1,1},{512,512},{1,1},Locator,Enabled->imagesLoadedQ}
,{{xyCrop2,{512,512}},{1,1},{512,512},{1,1},Locator,Enabled->imagesLoadedQ}
,{{xyCropBackground1,{450,450}},{1,1},{512,512},{1,1},Locator,Enabled->imagesLoadedQ}
,{{xyCropBackground2,{500,500}},{1,1},{512,512},{1,1},Locator,Enabled->imagesLoadedQ}


(************ Data ***********)

,Item[Style["Data",14]]
,{{intensityMax,1},0,2.^16,None}
,{{imagesLoadedQ,False},{True,False},None}
,{{fittedDataQ,False},{True,False},None}
,{{resultsSavedQ,False},{True,False},None}

(*********************)
(* Import experiment *)
(*********************)


,Tooltip[Button["Import experiment",

	(*check if the results were saved*)
	If[fittedDataQ&&!resultsSavedQ,
	If[!ChoiceDialog["Are you sure you don't want to save the results of your last analysis?",{"  Yes, I don't need them.  " -> True,"  No, go back, please!  "->False}],
		Return[]
	]];	



	Clear[importResult];
	
	(*get all the data from experiment; images ordered by wavelength*)
	importResult=ImportImages[importFolder,"",lctfCorrectionFileName];

If[Length[importResult]>0, (*if opening of a new experiment was not cancelled, refresh everything, else do nothing*)
	(*reset the rest of the output*)
	imagesCC=imagesCCshow={{"color-coded images"}};plotHistograms={{"histograms"}};plotsFitSpectra="fitted spectra";imageIntensityCropAligned="";
	imagesLoadedQ=False;
	fittedDataQ=False;
	resultsSavedQ=False;

	{name,images,intensityData,lambdaSample,exposureTime,randomSampling,experimentData,importFolder,{bleachRefMode,bleachRefImages,bleachRefLambda,bleachRefFrameNumbers}}=importResult;
	imagesLoadedQ=True;
	
	(*intensity image*)
	{adjustContrastMin,adjustContrastMax}=Round[Sort[Flatten[intensityData]][[{10,-10}]],.00001];	
	intensityHistogram=IntensityHistogram[intensityData,{adjustContrastMin,adjustContrastMax}];(*Histogram[Flatten[intensityData],{(adjustContrastMax-adjustContrastMin)/100.},{"Log","Probability"},PlotRange->{{.5 adjustContrastMin,1.5 adjustContrastMax},{-13.5,0}},PlotRangePadding->None,Axes->None,ChartStyle->Black,
	Frame->True,FrameLabel->{"I [au]","dP/dI"},LabelStyle->{FontSize->14},LabelingFunction->None,PerformanceGoal->"Speed",ImageSize->{400}];*)
	
	backgroundSpectrum=0;	

	(*position of bleachRefLambda in the lambda range - used for background subtraction*)
	bleachRefLambdaPosition=Position[Sort[lambdaSample],Nearest[lambdaSample,bleachRefLambda][[1]]][[1,1]];
        
	(*if no info on bleaching is available, set b=0 and don't fit bleaching rates*)	
	If[Not[randomSampling||bleachRefMode],
	fitSwitchBleach1=fitSwitchBleach2=False;
	manualSetBleach1=manualSetBleach2=0.;
	];

(*Print[{limitOxyLow,limitOxyHigh}];*)

	(*prepare for fitting the green point*)
	{fitSwitches,initialValues,parameterLimits}=
		ControlsFit[fitNComponents,fitSwitchPortion1,fitSwitchLambdaMax1,fitSwitchWidth1,fitSwitchAssymetry1,fitSwitchBleach1,fitSwitchLambdaMax2,fitSwitchWidth2,fitSwitchWidth2,fitSwitchAssymetry2,fitSwitchBleach2,oxygenation,manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen,limitPortionLow,limitPortionHigh,limitLambdaMaxLow,limitLambdaMaxHigh,limitWidthLow,limitWidthHigh,limitAsymmetryLow,limitAsymmetryHigh,limitBleachLow,limitBleachHigh,limitOxyLow,limitOxyHigh,exposureTime];

	(*Import hemSpectra*)
	data=Import[hemSpectraData];
		   hemSpectra=data[[Flatten[Position[data,#]][[1]],2]]&/@lambdaSample;
	(*Print[FullForm[hemSpectra]];*)
	
	(*fit the green point*)
{noise,parametersPoint,plotSpectrum,plotBleachRef,parametersPointTable,spectraPoint}=
AnalizeOnePoint[images,cropPoint,cropBackground,randomSampling,lambdaSample,exposureTime,fitSignalThreshold,
			{fitSwitches,initialValues,parameterLimits},{bleachRefMode,bleachRefImages,bleachRefLambda,bleachRefFrameNumbers}];
	
	(*refresh the manual settings and limits*)
	{manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen}=parametersPoint[[{5,6,7,8,9,12,13,14,15,16}]];		


	{limitLambdaMaxLow,limitLambdaMaxHigh}={510,600};
	{limitOxyLow,limitOxyHigh}={0.,1.};
	{colorlLimitOxyLow,colorLimitOxyHigh}={0.,1.};
	{{colorLimitIntensity1Low,colorLimitIntensity1High},{colorLimitIntensity2Low,colorLimitIntensity2High}}={{0.,1.},{0.,1.}};

	
];
Clear[importResult];

,Method->"Queued"
],"Select a dsc file"]




(************ Intensity image ***********)

,OpenerView[{
Item[Style["Adjust intensity image",12]]

,Column[{
Row[{

(******************)
(* Reset contrast *)
(******************)

Tooltip[
Button["Reset",
{adjustContrastMin,adjustContrastMax}={0,1};
intensityHistogram=IntensityHistogram[intensityData,{adjustContrastMin,adjustContrastMax}];
(*intensityHistogram=Histogram[Flatten[intensityData],{.01},{"Log","Probability"},PlotRange->{{adjustContrastMin,adjustContrastMax},{-13.5,0}},PlotRangePadding->None,Axes->None,ChartStyle->Black,
	Frame->True,FrameLabel->{"I [au]","dP/dI"},LabelStyle->{FontSize->14},LabelingFunction->None,PerformanceGoal->"Speed",ImageSize->{350},AspectRatio->1];*)
,ImageSize->buttonSize-10,Enabled->imagesLoadedQ
]
,"Reset intensity to full dynamic range of the camera"]

(*****************)
(* Auto-contrast *)
(*****************)

,Tooltip[
Button["Auto-contrast",
{adjustContrastMin,adjustContrastMax}=Round[Sort[Flatten[intensityData]][[{10,-10}]],.00001];
intensityHistogram=IntensityHistogram[intensityData,{adjustContrastMin,adjustContrastMax}];
(*intensityHistogram=Histogram[Flatten[intensityData],{(adjustContrastMax-adjustContrastMin)/100.},{"Log","Probability"},PlotRange->{{.5 adjustContrastMin,1.5 adjustContrastMax},{-13.5,0}},PlotRangePadding->None,Axes->None,ChartStyle->Black,
	Frame->True,FrameLabel->{"I [au]","dP/dI"},LabelStyle->{FontSize->14},LabelingFunction->None,PerformanceGoal->"Speed",ImageSize->{400}];*)
,ImageSize->buttonSize-10,Enabled->imagesLoadedQ
]
,"Adjust contrast according to dynamic range of the experiment"]
}]

(* -||------------ *)
(* Adjust contrast *)
(* ------------||- *)

,Grid[{
{Tooltip[Style["Contrast",12],"Adjust minimal and maximal light levels to enhance contrast of the intensity image"]
,Control[{{adjustContrastMin,0,"(Subscript[I, MIN])"},0,1,.001,Appearance->"Labeled"}]},
{,
Control[{{adjustContrastMax,1,"(Subscript[I, MAX])"},0,1,.001,Appearance->"Labeled"}]}
},Alignment->Right,Spacings->{2.5,.2}]

},Spacings->2]

}]
,Delimiter

(************ Background ***********)


,Item[Style["Background",14]]

,Grid[{{Row[{

(********************)
(* Reset background *)
(********************)

Tooltip[Button["Reset",
	
If[taskDone=="Blue region subtracted",
{images,bleachRefImages,backgroundSpectrum}=BackgroundReset[images,bleachRefImages,backgroundSpectrum,bleachRefLambdaPosition],
If[taskDone=="Ref backg image subtracted",
images=images+importResult[[2]];
importResult[[2]]=0;
intensityData = Total[images]/Length[images]/2^16;
	{adjustContrastMin,adjustContrastMax}=Round[Sort[Flatten[intensityData]][[{10,-10}]],.00001];
	intensityHistogram=IntensityHistogram[intensityData,{adjustContrastMin,adjustContrastMax}]
,
If[taskDone=="Illumination profile subtracted",
images=images[[#]]*IlluminationProfile&/@Range[Length[images]];
intensityData = Total[images]/Length[images]/2^16;
	{adjustContrastMin,adjustContrastMax}=Round[Sort[Flatten[intensityData]][[{10,-10}]],.00001];
	intensityHistogram=IntensityHistogram[intensityData,{adjustContrastMin,adjustContrastMax}]],

]];	

taskDone="";
	(*prepare for fitting the green point*)
	{fitSwitches,initialValues,parameterLimits}=
		 	ControlsFit[fitNComponents,fitSwitchPortion1,fitSwitchLambdaMax1,fitSwitchWidth1,fitSwitchAssymetry1,fitSwitchBleach1,fitSwitchLambdaMax2,fitSwitchWidth2,fitSwitchWidth2,fitSwitchAssymetry2,fitSwitchBleach2,oxygenation,manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen,limitPortionLow,limitPortionHigh,limitLambdaMaxLow,limitLambdaMaxHigh,limitWidthLow,limitWidthHigh,limitAsymmetryLow,limitAsymmetryHigh,limitBleachLow,limitBleachHigh,limitOxyLow,limitOxyHigh,exposureTime];
	
	(*fit the green point*)
	{noise,parametersPoint,plotSpectrum,plotBleachRef,parametersPointTable,spectraPoint}=
		AnalizeOnePoint[images,cropPoint,cropBackground,randomSampling,lambdaSample,(*hemSpectra,*)exposureTime,fitSignalThreshold,{fitSwitches,initialValues,parameterLimits},{bleachRefMode,bleachRefImages,bleachRefLambda,bleachRefFrameNumbers}];
	(*refresh the manual settings and limits*)
	{manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen}=parametersPoint[[{5,6,7,8,9,12,13,14,15,16}]];	
	
	resultsSavedQ=False;
	,ImageSize->buttonSize,Enabled->imagesLoadedQ],
"Restore original signal"]

(***********************)
(* Subtract background *)
(***********************)

,Tooltip[Button["Subtract blue region",
	{images,bleachRefImages,backgroundSpectrum}=BackgroundSubtractFromImage[images,bleachRefImages,cropBackground,bleachRefLambdaPosition];
			
	taskDone="Blue region subtracted";

	(*prepare for fitting the green point*)
	{fitSwitches,initialValues,parameterLimits}=
		ControlsFit[fitNComponents,fitSwitchPortion1,fitSwitchLambdaMax1,fitSwitchWidth1,fitSwitchAssymetry1,fitSwitchBleach1,fitSwitchLambdaMax2,fitSwitchWidth2,fitSwitchWidth2,fitSwitchAssymetry2,fitSwitchBleach2,oxygenation,manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen,limitPortionLow,limitPortionHigh,limitLambdaMaxLow,limitLambdaMaxHigh,limitWidthLow,limitWidthHigh,limitAsymmetryLow,limitAsymmetryHigh,limitBleachLow,limitBleachHigh,limitOxyLow,limitOxyHigh,exposureTime];
	
	(*fit the green point*)
	{noise,parametersPoint,plotSpectrum,plotBleachRef,parametersPointTable,spectraPoint}=
		AnalizeOnePoint[images,cropPoint,cropBackground,randomSampling,lambdaSample,(*hemSpectra,*)exposureTime,fitSignalThreshold,
			{fitSwitches,initialValues,parameterLimits},{bleachRefMode,bleachRefImages,bleachRefLambda,bleachRefFrameNumbers}];
	(*refresh the manual settings and limits*)
	{manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen}=parametersPoint[[{5,6,7,8,9,12,13,14,15,16}]];	

	resultsSavedQ=False;
	,ImageSize->buttonSize,Enabled->imagesLoadedQ],
Row[{"Subtract average spectrum from  ",Style["□",Blue,Bold,20],"  all over the image"}]]
}]},

{Tooltip[Button[Style["Subtract BLANK SAMPLE spectral image",Darker[Red],11],

taskDone="Ref backg image subtracted";

(*fileNameBackgCode={"backg","vzorca"};
fileNamesBackg=Flatten[FileNames[___~~ToString[fileNameBackgCode[[#]]]~~___~~".dsc",{importFolder}]&/@Range[Length[fileNameBackgCode]]];
If[Length[fileNamesBackg]>0 *)

(*get all the data from background spectral aquisition; images ordered by wavelength*)
importResult=ImportImages[importFolder,(*fileNamesBackg[[#]]*)"",lctfCorrectionFileName](*&/@Range[Length[fileNameBackgCode]]*);

lambdaRef=importResult[[4]](*&/@Range[Length[fileNameBackgCode]]*);
expTimeRef=importResult[[5]](*&/@Range[Length[fileNameBackgCode]]*);

If[Sort[lambdaRef]==Sort[lambdaSample] (*&&expTimeRef==exposureTime*),
imagesDataPop=Abs[images-importResult[[2]]*N[exposureTime/expTimeRef]];

,imagesDataPop=images
](*&/@Range[Length[fileNameBackgCode]]*);
images=imagesDataPop;

(*Shrani podatke blank vzorca za morebitni Batch fit*)
blankSampleData=importResult[[2]]*N[exposureTime/expTimeRef];


(*show the original non-corrected image below the corrected one*)
intensityDataOriginal=intensityData;
adjustContrastMinOriginal=adjustContrastMin;
adjustContrastMinOriginal=adjustContrastMax;

(*show the corrected image*)
intensityData = Total[images]/Length[images]/2^16;
	{adjustContrastMin,adjustContrastMax}=Round[Sort[Flatten[intensityData]][[{10,-10}]],.00001];
	intensityHistogram=IntensityHistogram[intensityData,{adjustContrastMin,adjustContrastMax}];

(*prepare for fitting the green point*)
	{fitSwitches,initialValues,parameterLimits}=
		 ControlsFit[fitNComponents,fitSwitchPortion1,fitSwitchLambdaMax1,fitSwitchWidth1,fitSwitchAssymetry1,fitSwitchBleach1,fitSwitchLambdaMax2,fitSwitchWidth2,fitSwitchWidth2,fitSwitchAssymetry2,fitSwitchBleach2,oxygenation,manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen,limitPortionLow,limitPortionHigh,limitLambdaMaxLow,limitLambdaMaxHigh,limitWidthLow,limitWidthHigh,limitAsymmetryLow,limitAsymmetryHigh,limitBleachLow,limitBleachHigh,limitOxyLow,limitOxyHigh,exposureTime];
	
	(*fit the green point*)
	{noise,parametersPoint,plotSpectrum,plotBleachRef,parametersPointTable,spectraPoint}=
		AnalizeOnePoint[images,cropPoint,cropBackground,randomSampling,lambdaSample,(*hemSpectra,*)exposureTime,fitSignalThreshold,
			{fitSwitches,initialValues,parameterLimits},{bleachRefMode,bleachRefImages,bleachRefLambda,bleachRefFrameNumbers}];
	(*refresh the manual settings and limits*)
	{manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen}=parametersPoint[[{5,6,7,8,9,12,13,14,15,16}]];	
	
	resultsSavedQ=False;
	,ImageSize->buttonSize,Enabled->imagesLoadedQ,
Method->"Queued",FrameMargins->{{30,30},{1,1}}],

"IF spectral aquisition of a BLANK SAMPLE was implemented"]
},
{Tooltip[Button[Style["Correct for uneven ILLUMINATION profile",Darker[Blue],11],

taskDone="Illumination profile subtracted";

IlluminationProfileData=Import[IlluminationProfileCorrectionFileName,"Image"];
IlluminationProfile=ImageData[IlluminationProfileData];
IlluminationProfileMax=Max[IlluminationProfile];
IlluminationProfile=IlluminationProfile/IlluminationProfileMax;

images=images[[#]]/IlluminationProfile&/@Range[Length[images]];

(*show the corrected image*)
intensityData = Total[images]/Length[images]/2^16;
	{adjustContrastMin,adjustContrastMax}=Round[Sort[Flatten[intensityData]][[{10,-10}]],.00001];
	intensityHistogram=IntensityHistogram[intensityData,{adjustContrastMin,adjustContrastMax}];

(*prepare for fitting the green point*)
	{fitSwitches,initialValues,parameterLimits}=
		 ControlsFit[fitNComponents,fitSwitchPortion1,fitSwitchLambdaMax1,fitSwitchWidth1,fitSwitchAssymetry1,fitSwitchBleach1,fitSwitchLambdaMax2,fitSwitchWidth2,fitSwitchWidth2,fitSwitchAssymetry2,fitSwitchBleach2,oxygenation,manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen,limitPortionLow,limitPortionHigh,limitLambdaMaxLow,limitLambdaMaxHigh,limitWidthLow,limitWidthHigh,limitAsymmetryLow,limitAsymmetryHigh,limitBleachLow,limitBleachHigh,limitOxyLow,limitOxyHigh,exposureTime];
	
	(*fit the green point*)
	{noise,parametersPoint,plotSpectrum,plotBleachRef,parametersPointTable,spectraPoint}=
		AnalizeOnePoint[images,cropPoint,cropBackground,randomSampling,lambdaSample,(*hemSpectra,*)exposureTime,fitSignalThreshold,
			{fitSwitches,initialValues,parameterLimits},{bleachRefMode,bleachRefImages,bleachRefLambda,bleachRefFrameNumbers}];
	(*refresh the manual settings and limits*)
	{manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen}=parametersPoint[[{5,6,7,8,9,12,13,14,15,16}]];	
	
	resultsSavedQ=False;

	(*fileNameParts={{Style["IlluminationProfile.tif",Bold],Style["lib",Bold]}};*)
	
	,ImageSize->buttonSize,Enabled->imagesLoadedQ,
Method->"Queued"
],
"Regularly check illumination profile and save it as <IlluminationProfile.tif> into the subfolder <lib>",LabelStyle->Red]
}}]

,Delimiter



(************ Fitting ***********)


,Item[Style["Fitting",14]]

,Grid[{

(* -||------------------------- *)
(* Data filtering and averaging *)
(* -------------------------||- *)

{Tooltip[Style["Threshold [σ]",12],"Minimal signal intenensity to be analized [noise level]"],Control[{{fitSignalThreshold,3.,""},1.,10.,.5,Appearance->"Labeled"}]},
{Tooltip[Style["Averaging [pix]",12],"Average n×n pixels before fitting"],Control[{{fitAveragingPix,5,""},1,51,2,Appearance->"Labeled"}]},

(* x  -||--------------------- *)
(* Fitted parameters' controls *)
(* x  ---------------------||- *)

{Tooltip[Style["N of components:",12],"Number of spectral components used"],Control[{{fitNComponents,2,""},{1->"\t  1  \t",2->"\t  2  \t"}}]},
{Tooltip[Style["\nParameters to fit:",12],"Select variable parameters for optimization"],Tooltip[Style["\nStarting or fixed parameter values:",12],"Set initial parameter values; for non-optimized parameters they will be kept constant"]},
{Control[{{fitSwitchPortion1,True,"(Subscript[p, 1])"},{True,False},Enabled->fitNComponents==2}],
Control[{{manualSetPortion1,.9,""},0.01,1.,.01,Appearance->"Labeled",Enabled->fitNComponents==2}]},
{Control[{{fitSwitchLambdaMax1,True,"(Subscript[λ, MAX, 1]) [nm]"},{True,False}}],
Control[{{manualSetLambdaMax1,560,""},limitLambdaMaxLow,limitLambdaMaxHigh,1,Appearance->"Labeled"}]},
{Control[{{fitSwitchLambdaMax2,False,"(Subscript[λ, MAX, 2]) [nm]"},{True,False},Enabled->fitNComponents==2}],
Control[{{manualSetLambdaMax2,600,""},limitLambdaMaxLow,limitLambdaMaxHigh,1,Appearance->"Labeled",Enabled->fitNComponents==2}]},
{Control[{{fitSwitchWidth1,False,"(Subscript[w, 1]) [nm]"},{True,False}}],
Control[{{manualSetWidth1,140,""},limitWidthLow,limitWidthHigh,1,Appearance->"Labeled"}]},
{Control[{{fitSwitchWidth2,False,"(Subscript[w, 2]) [nm]"},{True,False},Enabled->fitNComponents==2}],
Control[{{manualSetWidth2,100,""},limitWidthLow,limitWidthHigh,1,Appearance->"Labeled",Enabled->fitNComponents==2}]},
{Control[{{fitSwitchAssymetry1,False,"(Subscript[a, 1])"},{True,False}}],
Control[{{manualSetAsymmetry1,.24,""},limitAsymmetryLow,limitAsymmetryHigh,.01,Appearance->"Labeled"}]},
{Control[{{fitSwitchAssymetry2,False,"(Subscript[a, 2])"},{True,False},Enabled->fitNComponents==2}],
Control[{{manualSetAsymmetry2,.21,""},limitAsymmetryLow,limitAsymmetryHigh,.01,Appearance->"Labeled",Enabled->fitNComponents==2}]},
{Control[{{fitSwitchBleach1,False,"(Subscript[b, 1]) [(s^(-1))]"},{True,False}}],
Control[{{manualSetBleach1,0,""},limitBleachLow,limitBleachHigh,.005,Appearance->"Labeled"}]},
{Control[{{fitSwitchBleach2,False,"(Subscript[b, 2]) [(s^(-1))]"},{True,False},Enabled->fitNComponents==2}],
Control[{{manualSetBleach2,0,""},limitBleachLow,limitBleachHigh,.005,Appearance->"Labeled",Enabled->fitNComponents==2}]},
{Control[{{oxygenation,False,Tooltip[Style["Oxygenation",12],"Oxy/DeOxy"]},{True,False},Enabled->fitNComponents==2}],Control[{{manualSetOxygen,1.,""},limitOxyLow,limitOxyHigh,.005,Appearance->"Labeled",Enabled->fitNComponents==2}]},
(*{,},*)

(* x  >>>>>>>>>>>> *)
(* Image alignment *)
(* x  >>>>>>>>>>>> *)

{Tooltip[Control[{{fitAlignImages,False,Style["Align images:",12]},{True,False}}],"Correct images for object movement"]
,Tooltip[Control[{{fitAlignMethod,"Rigid",""},{"Translation","Rigid","Similarity","Affine","Perspective"},Enabled->fitAlignImages,ControlType->PopupMenu,FrameMargins->-5,BaselinePosition->Top}],"Select alignment method (sorted from simplest to slowest)"]}
},Alignment->{{Right,Left},Center},Spacings->{2.5,{0,0,1,1,.8,.8,{-.2,.8},1,0}}(*Spacings->{2.5,.2}*)]


,Item[Style["",12]]
,OpenerView[{
Item[Style["Fit options:",12],Alignment->Left],
Column[{

(* -||------------- *)
(* Parameter limits *)
(* -------------||- *)

Grid[Transpose[{{Tooltip[Style["\nParamter limits:",12],"Limit optimization to specified parameter values"],
"(Subscript[p, 1])","","(Subscript[λ, MAX]) [nm]","","w [nm]","","a","","b [(s^(-1))]","","HemOxy",""},
{,Control[{{limitPortionLow,0.0,""},0.,1.,.05,Appearance->"Labeled",Enabled->fitNComponents==2&&fitSwitchPortion1}]
,Control[{{limitPortionHigh,1.,""},0.,1.,.05,Appearance->"Labeled",Enabled->fitNComponents==2&&fitSwitchPortion1}]
,Control[{{limitLambdaMaxLow,400,""},400,700,10,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchLambdaMax1||fitSwitchLambdaMax2,fitSwitchLambdaMax1]}]
,Control[{{limitLambdaMaxHigh,700,""},400,700,10,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchLambdaMax1||fitSwitchLambdaMax2,fitSwitchLambdaMax1]}]
,Control[{{limitWidthLow,20,""},20,120,10,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchWidth1||fitSwitchWidth2,fitSwitchWidth1]}]
,Control[{{limitWidthHigh,140,""},20,140,10,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchWidth1||fitSwitchWidth2,fitSwitchWidth1]}]
,Control[{{limitAsymmetryLow,0.01,""},0.01,.5,.01,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchAssymetry1||fitSwitchAssymetry2,fitSwitchAssymetry1]}]
,Control[{{limitAsymmetryHigh,.5,""},0.01,.5,.01,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchAssymetry1||fitSwitchAssymetry2,fitSwitchAssymetry1]}]
,Control[{{limitBleachLow,0.,""},0.,1.,.005,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchBleach1||fitSwitchBleach2,fitSwitchBleach1]}]
,Control[{{limitBleachHigh,1.,""},0.,1.,.005,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchBleach1||fitSwitchBleach2,fitSwitchBleach1]}]
,Control[{{limitOxyLow,0.,""},0.,1.,.005,Appearance->"Labeled",Enabled->fitNComponents==2&&oxygenation}]
,Control[{{limitOxyHigh,1.,""},0.,1.,.005,Appearance->"Labeled",Enabled->fitNComponents==2&&oxygenation}]
}}],Alignment->Right,Spacings->{2.5,{0,0,{-.1,.8},0}}]

(* x x x x x x *)
(* Computation *)
(* x x x x x x *)

,Grid[{
{,Style["\nComputation:", 12]
,Tooltip[Control[{{fitCompiled,True,"use compiled functions"},{True,False}}],"Compiled version works much faster - uncheck only if having troubles with compilation"]
,Tooltip[Control[{{fitParallel,True,"run in parallel"},{True,False}}],"Use parallelization - uncheck only if computer gets unresponsive (runs out of memory)"]}
},Spacings->{1,1},Alignment->{Right,Bottom}]
}]
}]

,
Row[{

(*********************************)
(* Fit spectrum from green point *)
(*********************************)

Tooltip[Button["Fit point",
	$parameterSymbolsForm=If[fitNComponents==1,
	{"x [pix]","y [pix]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"0\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"1\"]\) [a.u.]","\!\(\*
StyleBox[\"p\",\nFontSlant->\"Italic\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"λ\",\nFontSlant->\"Italic\"], \"MAX\"]\) [nm]","\!\(\*
StyleBox[\"w\",\nFontSlant->\"Italic\"]\) [nm]","\!\(\*
StyleBox[\"a\",\nFontSlant->\"Italic\"]\) []","\!\(\*
StyleBox[\"b\",\nFontSlant->\"Italic\"]\) [(s^(-1))]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"2\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"p\",\nFontSlant->\"Italic\"], \"2\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"λ\",\nFontSlant->\"Italic\"], 
 RowBox[{\"MAX\", \",\", \"2\"}]]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"w\",\nFontSlant->\"Italic\"], \"2\"]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"a\",\nFontSlant->\"Italic\"], \"2\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"b\",\nFontSlant->\"Italic\"], \"2\"]\) [(s^(-1))]","\!\(\*SuperscriptBox[
 StyleBox[\"χ\",\nFontSlant->\"Italic\"], \"2\"]\) [\!\(\*
StyleBox[\"N\",\nFontSlant->\"Italic\"]\) \!\(\*SuperscriptBox[
 StyleBox[\"σ\",\nFontSlant->\"Italic\"], \"2\"]\)]"},
	{"x [pix]","y [pix]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"0\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"1\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"p\",\nFontSlant->\"Italic\"], \"1\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"λ\",\nFontSlant->\"Italic\"], 
 RowBox[{\"MAX\", \",\", \"1\"}]]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"w\",\nFontSlant->\"Italic\"], \"1\"]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"a\",\nFontSlant->\"Italic\"], \"1\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"b\",\nFontSlant->\"Italic\"], \"1\"]\) [(s^(-1))]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"2\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"p\",\nFontSlant->\"Italic\"], \"2\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"λ\",\nFontSlant->\"Italic\"], 
 RowBox[{\"MAX\", \",\", \"2\"}]]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"w\",\nFontSlant->\"Italic\"], \"2\"]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"a\",\nFontSlant->\"Italic\"], \"2\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"b\",\nFontSlant->\"Italic\"], \"2\"]\) [(s^(-1))]","\!\(\*
 StyleBox[\"HemOxy\",\nFontSlant->\"Italic\"]\) []","\!\(\*SuperscriptBox[
 StyleBox[\"χ\",\nFontSlant->\"Italic\"], \"2\"]\) [\!\(\*
StyleBox[\"N\",\nFontSlant->\"Italic\"]\) \!\(\*SuperscriptBox[
 StyleBox[\"σ\",\nFontSlant->\"Italic\"], \"2\"]\)]"}
	];	
	(*prepare for fitting the green point*)
	{fitSwitches,initialValues,parameterLimits}=
		 ControlsFit[fitNComponents,fitSwitchPortion1,fitSwitchLambdaMax1,fitSwitchWidth1,fitSwitchAssymetry1,fitSwitchBleach1,fitSwitchLambdaMax2,fitSwitchWidth2,fitSwitchWidth2,fitSwitchAssymetry2,fitSwitchBleach2,oxygenation,manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen,limitPortionLow,limitPortionHigh,limitLambdaMaxLow,limitLambdaMaxHigh,limitWidthLow,limitWidthHigh,limitAsymmetryLow,limitAsymmetryHigh,limitBleachLow,limitBleachHigh,limitOxyLow,limitOxyHigh,exposureTime];

	(*fit the green point*)
	{noise,parametersPoint,plotSpectrum,plotBleachRef,parametersPointTable,spectraPoint}=
		AnalizeOnePoint[images,cropPoint,cropBackground,randomSampling,lambdaSample,(*hemSpectra,*)exposureTime,fitSignalThreshold,
			{fitSwitches,initialValues,parameterLimits},{bleachRefMode,bleachRefImages,bleachRefLambda,bleachRefFrameNumbers}];
	(*refresh the manual settings and limits*)
	{manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen}=parametersPoint[[{5,6,7,8,9,12,13,14,15,16}]];
	,Method->"Queued",ImageSize->buttonSize,Enabled->imagesLoadedQ
],Row[{"Recalculate the spectrum from ",Style["□",Green,Bold]}]]

(**********************************)
(* Fit spectra all over the image *)
(**********************************)

,Tooltip[Button["Fit image",
	resultsSavedQ=True;
	
	(*check if whole image will be fitted with no averaging; in this case warn the user and cancel the fitting*)
	If[Abs[xyCrop1-xyCrop2]=={511,511}&&fitAveragingPix==1,
		CreateDialog[{TextCell["THE CALCULATION MAY TAKE SEVERAL MINUTES AND CAUSE YOUR COMPUTER TO FREEZE! \n\nDO YOU STILL WANT TO CONTINUE? \n\nTo speed up the calculation, you can crop the area or increse the averaging."],
Row[{
Button["Continue",DialogReturn[]],
Button[" Cancel ",DialogReturn[FrontEndExecute[FrontEndToken["EvaluatorAbort"]]]]
}]
}
];
Pause[10];
];

	imagesCC={{"color-coded images"}};plotHistograms={{"histograms"}};plotsFitSpectra="spectra";imageIntensityCropAligned="";
	$parameterSymbolsForm=If[fitNComponents==1,
	{"x [pix]","y [pix]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"0\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"1\"]\) [a.u.]","\!\(\*
StyleBox[\"p\",\nFontSlant->\"Italic\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"λ\",\nFontSlant->\"Italic\"], \"MAX\"]\) [nm]","\!\(\*
StyleBox[\"w\",\nFontSlant->\"Italic\"]\) [nm]","\!\(\*
StyleBox[\"a\",\nFontSlant->\"Italic\"]\) []","\!\(\*
StyleBox[\"b\",\nFontSlant->\"Italic\"]\) [(s^(-1))]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"2\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"p\",\nFontSlant->\"Italic\"], \"2\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"λ\",\nFontSlant->\"Italic\"], 
 RowBox[{\"MAX\", \",\", \"2\"}]]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"w\",\nFontSlant->\"Italic\"], \"2\"]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"a\",\nFontSlant->\"Italic\"], \"2\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"b\",\nFontSlant->\"Italic\"], \"2\"]\) [(s^(-1))]","\!\(\*SuperscriptBox[
 StyleBox[\"χ\",\nFontSlant->\"Italic\"], \"2\"]\) [\!\(\*
StyleBox[\"N\",\nFontSlant->\"Italic\"]\) \!\(\*SuperscriptBox[
 StyleBox[\"σ\",\nFontSlant->\"Italic\"], \"2\"]\)]"},
	{"x [pix]","y [pix]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"0\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"1\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"p\",\nFontSlant->\"Italic\"], \"1\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"λ\",\nFontSlant->\"Italic\"], 
 RowBox[{\"MAX\", \",\", \"1\"}]]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"w\",\nFontSlant->\"Italic\"], \"1\"]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"a\",\nFontSlant->\"Italic\"], \"1\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"b\",\nFontSlant->\"Italic\"], \"1\"]\) [(s^(-1))]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"2\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"p\",\nFontSlant->\"Italic\"], \"2\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"λ\",\nFontSlant->\"Italic\"], 
 RowBox[{\"MAX\", \",\", \"2\"}]]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"w\",\nFontSlant->\"Italic\"], \"2\"]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"a\",\nFontSlant->\"Italic\"], \"2\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"b\",\nFontSlant->\"Italic\"], \"2\"]\) [(s^(-1))]","\!\(\*
 StyleBox[\"HemOxy\",\nFontSlant->\"Italic\"]\) []","\!\(\*SuperscriptBox[
 StyleBox[\"χ\",\nFontSlant->\"Italic\"], \"2\"]\) [\!\(\*
StyleBox[\"N\",\nFontSlant->\"Italic\"]\) \!\(\*SuperscriptBox[
 StyleBox[\"σ\",\nFontSlant->\"Italic\"], \"2\"]\)]"}
	];
	(*prepare for fitting*)
	{fitSwitches,initialValues,parameterLimits}=
		ControlsFit[fitNComponents,fitSwitchPortion1,fitSwitchLambdaMax1,fitSwitchWidth1,fitSwitchAssymetry1,fitSwitchBleach1,fitSwitchLambdaMax2,fitSwitchWidth2,fitSwitchWidth2,fitSwitchAssymetry2,fitSwitchBleach2,oxygenation,manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen,limitPortionLow,limitPortionHigh,limitLambdaMaxLow,limitLambdaMaxHigh,limitWidthLow,limitWidthHigh,limitAsymmetryLow,limitAsymmetryHigh,limitBleachLow,limitBleachHigh,limitOxyLow,limitOxyHigh,exposureTime];

(*Print[{fitSwitches,initialValues,parameterLimits}];*)

	(*fit*)
	{t,{parameters,plotsFitSpectra,selectedPointsToLabel,intensityMax(*{intensityMax,colorLimitIntensityLow,colorLimitIntensityHigh}*),imageIntensityCropAligned,spectraPoints,specFit}}=AnalizeImages[images,crop,lambdaSample,exposureTime,fitAveragingPix,noise,fitSignalThreshold,
	fitSwitches,initialValues,parameterLimits,
	{bleachRefMode,bleachRefImages,bleachRefLambda,bleachRefFrameNumbers},
	"AlignImages"->fitAlignImages,"AlignMethod"->fitAlignMethod,"UseCompiled"->fitCompiled,"UseParallel"->fitParallel]//AbsoluteTiming;



	(*color scale limits*)
	colorLimits=ControlsColor[(*{colorLimitIntensityLow,colorLimitIntensityHigh},*){colorLimitIntensity1Low,colorLimitIntensity1High},{colorLimitIntensity2Low,colorLimitIntensity2High},{colorLimitPortionLow,colorLimitPortionHigh},{colorLimitLambdaMaxLow,colorLimitLambdaMaxHigh},{colorLimitWidthLow,colorLimitWidthHigh},{colorLimitAsymmetryLow,colorLimitAsymmetryHigh},{colorLimitBleachLow,colorLimitBleachHigh},{colorLimitHemOxyLow,colorLimitHemOxyHigh},parameters,fitNComponents];

	If[{colorLimitIntensity1Low,colorLimitIntensity1High}=={0.,1.}||{colorLimitIntensity2Low,colorLimitIntensity2High}=={0.,1.},
	{{colorLimitIntensity1Low,colorLimitIntensity1High},{colorLimitIntensity2Low,colorLimitIntensity2High}}=colorLimits[[{4,10}]]];
	
(*Print[colorLimits];*)

	(*draw color-coded images, add labels, and draw histograms*)
	{plotHistograms,imagesCC,imagesCCshow}=AnalizeFitParameters[parameters,fitSwitches,colorLimits,fitAveragingPix,selectedPointsToLabel,hemRegionDensityThresh];

	fittedDataQ=True;
	
	, Method->"Queued",ImageSize->buttonSize,Enabled->imagesLoadedQ
],"Run optimization"]

}]


(**************************)
(* Fit a series of images *)
(**************************)

,Tooltip[Button["Batch fit and export",
batchStartQ=False;
(*CreateDialog[{TextCell["Have you checked ALL settings (fitting, coloring, saving)?"],DefaultButton[]}];*)
batchStartQ=ChoiceDialog["Are you sure you want to FIT ALL FMS EXPERIMENTS IN THE FOLDER of the currently open file?",{"  Yes, proceed to fitting!  "->True,"  No, I was just curious ..  "->False}];
If[!batchStartQ,Return[]];
batchStartQ=ChoiceDialog["Have you CHECKED ALL SETTINGS for fitting, color-coding and saving? They will apply to all experiments!",{"  Yes, proceed to fitting!  "->True,"  No, I want to check again!  "->False}];
If[!batchStartQ,Return[]];

backgroundSubtractQ=ChoiceDialog["Do you want to SUBTRACT THE BACKGROUND SIGNAL from the area enclosed by the blue rectangle in every experiment?",{"  Yes  "->True,"  No  "->False}];

backgroundSubtractBlank=ChoiceDialog["Do you want to SUBTRACT THE BACKGROUND SIGNAL from the blank sample in every experiment?",{"  Yes  "->True,"  No  "->False}];

namesBatch=FileNames[__~~".dsc",importFolder];
namesBatch=FileNameTake/@namesBatch;(*just take the filename from the path*)
namesBatch=DeleteCases[namesBatch,name<>".dsc"]; (*exclude the experiment already fitted*)

iBatch=0;
CreateDialog[{Column[{
"Sit back and relax ...",
ProgressIndicator[Dynamic[iBatch],{0,Length[namesBatch]}],
Dynamic[If[iBatch<Length[namesBatch],namesBatch[[iBatch+1]],"Finished!"]]
}],
Row[{DefaultButton["OK",DialogReturn[],ImageSize->100],CancelButton["Abort",DialogReturn[FrontEndExecute[FrontEndToken["EvaluatorAbort"]]],ImageSize->100]}]}
,WindowTitle->"FMS batch fitting .. "];


For[i=1,i≤Length[namesBatch],i++,
iBatch=i-1;
PrintTemporary[namesBatch[[i]]];
(*Pause[1];*)

imagesCC=imagesCCshow={{"color-coded images"}};plotHistograms={{"histograms"}};plotsFitSpectra="fitted spectra";imageIntensityCropAligned="";
Clear[importResult];	
imagesLoadedQ=False;
fittedDataQ=False;

importResult=ImportImages[importFolder,namesBatch[[i]],lctfCorrectionFileName,"BatchModeQ"->batchStartQ];

If[Length[importResult]>0, (*if opening of a new experiment was not cancelled, refresh everything, else do nothing*)
	
	{name,images,intensityData,lambdaSample,exposureTime,randomSampling,experimentData,importFolder,{bleachRefMode,bleachRefImages,bleachRefLambda,bleachRefFrameNumbers}}=importResult;
	imagesLoadedQ=True;	

	(*intensity image*)
	{adjustContrastMin,adjustContrastMax}=Round[Sort[Flatten[intensityData]][[{10,-10}]],.00001];	
	(*intensityHistogram=IntensityHistogram[intensityData,{adjustContrastMin,adjustContrastMax}];*)
	
	backgroundSpectrum=0;


	If[backgroundSubtractQ,
		{images,bleachRefImages,backgroundSpectrum}=BackgroundSubtractFromImage[images,bleachRefImages,cropBackground,bleachRefLambdaPosition];
	];	

	If[backgroundSubtractBlank,
		images=images-blankSampleData;
	];
	
	(*position of bleachRefLambda in the lambda range - used for background subtraction*)
	bleachRefLambdaPosition=Position[Sort[lambdaSample],Nearest[lambdaSample,bleachRefLambda][[1]]][[1,1]];

	(*if no info on bleaching is available, set b=0 and don't fit bleaching rates*)	
	If[Not[randomSampling||bleachRefMode],
	fitSwitchBleach1=fitSwitchBleach2=False;
	manualSetBleach1=manualSetBleach2=0.;
	];

	(*prepare for fitting the green point*)
	{fitSwitches,initialValues,parameterLimits}=
		 ControlsFit[fitNComponents,fitSwitchPortion1,fitSwitchLambdaMax1,fitSwitchWidth1,fitSwitchAssymetry1,fitSwitchBleach1,fitSwitchLambdaMax2,fitSwitchWidth2,fitSwitchWidth2,fitSwitchAssymetry2,fitSwitchBleach2,oxygenation,manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen,limitPortionLow,limitPortionHigh,limitLambdaMaxLow,limitLambdaMaxHigh,limitWidthLow,limitWidthHigh,limitAsymmetryLow,limitAsymmetryHigh,limitBleachLow,limitBleachHigh,limitOxyLow,limitOxyHigh,exposureTime];
	
	(*fit the green point*)
	{noise,parametersPoint,plotSpectrum,plotBleachRef,parametersPointTable,spectraPoint}=
		AnalizeOnePoint[images,cropPoint,cropBackground,randomSampling,lambdaSample,(*hemSpectra,*)exposureTime,fitSignalThreshold,
			{fitSwitches,initialValues,parameterLimits},{bleachRefMode,bleachRefImages,bleachRefLambda,bleachRefFrameNumbers}];
	
	(*refresh the manual settings and limits*)
(*	{manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2}=parametersPoint[[{5,6,7,8,9,12,13,14,15}]];		
	{limitLambdaMaxLow,limitLambdaMaxHigh}={Min[lambdaSample],Max[lambdaSample]};*)
	{{colorLimitIntensity1Low,colorLimitIntensity1High},{colorLimitIntensity2Low,colorLimitIntensity2High}}={{0.,1.},{0.,1.}};
	

Clear[importResult];


(*check if whole image will be fitted with no averaging; in this case warn the user and cancel the fitting*)
	If[Abs[xyCrop1-xyCrop2]=={511,511}&&fitAveragingPix==1,
		CreateDialog[{TextCell["THE CALCULATION MAY TAKE SEVERAL MINUTES AND CAUSE YOUR COMPUTER TO FREEZE! \n\nDO YOU STILL WANT TO CONTINUE? \n\nTo speed up the calculation, you can crop the area or increse the averaging."],
Row[{
Button["Continue",DialogReturn[]],
Button[" Cancel ",DialogReturn[FrontEndExecute[FrontEndToken["EvaluatorAbort"]]]]
}]
}
];
Pause[10];
];

	
	$parameterSymbolsForm=If[fitNComponents==1,
	{"x [pix]","y [pix]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"0\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"1\"]\) [a.u.]","\!\(\*
StyleBox[\"p\",\nFontSlant->\"Italic\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"λ\",\nFontSlant->\"Italic\"], \"MAX\"]\) [nm]","\!\(\*
StyleBox[\"w\",\nFontSlant->\"Italic\"]\) [nm]","\!\(\*
StyleBox[\"a\",\nFontSlant->\"Italic\"]\) []","\!\(\*
StyleBox[\"b\",\nFontSlant->\"Italic\"]\) [(s^(-1))]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"2\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"p\",\nFontSlant->\"Italic\"], \"2\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"λ\",\nFontSlant->\"Italic\"], 
 RowBox[{\"MAX\", \",\", \"2\"}]]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"w\",\nFontSlant->\"Italic\"], \"2\"]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"a\",\nFontSlant->\"Italic\"], \"2\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"b\",\nFontSlant->\"Italic\"], \"2\"]\) [(s^(-1))]","\!\(\*SuperscriptBox[
 StyleBox[\"χ\",\nFontSlant->\"Italic\"], \"2\"]\) [\!\(\*
StyleBox[\"N\",\nFontSlant->\"Italic\"]\) \!\(\*SuperscriptBox[
 StyleBox[\"σ\",\nFontSlant->\"Italic\"], \"2\"]\)]"},
	{"x [pix]","y [pix]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"0\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"1\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"p\",\nFontSlant->\"Italic\"], \"1\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"λ\",\nFontSlant->\"Italic\"], 
 RowBox[{\"MAX\", \",\", \"1\"}]]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"w\",\nFontSlant->\"Italic\"], \"1\"]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"a\",\nFontSlant->\"Italic\"], \"1\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"b\",\nFontSlant->\"Italic\"], \"1\"]\) [(s^(-1))]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"2\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"p\",\nFontSlant->\"Italic\"], \"2\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"λ\",\nFontSlant->\"Italic\"], 
 RowBox[{\"MAX\", \",\", \"2\"}]]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"w\",\nFontSlant->\"Italic\"], \"2\"]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"a\",\nFontSlant->\"Italic\"], \"2\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"b\",\nFontSlant->\"Italic\"], \"2\"]\) [(s^(-1))]","\!\(\*
 StyleBox[\"HemOxy\",\nFontSlant->\"Italic\"]\) []","\!\(\*SuperscriptBox[
 StyleBox[\"χ\",\nFontSlant->\"Italic\"], \"2\"]\) [\!\(\*
StyleBox[\"N\",\nFontSlant->\"Italic\"]\) \!\(\*SuperscriptBox[
 StyleBox[\"σ\",\nFontSlant->\"Italic\"], \"2\"]\)]"}
	];

	(*prepare for fitting*)
	{fitSwitches,initialValues,parameterLimits}=
		 ControlsFit[fitNComponents,fitSwitchPortion1,fitSwitchLambdaMax1,fitSwitchWidth1,fitSwitchAssymetry1,fitSwitchBleach1,fitSwitchLambdaMax2,fitSwitchWidth2,fitSwitchWidth2,fitSwitchAssymetry2,fitSwitchBleach2,oxygenation,manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2,manualSetOxygen,limitPortionLow,limitPortionHigh,limitLambdaMaxLow,limitLambdaMaxHigh,limitWidthLow,limitWidthHigh,limitAsymmetryLow,limitAsymmetryHigh,limitBleachLow,limitBleachHigh,limitOxyLow,limitOxyHigh,exposureTime];

	(*fit*)
	{t,{parameters,plotsFitSpectra,selectedPointsToLabel,intensityMax(*{intensityMax,colorLimitIntensityLow,colorLimitIntensityHigh}*),imageIntensityCropAligned,spectraPoints,specFit}}=AnalizeImages[images,crop,lambdaSample,exposureTime,fitAveragingPix,noise,fitSignalThreshold,
	fitSwitches,initialValues,parameterLimits,
	{bleachRefMode,bleachRefImages,bleachRefLambda,bleachRefFrameNumbers},
	"AlignImages"->fitAlignImages,"AlignMethod"->fitAlignMethod,"UseCompiled"->fitCompiled,"UseParallel"->fitParallel]//AbsoluteTiming;



	(*color scale limits*)
	colorLimits=ControlsColor[(*{colorLimitIntensityLow,colorLimitIntensityHigh},*){colorLimitIntensity1Low,colorLimitIntensity1High},{colorLimitIntensity2Low,colorLimitIntensity2High},{colorLimitPortionLow,colorLimitPortionHigh},{colorLimitLambdaMaxLow,colorLimitLambdaMaxHigh},{colorLimitWidthLow,colorLimitWidthHigh},{colorLimitAsymmetryLow,colorLimitAsymmetryHigh},{colorLimitBleachLow,colorLimitBleachHigh},{colorLimitHemOxyLow,colorLimitHemOxyHigh},parameters,fitNComponents];

	If[{colorLimitIntensity1Low,colorLimitIntensity1High}=={0.,1.}||{colorLimitIntensity2Low,colorLimitIntensity2High}=={0.,1.},
	{{colorLimitIntensity1Low,colorLimitIntensity1High},{colorLimitIntensity2Low,colorLimitIntensity2High}}=colorLimits[[{4,10}]]];
	
	(*draw color-coded images, add labels, and draw histograms*)
	{plotHistograms,imagesCC,imagesCCshow}=AnalizeFitParameters[parameters,fitSwitches,colorLimits,fitAveragingPix,selectedPointsToLabel,hemRegionDensityThresh];

	fittedDataQ=True;

	exportFolder=ExportResults[exportFolder,name,
		crop,exposureTime,
		{fitSwitches,initialValues},
		{parameters,spectraPoints,specFit,plotHistograms,plotsFitSpectra,intensityData,imageIntensityCropAligned,If[saveImagesCCFitPoints&&savePlots,imagesCCshow,imagesCC]},
		{saveParameters,saveHistograms,savePlots,saveImagesCC},
		{adjustContrastMin,adjustContrastMax},
		"SaveNamePrefixSufix"->namePrefixSufix,
		"SaveNameParameters"->ToString@nameParameters,"SaveNameImagesCC"->ToString@nameImagesCC,"SaveNameHistograms"->ToString@nameHistograms,"SaveNameSpectra"->ToString@nameSpectra,"SaveNameAll"->ToString@nameAllTogether,
		"SaveImagesCCTogether"->saveImagesCCTogether,"SaveImagesCCIntensity"->saveImagesCCIntensity,"SaveImagesCCIntensityCrop"->saveImagesCCIntensityCrop,"SaveImagesRaw"->saveImagesRaw,"SaveImagesCCAlign"->saveImagesCCAlign,
		"SaveAllImagesTogether"->saveAllImagesTogether,"SaveShowFileName"->saveShowFileName,"SaveImageFiletype"->saveImageFiletype,"SaveImageResolution"->saveImageResolution,"BatchModeQ"->batchStartQ
		];


];
];

iBatch=Length[namesBatch];


, Method->"Queued",Enabled->resultsSavedQ
],"Repeat the analysis for all images in the folder and save results"]


(************ Color-coding ***********)

,Delimiter

(* -||--------- *)
(* Color limits *)
(* ---------||- *)

,Tooltip[Item[Style["Color-coding",14]],"Select limits for color scaling"]
,Grid[Transpose[{{
"\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"1\"]\) [a.u.]","","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"2\"]\) [a.u.]","","(Subscript[p, 1])","","(Subscript[λ, MAX]) [nm]","","w [nm]","","a","","b [(s^(-1))]","","(Subscript[d, hem])","HemOxy",""(*,
Tooltip["contrast","Lower/upper intensity threshold relative to the point with highest signal;\ndefines what appears black and what saturated"],""*)},
{Control[{{colorLimitIntensity1Low,0,""},-0.5,1.4intensityMax,1,Appearance->"Labeled"}]
,Control[{{colorLimitIntensity1High,1,""},-0.5,1.4intensityMax,1,Appearance->"Labeled"}]
,Control[{{colorLimitIntensity2Low,0,""},-0.5,1.4intensityMax,1,Appearance->"Labeled",Enabled->fitNComponents==2}]
,Control[{{colorLimitIntensity2High,0.5,""},-0.5,1intensityMax,1,Appearance->"Labeled",Enabled->fitNComponents==2}]
,Control[{{colorLimitPortionLow,0.7,""},0.,1.,.01,Appearance->"Labeled",Enabled->fitNComponents==2&&fitSwitchPortion1}]
,Control[{{colorLimitPortionHigh,0.9,""},0.,1.,.01,Appearance->"Labeled",Enabled->fitNComponents==2&&fitSwitchPortion1}]
,Control[{{colorLimitLambdaMaxLow,560,""},400,700,1,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchLambdaMax1||fitSwitchLambdaMax2,fitSwitchLambdaMax1]}]
,Control[{{colorLimitLambdaMaxHigh,575,""},400,700,1,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchLambdaMax1||fitSwitchLambdaMax2,fitSwitchLambdaMax1]}]
,Control[{{colorLimitWidthLow,60,""},20,140,1,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchWidth1||fitSwitchWidth2,fitSwitchWidth1]}]
,Control[{{colorLimitWidthHigh,80,""},20,140,1,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchWidth1||fitSwitchWidth2,fitSwitchWidth1]}]
,Control[{{colorLimitAsymmetryLow,.18,""},0.01,.5,.01,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchAssymetry1||fitSwitchAssymetry2,fitSwitchAssymetry1]}]
,Control[{{colorLimitAsymmetryHigh,.22,""},0.01,.5,.01,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchAssymetry1||fitSwitchAssymetry2,fitSwitchAssymetry1]}]
,Control[{{colorLimitBleachLow,0.,""},0.,1.,.005,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchBleach1||fitSwitchBleach2,fitSwitchBleach1]}]
,Control[{{colorLimitBleachHigh,.1,""},0.,1.,.005,Appearance->"Labeled",Enabled->If[fitNComponents==2,fitSwitchBleach1||fitSwitchBleach2,fitSwitchBleach1]}]
,Control[{{hemRegionDensityThresh,0.15,""},0.01,0.5,.01,Appearance->"Labeled",Enabled->fitNComponents==2}]
,Control[{{colorLimitHemOxyLow,0.5,""},0.,1.,.01,Appearance->"Labeled",Enabled->fitNComponents==2&&fitSwitchPortion1}]
,Control[{{colorLimitHemOxyHigh,1.,""},0.,1.,.01,Appearance->"Labeled",Enabled->fitNComponents==2&&fitSwitchPortion1}]
(*,Control[{{colorLimitIntensityLow,0.,""},0.,1.,.01,Appearance->"Labeled"}]
,Control[{{colorLimitIntensityHigh,1.,""},0.,1.,.01,Appearance->"Labeled"}]*)
}}],Alignment->Right,Spacings->{2.5,{0,{-.2,.8},0}}]


(***********)
(* Recolor *)
(***********)

(*,Row[{

Tooltip[Button["Import fitted data",
	(*color scale limits*)

	
	fittedDataQ=True;
, Method->"Queued",ImageSize->buttonSize
],"Refresh color-coded images and histograms"]
*)
,Tooltip[Button["Recolor",
	(*color scale limits*)

	colorLimits=ControlsColor[(*{colorLimitIntensityLow,colorLimitIntensityHigh},*){colorLimitIntensity1Low,colorLimitIntensity1High},{colorLimitIntensity2Low,colorLimitIntensity2High},{colorLimitPortionLow,colorLimitPortionHigh},{colorLimitLambdaMaxLow,colorLimitLambdaMaxHigh},{colorLimitWidthLow,colorLimitWidthHigh},{colorLimitAsymmetryLow,colorLimitAsymmetryHigh},{colorLimitBleachLow,colorLimitBleachHigh},{colorLimitHemOxyLow,colorLimitHemOxyHigh},parameters,fitNComponents];
	
	(*redraw color-coded images, add labels, and redraw histograms (new parameter limits and intensity weighting)*)
	{plotHistograms,imagesCC,imagesCCshow}=AnalizeFitParameters[parameters,fitSwitches,colorLimits,fitAveragingPix,selectedPointsToLabel,hemRegionDensityThresh];

resultsSavedQ=False;

, Method->"Queued",(*ImageSize->buttonSize,*)Enabled->fittedDataQ
],"Refresh color-coded images and histograms"]

(*}]*)

(************ Export ***********)

,Delimiter

(* x x x x x x x x x x x x *)
(* Select items for saving *)
(* x x x x x x x x x x x x *)

,Grid[{
{Style["Save results",14],
Control[{{saveParameters,True,Tooltip["parameters","Save parameters from all points to a .txt file"]},{True,False}}],
Control[{{saveHistograms,True,Tooltip["histograms","Save histograms of parameter distributions"]},{True,False}}]},
{,
Control[{{saveImagesCC,True,Tooltip["color-coded images","Save color-coded images"]},{True,False}}],
Control[{{savePlots,True,Tooltip["spectra","Save the row of plots with experimental and fitted spectra"]},{True,False}}]}
},Spacings->{1,1},Alignment->{Right,Bottom}]

,Item[Style["",12]]

(* x x x x x x x x x  *)
(* Options for saving *)
(* x x x x x x x x x  *)

,OpenerView[{
Item[Style["Save options:",12],Alignment->Left],

Grid[
{
{Tooltip[Style["CC-images:",12],"Options for color-coded (CC) images"]
,Control[{{saveImagesCCTogether,True,Tooltip["all in one image","Save all color-coded images as one panel"]},{True,False},Enabled->saveImagesCC&&!saveAllImagesTogether}]
,Control[{{saveImagesCCIntensity,True,Tooltip["intensity","Include intensity image to compare with color-coded"]},{True,False},Enabled->saveImagesCC}]}
,{,Control[{{saveImagesCCFitPoints,True,Tooltip["show points 1..6","Show points where plotted spectra were extracted from"]},{True,False},Enabled->saveImagesCC&&savePlots}]
,Control[{{saveImagesCCIntensityCrop,False,Tooltip["crop intensity","Crop intensity image to the same area as color-coded"]},{True,False},Enabled->saveImagesCC&&saveImagesCCIntensity}]}
,{,Control[{{saveImagesRaw,False,Tooltip["FM/FMS images","Export FM/FMS images"]},{True,False},Enabled->saveImagesCC(*&&fitAlignImages*)}],Control[{{saveImagesCCAlign,True,Tooltip["alignment","Include small intensity images to compare before/after alignment"]},{True,False},Enabled->saveImagesCC&&fitAlignImages}]}
,{"",,}
,{Tooltip[Style["All graphics: ",12],"Options for all graphic output"]
,Control[{{saveAllImagesTogether,True,Tooltip["all in one image","Save all selected graphics as one image"]},{True,False},Enabled->Count[{saveImagesCC,saveHistograms,savePlots},True]≥2}]
,Control[{{saveShowFileName,True,Tooltip["show filename","Show filename at the top of each image"]},{True,False},Enabled->saveImagesCC||saveHistograms||savePlots}]
}
,{
,Control[{{saveImageFiletype,".png","filetype"},{".png",".jpg",".gif",".tif"},ControlType->PopupMenu,FrameMargins->-5,BaselinePosition->Bottom,Enabled->saveImagesCC||saveHistograms||savePlots}]
,Control[{{saveImageResolution,80,Tooltip["resolution","[dpi]"]},{80,100,150,200,300,600,900,1200},ControlType->PopupMenu,FrameMargins->-5,BaselinePosition->Bottom,Enabled->saveImagesCC||saveHistograms||savePlots}]
}
,{"",,}
,{Tooltip[Style["Output filenames:",12],"Modify filenames for saving"],
"expand as:",Tooltip[Control[{{namePrefixSufix,"Prefix",""},{"Prefix"->"   Prefix   ","Sufix"->"   Sufix   "}}],"Choose whether to put extension before (Prefix) of after (Sufix) experiment name"]}
,{,"parameters:",Control[{{nameParameters,nameParameters,""},String,FieldSize->9,Enabled->saveParameters}]}
,{,"color-coded images:",Control[{{nameImagesCC,nameImagesCC,""},String,FieldSize->9,Enabled->saveImagesCC&&!saveAllImagesTogether}]}
,{,"plotHistograms:",Control[{{nameHistograms,nameHistograms,""},String,FieldSize->9,Enabled->saveHistograms&&!saveAllImagesTogether}]}
,{,"fitted spectra:",Control[{{nameSpectra,nameSpectra,""},String,FieldSize->9,Enabled->savePlots&&!saveAllImagesTogether}]}
,{,"all graphics:",Control[{{nameAllTogether,nameAllTogether,""},String,FieldSize->9,Enabled->saveAllImagesTogether}]}

},Spacings->{1,1},Alignment->{Right,Bottom}]

}]

,Row[{

(***********************************)
(* Export spectra from green point *)
(***********************************)

Tooltip[Button["Export spectrum",
exportFolder=ExportSpectra[exportFolder,name,cropBackground,fitAveragingPix,parametersPoint,spectraPoint,fitSwitches,backgroundSpectrum];
, Method->"Queued",ImageSize->buttonSize,Enabled->imagesLoadedQ],
Row[{"Save experimental and fitted spectra from ",Style["□",Green,Bold]}]]

(*******************************)
(* Export results from fitting *)
(*******************************)

,Tooltip[Button["Export fit results",
(*	If[saveImagesCCIntensityCrop,
		imageIntensity=ArrayPlot[CropImages[{intensityData},crop][[1]],ColorFunction->GrayLevel,PlotRange->{adjustContrastMin,adjustContrastMax},ClippingStyle->{Black,White},Frame->False,ImageSize->300];
	];*)
	exportFolder=ExportResults[exportFolder,name,
		crop,exposureTime,
		{fitSwitches,initialValues},
		{parameters,spectraPoints,specFit,plotHistograms,plotsFitSpectra,intensityData,imageIntensityCropAligned,If[saveImagesCCFitPoints&&savePlots,imagesCCshow,imagesCC]},
		{saveParameters,saveHistograms,savePlots,saveImagesCC},
		{adjustContrastMin,adjustContrastMax},
		"SaveNamePrefixSufix"->namePrefixSufix,
		"SaveNameParameters"->ToString@nameParameters,"SaveNameImagesCC"->ToString@nameImagesCC,"SaveNameHistograms"->ToString@nameHistograms,"SaveNameSpectra"->ToString@nameSpectra,"SaveNameAll"->ToString@nameAllTogether,
		"SaveImagesCCTogether"->saveImagesCCTogether,"SaveImagesCCIntensity"->saveImagesCCIntensity,"SaveImagesCCIntensityCrop"->saveImagesCCIntensityCrop,"SaveImagesRaw"->saveImagesRaw,"SaveImagesCCAlign"->saveImagesCCAlign,
		"SaveAllImagesTogether"->saveAllImagesTogether,"SaveShowFileName"->saveShowFileName,"SaveImageFiletype"->saveImageFiletype,"SaveImageResolution"->saveImageResolution
		];
	resultsSavedQ=True;
	, Method->"Queued",ImageSize->buttonSize,Enabled->fittedDataQ
],"Save selected information"]

}]

(******** Bookmarks *******)

,Delimiter

,Tooltip[Item[Style["Bookmarks",14]],"Import/export control settings (slider positions, checkbox states, etc.), \nwhich appear as \"Bookmarks\" in the top-right corner of the panel (click ⊕)"]

,Row[{

(********************)
(* Import bookmarks *)
(********************)

Tooltip[Button["Load a bookmark",
bookmarks=BookmarkImport[];
If[ToString@bookmarks≠"Null",AppendTo[Typeset`bookmarkList$$,ImportString[bookmarks,"Package"]]];
,Method->"Queued",ImageSize->buttonSize]
,"Improt a bookmark from a file"]

(********************)
(* Export bookmarks *)
(********************)

,Tooltip[Button["Save new bookmarks",
bookmarks=ToString[FullForm[Typeset`bookmarkList$$]];
BookmarksExport[bookmarks];
,Method->"Queued",ImageSize->buttonSize]
,"Export created bookmarks into a file"]
}]

(******************************************************************)

,ControlPlacement->Left,SynchronousUpdating->False,ContinuousAction->False,SaveDefinitions->False,
Initialization:>(
name="filename";
experimentData="experimentData";
plotSpectrum="spectra";
plotBleachRef="bleach reference";
imagesCC=imagesCCshow={{"color-coded images"}};
plotHistograms={{"histograms"}};
plotsFitSpectra="fitted spectra";
(*imageIntensity=ArrayPlot[ConstantArray[1,{512,512}],ColorFunction->GrayLevel,ColorFunctionScaling->False,ImageSize->400];*)
intensityData=ConstantArray[1,{512,512}];
intensityDataOriginal=ConstantArray[1,{512,512}];
adjustContrastMinOriginal=0;
adjustContrastMaxOriginal=1;
intensityHistogram="intensityHistogram";
imageIntensityCropAligned="";
importFolder=exportFolder="Recent Places";
parameterSymbols={x,y,i0,i1,p1,lm1,w1,a1,b1,i2,p2,lm2,w2,a2,b2,HemOxy,chi2};
hemRegionDensityThresh=0.24;
$parameterSymbolsForm={"x [pix]","y [pix]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"0\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"1\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"p\",\nFontSlant->\"Italic\"], \"1\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"λ\",\nFontSlant->\"Italic\"], 
 RowBox[{\"MAX\", \",\", \"1\"}]]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"w\",\nFontSlant->\"Italic\"], \"1\"]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"a\",\nFontSlant->\"Italic\"], \"1\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"b\",\nFontSlant->\"Italic\"], \"1\"]\) [(s^(-1))]","\!\(\*SubscriptBox[
 StyleBox[\"I\",\nFontSlant->\"Italic\"], \"2\"]\) [a.u.]","\!\(\*SubscriptBox[
 StyleBox[\"p\",\nFontSlant->\"Italic\"], \"2\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"λ\",\nFontSlant->\"Italic\"], 
 RowBox[{\"MAX\", \",\", \"2\"}]]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"w\",\nFontSlant->\"Italic\"], \"2\"]\) [nm]","\!\(\*SubscriptBox[
 StyleBox[\"a\",\nFontSlant->\"Italic\"], \"2\"]\) []","\!\(\*SubscriptBox[
 StyleBox[\"b\",\nFontSlant->\"Italic\"], \"2\"]\) [(s^(-1))]","\!\(\*
 StyleBox[\"HemOxy\",\nFontSlant->\"Italic\"]\) []","\!\(\*SuperscriptBox[
 StyleBox[\"χ\",\nFontSlant->\"Italic\"], \"2\"]\) [\!\(\*
StyleBox[\"N\",\nFontSlant->\"Italic\"]\) \!\(\*SuperscriptBox[
 StyleBox[\"σ\",\nFontSlant->\"Italic\"], \"2\"]\)]"};
nameParameters="fitParameters";
nameImagesCC="ccImages";
nameHistograms="parHistogram";
nameSpectra="spectra";
nameAllTogether="results";
imagesLoadedQ=False;
fittedDataQ=False;
resultsSavedQ=False;
batchStartQ=False;
parametersPoint={1,1,1,manualSetPortion1,manualSetLambdaMax1,manualSetWidth1,manualSetAsymmetry1,manualSetBleach1,1.-manualSetPortion1,manualSetLambdaMax2,manualSetWidth2,manualSetAsymmetry2,manualSetBleach2, manualSetOxygen};
(*import bookmarks from default directory*)
SetDirectory[FileNameJoin[{NotebookDirectory[],"bookmarks"}]];
bookmarks=FileNames["FMSfit-bookmark_"~~__~~".dat"];
bookmarks=BookmarkImport/@bookmarks;
bookmarks=ImportString[#,"Package"]&/@bookmarks;
Typeset`bookmarkList$$=bookmarks;
Clear[bookmarks];
ResetDirectory[];
)
]
]