//  Wellcome to the organoid macro
print("");waitForUser(" Welcome to the 'Macro PI vs H2B' Macro, made in the lab of Hugo Snippert \n \n It works on our data from our microscope (Leica SP8 confocal), run on our PCs with 64bits Fiji/ImageJ (1.49b)  \n \n for questions, please email h.j.g.snippert@umcutrecht.nl  or  b.ponsioen@umcurecht.nl");print("");














NumberOfWells = 60; 






ArrayWells	=newArray(NumberOfWells);
ArrayConditions	=newArray(NumberOfWells);
ArraySkip	=newArray(NumberOfWells);

for(Pos=1 ; Pos<NumberOfWells+1; Pos++){

		if(Pos==1){	ArrayWells[Pos-1] =  "A1";	ArrayConditions[Pos-1] = "drug 01";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==2){	ArrayWells[Pos-1] =  "A2";	ArrayConditions[Pos-1] = "drug 02";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==3){	ArrayWells[Pos-1] =  "A3";	ArrayConditions[Pos-1] = "drug 03";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==4){	ArrayWells[Pos-1] =  "A4";	ArrayConditions[Pos-1] = "drug 04";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==5){	ArrayWells[Pos-1] =  "A5";	ArrayConditions[Pos-1] = "drug 05";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==6){	ArrayWells[Pos-1] =  "A6";	ArrayConditions[Pos-1] = "drug 06";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==7){	ArrayWells[Pos-1] =  "A7";	ArrayConditions[Pos-1] = "drug 07";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==8){	ArrayWells[Pos-1] =  "A8";	ArrayConditions[Pos-1] = "drug 08";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==9){	ArrayWells[Pos-1] =  "A9";	ArrayConditions[Pos-1] = "drug 09";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==10){	ArrayWells[Pos-1] =  "A10";	ArrayConditions[Pos-1] = "drug 10";		ArraySkip[Pos-1] = 0 ;		}
		
		if(Pos==11){	ArrayWells[Pos-1] =  "B1";	ArrayConditions[Pos-1] = "drug 11";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==12){	ArrayWells[Pos-1] =  "B2";	ArrayConditions[Pos-1] = "drug 12";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==13){	ArrayWells[Pos-1] =  "B3";	ArrayConditions[Pos-1] = "drug 13";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==14){	ArrayWells[Pos-1] =  "B4";	ArrayConditions[Pos-1] = "drug 14";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==15){	ArrayWells[Pos-1] =  "B5";	ArrayConditions[Pos-1] = "drug 15";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==16){	ArrayWells[Pos-1] =  "B6";	ArrayConditions[Pos-1] = "drug 16";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==17){	ArrayWells[Pos-1] =  "B7";	ArrayConditions[Pos-1] = "drug 17";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==18){	ArrayWells[Pos-1] =  "B8";	ArrayConditions[Pos-1] = "drug 18";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==19){	ArrayWells[Pos-1] =  "B9";	ArrayConditions[Pos-1] = "drug 19";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==20){	ArrayWells[Pos-1] =  "B10";	ArrayConditions[Pos-1] = "drug 20";		ArraySkip[Pos-1] = 0 ;		}
		
		if(Pos==21){	ArrayWells[Pos-1] =  "C1";	ArrayConditions[Pos-1] = "drug 21";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==22){	ArrayWells[Pos-1] =  "C2";	ArrayConditions[Pos-1] = "drug 22";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==23){	ArrayWells[Pos-1] =  "C3";	ArrayConditions[Pos-1] = "drug 23";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==24){	ArrayWells[Pos-1] =  "C4";	ArrayConditions[Pos-1] = "drug 24";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==25){	ArrayWells[Pos-1] =  "C5";	ArrayConditions[Pos-1] = "drug 25";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==26){	ArrayWells[Pos-1] =  "C6";	ArrayConditions[Pos-1] = "drug 26";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==27){	ArrayWells[Pos-1] =  "C7";	ArrayConditions[Pos-1] = "drug 27";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==28){	ArrayWells[Pos-1] =  "C8";	ArrayConditions[Pos-1] = "drug 28";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==29){	ArrayWells[Pos-1] =  "C9";	ArrayConditions[Pos-1] = "drug 29";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==30){	ArrayWells[Pos-1] =  "C10";	ArrayConditions[Pos-1] = "drug 30";		ArraySkip[Pos-1] = 0 ;		}
		
		if(Pos==31){	ArrayWells[Pos-1] =  "C1";	ArrayConditions[Pos-1] = "drug 31";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==32){	ArrayWells[Pos-1] =  "C2";	ArrayConditions[Pos-1] = "drug 32";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==33){	ArrayWells[Pos-1] =  "C3";	ArrayConditions[Pos-1] = "drug 33";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==34){	ArrayWells[Pos-1] =  "C4";	ArrayConditions[Pos-1] = "drug 34";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==35){	ArrayWells[Pos-1] =  "C5";	ArrayConditions[Pos-1] = "drug 35";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==36){	ArrayWells[Pos-1] =  "C6";	ArrayConditions[Pos-1] = "drug 36";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==37){	ArrayWells[Pos-1] =  "C7";	ArrayConditions[Pos-1] = "drug 37";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==38){	ArrayWells[Pos-1] =  "C8";	ArrayConditions[Pos-1] = "drug 38";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==39){	ArrayWells[Pos-1] =  "C9";	ArrayConditions[Pos-1] = "drug 39";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==40){	ArrayWells[Pos-1] =  "C10";	ArrayConditions[Pos-1] = "drug 40";		ArraySkip[Pos-1] = 0 ;		}
		
		if(Pos==41){	ArrayWells[Pos-1] =  "E1";	ArrayConditions[Pos-1] = "drug 41";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==42){	ArrayWells[Pos-1] =  "E2";	ArrayConditions[Pos-1] = "drug 42";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==43){	ArrayWells[Pos-1] =  "E3";	ArrayConditions[Pos-1] = "drug 43";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==44){	ArrayWells[Pos-1] =  "E4";	ArrayConditions[Pos-1] = "drug 44";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==45){	ArrayWells[Pos-1] =  "E5";	ArrayConditions[Pos-1] = "drug 45";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==46){	ArrayWells[Pos-1] =  "E6";	ArrayConditions[Pos-1] = "drug 46";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==47){	ArrayWells[Pos-1] =  "E7";	ArrayConditions[Pos-1] = "drug 47";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==48){	ArrayWells[Pos-1] =  "E8";	ArrayConditions[Pos-1] = "drug 48";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==49){	ArrayWells[Pos-1] =  "E9";	ArrayConditions[Pos-1] = "drug 49";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==50){	ArrayWells[Pos-1] =  "E10";	ArrayConditions[Pos-1] = "drug 50";		ArraySkip[Pos-1] = 0 ;		}
		
		if(Pos==51){	ArrayWells[Pos-1] =  "F1";	ArrayConditions[Pos-1] = "drug 51";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==52){	ArrayWells[Pos-1] =  "F2";	ArrayConditions[Pos-1] = "drug 52";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==53){	ArrayWells[Pos-1] =  "F3";	ArrayConditions[Pos-1] = "drug 53";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==54){	ArrayWells[Pos-1] =  "F4";	ArrayConditions[Pos-1] = "drug 54";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==55){	ArrayWells[Pos-1] =  "F5";	ArrayConditions[Pos-1] = "drug 55";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==56){	ArrayWells[Pos-1] =  "F6";	ArrayConditions[Pos-1] = "drug 56";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==57){	ArrayWells[Pos-1] =  "F7";	ArrayConditions[Pos-1] = "drug 57";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==58){	ArrayWells[Pos-1] =  "F8";	ArrayConditions[Pos-1] = "drug 58";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==59){	ArrayWells[Pos-1] =  "F9";	ArrayConditions[Pos-1] = "drug 59";		ArraySkip[Pos-1] = 0 ;		}
		if(Pos==60){	ArrayWells[Pos-1] =  "F10";	ArrayConditions[Pos-1] = "drug 60";		ArraySkip[Pos-1] = 0 ;		}
}


StringForInterface="";  for(Pos=1 ; Pos<NumberOfWells+1; Pos++){StringForInterface = StringForInterface + "Well : "+ArrayWells[Pos-1] + "  --  Condition : "+ArrayConditions[Pos-1] + "    --  Skip it? "+ArraySkip[Pos-1] +" \n" ;}
print("");waitForUser("now here follows the list of Wells versus Conditions \n \n \n TO ADAPT : \n \n  type the Wells and the Conditions in the (top of the) macro script   \n \n  and note the Number of Wells (NumberOfWells = xx) ");print("");

print("");waitForUser(StringForInterface);print("");














print("");waitForUser("This is how it starts : \n \n    FIRST run : set all settings for all positions / conditions / wells ; these are stored on the D-drive  \n \n    SECOND run : no more setting the settings required, macro takes its time to run all positions");print("");

Dialog.create(" ");  Dialog.addRadioButtonGroup("", newArray("Set settings", "Run"),2, 1, "Set settings");    Dialog.show();  	
SettingsOrRun = Dialog.getRadioButton();	
if(SettingsOrRun=="Set settings"){	SetSettings=1;	RunAnalysis=0;}
if(SettingsOrRun=="Run"){		SetSettings=0;	RunAnalysis=1;}

	
OpenString 	= "";
	OpenString	= "O:\\bponsioen\\DATA BP\\2016\\02\\12\\160212 384-plate Afa-Sel-Bcl 48hrs (ATP-screen tomorrow).lif";

ExperimentDate 		= "160101";
Pos 			= 1; 

BinFactor		= 2 ; 
ReduceSize		= 0.2;

nSteps 			= 280 ;

NoCropAfterOpening 	= 1;

Test			= 0 ;
NoTransmitted		= 0 ;
OmitTransmitted		= 1 ;
Huang			= 1 ;
GammaManually		= 0 ;
nTimesSmooth		= 4 ;
MovieFrameRate		= 3 ;
AllowReading		= 0 ;
SkipBrightnessAdapt 	= 1;
SetBatchModeOn		= 0 ;
Gauss 			= 0;

nTimesAnalyzed=0;

GreenThresholdNumberSTART	= 3;		
GreenThresholdNumberSTOP	= 6;		
  RedThresholdNumberSTART	= 4;		
  RedThresholdNumberSTOP	= 8;		













for(GTN=GreenThresholdNumberSTART  ;  GTN<GreenThresholdNumberSTOP  ;  GTN++){

for(RTN=RedThresholdNumberSTART  ;  RTN<RedThresholdNumberSTOP  ;  RTN++){







StartPos = 1;
EndPos = NumberOfWells ;

for(Pos=StartPos ; Pos<EndPos+1 ; Pos++){
		

	if(ArraySkip[Pos-1]==0){
	
	nTimesAnalyzed=nTimesAnalyzed+1;
		run("Close All");setTool("rectangle");
							//  first we have to know whether the required directories exist 
							Mac=0; FileSeparator = File.separator; if(FileSeparator=="/"){Dialog.create(" "); Dialog.addCheckbox("Running on a Mac ?", 1); Dialog.show(); Mac = Dialog.getCheckbox();}else{print("this is a PC");}
							FileSeparator = FileSeparator + FileSeparator;	
							
							DumpLocation		= "D:"+FileSeparator+"ANALYSIS DUMP"+FileSeparator;
							ResultDump		= "RESULTS PI versus H2B"+FileSeparator;
							ResultDump		= "RESULTS Neon & Propidium"+FileSeparator;
							SettingsDump		= "Settings"+FileSeparator;
							ZipDump			= "Zip"+FileSeparator;
							AviDump			= "Avi"+FileSeparator;
							TempDump		= "Temp"+FileSeparator;

							ImageJDirectory		= getDirectory("imagej");	
							
							if(File.exists(DumpLocation)){print("yep");}
							else {	print("DumpLocation not found"); 	
							
								// try to generate it (works if computer has D-drive)
								File.makeDirectory(DumpLocation);}			
								if(File.exists(DumpLocation)){NotManaged=0; print("yep, just generated the folder DumpLocation");print("DumpLocation exists ("+DumpLocation+")");}else{NotManaged=1; waitForUser("???");}
							
									// try to generate it via the file in the imageJ-directory (hopefully helps if computer has no D-drive)
									TextFileName = "For FRET macro, this file knows where ANALYSIS DUMP is located on this computer.txt";
									if(NotManaged  && File.exists(ImageJDirectory + TextFileName)){
										ForDumpLocation = File.openAsRawString(ImageJDirectory + TextFileName);		
											//  add slashes...
											ForDumpLocation = DoubleSeparator(ForDumpLocation);	
										DumpLocation = ForDumpLocation + "ANALYSIS DUMP"+FileSeparator;  
										File.makeDirectory(DumpLocation);
										if(File.exists(DumpLocation)){NotManagedAgain=0;  waitForUser("yep, just generated the folder DumpLocation  (2e instantie)");print("DumpLocation exists ("+DumpLocation+")");}else{NotManagedAgain=1;}
									}else{NotManagedAgain=1;}
							
								// so, if nothing has worked ....
								if(NotManaged && NotManagedAgain){waitForUser("OK, first we need to create folders on your computer so we can store analysis output and settings \n" + " \n " + "WHERE ??");  print("DumpLocation not found, because D-drive is not there, hence macro could't generate it ..."); 
									ForDumpLocation = getDirectory("Where shall we create folders for analysis data ??");	print("ForDumpLocation (initially) : "+ForDumpLocation);		
									// write in ImageJDirectory, for next time
									File.saveString(ForDumpLocation , ImageJDirectory + TextFileName);
									
										//  add slashes...
										ForDumpLocation = DoubleSeparator(ForDumpLocation);		
									DumpLocation = ForDumpLocation + "ANALYSIS DUMP"+FileSeparator;
									if(File.exists(DumpLocation)){ }
									else {	File.makeDirectory(DumpLocation);										
										File.makeDirectory(DumpLocation + ResultDump);						
									}  //vd else
								} // vd else
								
								// wherever is DUmpLocation, generate these two inside that location
								if(File.exists(DumpLocation + ResultDump)){		 print("yep");}	else {print("ResultDump not found"); 		File.makeDirectory(DumpLocation + ResultDump);}			print("ResultDump exists ("+ResultDump+")");
								if(File.exists(DumpLocation + ResultDump + ZipDump)){	 print("yep");}	else {print("Zip-ResultDump not found");	File.makeDirectory(DumpLocation + ResultDump + ZipDump);}	print("ZipDump exists ("+ResultDump + ZipDump+")");
								if(File.exists(DumpLocation + ResultDump + SettingsDump)){print("yep");}else {print("Settings-ResultDump not found");	File.makeDirectory(DumpLocation + ResultDump + SettingsDump);}	print("SettingsDump exists ("+ResultDump + SettingsDump+")");
								if(File.exists(DumpLocation + ResultDump + AviDump)){	 print("yep");}	else {print("Avi-ResultDump not found");	File.makeDirectory(DumpLocation + ResultDump + AviDump);}	print("AviDump exists ("+ResultDump + AviDump+")");
								if(File.exists(DumpLocation + ResultDump + TempDump)){	 print("yep");}	else {print("Temp-ResultDump not found");	File.makeDirectory(DumpLocation + ResultDump + TempDump);}	print("TempDump exists ("+ResultDump + TempDump+")");

	if(File.exists(DumpLocation + ResultDump + TempDump + "GreenThresholdNumber.txt")){	GreenThresholdNumber = File.openAsRawString( DumpLocation + ResultDump + TempDump + "GreenThresholdNumber.txt");	GreenThresholdNumber = parseFloat(GreenThresholdNumber);	}else{GreenThresholdNumber=3;}
	if(File.exists(DumpLocation + ResultDump + TempDump +   "RedThresholdNumber.txt")){	RedThresholdNumber   = File.openAsRawString( DumpLocation + ResultDump + TempDump + "RedThresholdNumber.txt"  );	RedThresholdNumber   = parseFloat(RedThresholdNumber  );	}else{RedThresholdNumber=3;}
	if(File.exists(DumpLocation + ResultDump + TempDump +   "FilledL.txt")){ }else{	File.saveString(240 , DumpLocation + ResultDump + TempDump + "FilledL.txt"); }

	///  OVERRULE !!!
	GreenThresholdNumber = GTN;
	  RedThresholdNumber = RTN;
	


if(nTimesAnalyzed==1){	

	Line1 = " BinFactor is useful when you're having trouble with memory capacity \n ";
	Line2 = "nTimesSmooth : number of times smoothing before thresholding \n ";
	Line3 = "MovieFrameRate : frame rate of output avi \n ";
	
	print("");waitForUser(Line1+Line2+Line3);print("");

	Dialog.create("");
	Dialog.addString("Date experiment:", ExperimentDate, 20);
  	Dialog.addMessage("******************************** ");
	Dialog.addCheckbox("Test finding the right threshold?", 0);
  	Dialog.addMessage("******************************** ");
  	Dialog.addMessage("GreenThresholdNumber ");
	Dialog.addNumber("from", GreenThresholdNumberSTART);
	Dialog.addNumber("to  ", GreenThresholdNumberSTOP-1);
  	Dialog.addMessage("RedThresholdNumber ");
	Dialog.addNumber("from", RedThresholdNumberSTART);
	Dialog.addNumber("to  ", RedThresholdNumberSTOP-1);
  	Dialog.addMessage(" ");

  	Dialog.addMessage("******************************** ");
	Dialog.addNumber("TransmChannel", 1);
	Dialog.addNumber("H2BChannel", 2);
	Dialog.addNumber("PIChannel", 3	);
	Dialog.setInsets(2, 80,0)  Dialog.addCheckbox("Transmitted Absent", NoTransmitted);
	
  	Dialog.addMessage(" ");
  	Dialog.addMessage("******************************** ");
	Dialog.addNumber("BinFactor", BinFactor);
	Dialog.addNumber("nTimesSmooth", nTimesSmooth);
	Dialog.addNumber("MovieFrameRate", MovieFrameRate);


   Dialog.show();

	ExperimentDate		= Dialog.getString();	

	TestThresholdFinding	= Dialog.getCheckbox();	
	
	GreenThresholdNumberSTART	= Dialog.getNumber();	
	GreenThresholdNumberSTOP	= Dialog.getNumber();	GreenThresholdNumberSTOP = GreenThresholdNumberSTOP+1;
	RedThresholdNumberSTART		= Dialog.getNumber();	
	RedThresholdNumberSTOP		= Dialog.getNumber();	RedThresholdNumberSTOP = RedThresholdNumberSTOP+1;

	TransmChannel	= Dialog.getNumber();		ChPrefixTransm 	= "C"+d2s(TransmChannel,0)+"-";
	H2BChannel	= Dialog.getNumber();		ChPrefixGreen 	= "C"+d2s(H2BChannel,0)+"-";
	PIChannel	= Dialog.getNumber();		ChPrefixRed 	= "C"+d2s(PIChannel,0)+"-";
	NoTransmitted	= Dialog.getCheckbox();	

	BinFactor	= Dialog.getNumber();	
	nTimesSmooth	= Dialog.getNumber();	
	MovieFrameRate	= Dialog.getNumber();	
}
	NakedCondition = ArrayConditions[Pos-1];  ArrayConditions[Pos-1] = "( "+ ArrayConditions[Pos-1]+" )";

	TempDumpPerCondition = DumpLocation + ResultDump + TempDump + ArrayConditions[Pos-1] + FileSeparator;
	File.makeDirectory(TempDumpPerCondition);





if(SetSettings){GreenThresholdNumberSTART=1;}
if(SetSettings){GreenThresholdNumberSTOP=2;}
if(SetSettings){  RedThresholdNumberSTART=1;}
if(SetSettings){  RedThresholdNumberSTOP=2;}















		///  opening 
		///  opening 
		///  opening 
		OpenStringBFI		= "open=["+OpenString+"] color_mode=Default view=Hyperstack stack_order=XYCZT series_"+Pos;
		OpenStringBFI_V		= "open=["+OpenString+"] color_mode=Default view=Hyperstack stack_order=XYCZT use_virtual_stack series_"+Pos;
		OpenStringBFI_Split_V	= "open=["+OpenString+"] color_mode=Default split_channels view=Hyperstack stack_order=XYCZT use_virtual_stack series_"+Pos;

		if(OpenString==""){	print("");waitForUser("OPEN VIRTUAL STACK");print("");	run("Bio-Formats Importer");		}
		else{		if(SetSettings){
					run("Bio-Formats Importer", OpenStringBFI_Split_V);
					for(jj=nImages;jj>0;jj--){
						if(jj==H2BChannel){run("Put Behind [tab]");}else{close();}
					}
					Green=getTitle();
					getDimensions(x, y, channels, slices, frames);		OriginalNumberOfSlices = slices ;
				}
				if(RunAnalysis){
					run("Bio-Formats Importer", OpenStringBFI);
				}
		}

		if(SetSettings){
			Temp=getTitle(); rename("ThrowAway");	
			run("Scale...", "x="+(1/BinFactor)+" y="+(1/BinFactor)+" z=1.0 interpolation=Bilinear average process create title=["+Temp+"]");
			getDimensions(x, y, channels, slices, frames);		OriginalNumberOfSlices = slices ;	
			Stack.setPosition(1, floor(0.5*slices), floor(0.5*frames)); 	run("Enhance Contrast", "saturated=0.35");	
			selectWindow("ThrowAway"); close();
		}

		if(RunAnalysis){
		// prepare
		Stack.setDisplayMode("composite");
		getDimensions(x, y, channels, slices, frames);		OriginalNumberOfSlices = slices ;							
		BitDepth = bitDepth();
		for(i=0;i<channels;i++){
			Stack.setPosition(i+1, floor(0.5*slices), floor(0.5*frames)); 	run("Enhance Contrast", "saturated=0.35");	
			if(i+1==H2BChannel){run("Green");}
			if(i+1==PIChannel ){run("Red");}
		}
		
		
		
		
		print(""); if(Test==0 && NoCropAfterOpening==0){ waitForUser("feel free to  CROP");}
		/// crop or not?
		Uncropped=getTitle();
		if(selectionType==-1){a=Uncropped;}else{run("Duplicate...", "title=["+Uncropped+"_CROP] duplicate"); a=getTitle();}
		
		b=a; 
		
		selectWindow(b); run("Split Channels");   																									
			Transm	= ChPrefixTransm + b;	if(NoTransmitted==0){	selectWindow(Transm); 	if(OmitTransmitted){close();}else{	rename("transm"); 	Transm = getTitle();		print("done transm");	}}
			Red   	= ChPrefixRed    + b;				selectWindow(Red); 	run("Red");				rename("red"); 		Red = getTitle();		print("done red");
			Green 	= ChPrefixGreen  + b;				selectWindow(Green); 	run("Green");				rename("green"); 	Green = getTitle();		print("done green");
		
			selectWindow(Green);	setLocation(1,1);	getLocationAndSize(xTemp,yTemp,TempWidth,TempHeight);
		
			run("Brightness/Contrast...");	selectWindow("B&C"); setLocation(xTemp+TempWidth+10 , 0.25*TempHeight);
			SliceOfHighestIntensity(Green);	setLocation(1,1);	selectWindow("B&C"); 	if(Test==0 && SkipBrightnessAdapt==0){print(""); waitForUser("adapt B&C  GREEN ??  \n \nwill also be applied on the separate channels"); print("");} 	getMinAndMax(MinCh1,MaxCh1);
			SliceOfHighestIntensity(Red); 	setLocation(1,1);	selectWindow("B&C"); 	if(Test==0 && SkipBrightnessAdapt==0){print(""); waitForUser("adapt B&C  RED   ??  \n \nwill also be applied on the separate channels"); print("");} 	getMinAndMax(MinCh2,MaxCh2);
		
		} // vd if(RunAnalysis){



	if(SetSettings){
		//  CROPinZ - here only indicate
		CropInZ=1;		
		if(CropInZ){
			selectWindow(Green); setLocation(1,1);
			setSlice(2); 		if(Test){setSlice(8);}	print(""); 	if(Test==0){waitForUser("Pos_"+Pos+" \n \n set  LOWEST   Z to be included");}	Lowest  = getSliceNumber();
			setSlice(slices); 	if(Test){setSlice(12);}	print(""); 	if(Test==0){waitForUser("Pos_"+Pos+" \n \n set  HIGHEST  Z to be included");}	Highest = getSliceNumber();	
		}else{	Lowest=1;	Highest=slices; }
		
		
		// background subtract - here only draw the ROI
		if(isOpen("ROI Manager")){selectWindow("ROI Manager"); run("Close"); run("ROI Manager..."); }	
		selectWindow(Green); run("Z Project...", "projection=[Max Intensity]"); rename("Z-Proj Green"); setLocation(1,1); run("Enhance Contrast", "saturated=0.35"); getMinAndMax(MinGreen,MaxGreen); setMinAndMax(MinGreen, 0.15*MaxGreen); 
			print(""); waitForUser("Pos_"+Pos+" \n \n this is the Z-projection of the Neon channel \n \n Mark area for background subtraction"); print("");
		roiManager("Add"); 
		getSelectionBounds(xROI,yROI,ROIwidth,ROIheight);
		selectWindow("Z-Proj Green"); close();

				//  SAVE AWAY ...
				File.saveString(Lowest  , DumpLocation + ResultDump + SettingsDump + "Lowest_Pos_" +Pos+".txt");
				File.saveString(Highest , DumpLocation + ResultDump + SettingsDump + "Highest_Pos_"+Pos+".txt");
				File.saveString(xROI  , DumpLocation + ResultDump + SettingsDump + "xROI_Pos_" +Pos+".txt");
				File.saveString(yROI  , DumpLocation + ResultDump + SettingsDump + "yROI_Pos_" +Pos+".txt");
				File.saveString(ROIwidth  , DumpLocation + ResultDump + SettingsDump + "ROIwidth_Pos_"  +Pos+".txt");
				File.saveString(ROIheight , DumpLocation + ResultDump + SettingsDump + "ROIheight_Pos_" +Pos+".txt");

		run("Close All");
		if(isOpen("ROI Manager")) 	{selectWindow("ROI Manager"); run("Close");}

	}  // vd if(SetSettings)












if(RunAnalysis){

	// READOUT 
	Lowest  	= File.openAsRawString(DumpLocation + ResultDump + SettingsDump + "Lowest_Pos_" +Pos+".txt");			Lowest = parseFloat(Lowest);
	Highest 	= File.openAsRawString(DumpLocation + ResultDump + SettingsDump + "Highest_Pos_" +Pos+".txt");			Highest = parseFloat(Highest);
	xROI 		= File.openAsRawString(DumpLocation + ResultDump + SettingsDump + "xROI_Pos_" +Pos+".txt");			xROI = parseFloat(xROI);
	yROI 		= File.openAsRawString(DumpLocation + ResultDump + SettingsDump + "yROI_Pos_" +Pos+".txt");			yROI = parseFloat(yROI);
	ROIwidth  	= File.openAsRawString(DumpLocation + ResultDump + SettingsDump + "ROIwidth_Pos_"  +Pos+".txt");		ROIwidth = parseFloat(ROIwidth);
	ROIheight 	= File.openAsRawString(DumpLocation + ResultDump + SettingsDump + "ROIheight_Pos_" +Pos+".txt");		ROIheight = parseFloat(ROIheight);
																								

/////////    now all time-consuming stuff
/////////    now all time-consuming stuff
/////////    now all time-consuming stuff

//  CROPinZ - here only indicate
	CropInZ=1;		
	if(CropInZ){
		if(Lowest>1  ||  Highest<slices){  
			CropZ(Green); 		
			CropZ(Red);	
			if(NoTransmitted==0 && OmitTransmitted==0){CropZ(Transm);}		
		}
	}
	getDimensions(x, y, channels, slices, frames);	


selectWindow(Green);	setMinAndMax(MinCh1,MaxCh1);
selectWindow(Red);	setMinAndMax(MinCh2,MaxCh2); 
run("Merge Channels...", "c1=["+Red+"] c2=["+Green+"] keep");   rename(a);  setLocation(1,1);	getLocationAndSize(xTemp,yTemp,TempWidth,TempHeight);						
		if(AllowReading){
			if(isOpen(Uncropped)){	selectWindow(Uncropped); setLocation(screenWidth,1);}
						selectWindow(a); 	setLocation(screenWidth,1);
						selectWindow(Red); 	setLocation(screenWidth,1);
						selectWindow(Green); 	setLocation(screenWidth,1);
		}

// Smooth / Gauss
selectWindow("Log"); setLocation(1,1);
print("going to smooth GREEN"); 	selectWindow(Green); 	for(i=0;i<nTimesSmooth;i++){run("Smooth", "stack");}		if(Gauss){run("Gaussian Blur...", "sigma=.6 stack");}		print("just smoothed GREEN"); 	

print("going to smooth RED"); 		selectWindow(Red); 	for(i=0;i<nTimesSmooth;i++){run("Smooth", "stack");}		if(Gauss){run("Gaussian Blur...", "sigma=.6 stack");}		print("just smoothed RED"); 	


//  rescale maximally 
Go=0;
Show=0;
Manipulate=0;

ScaleTimelapse(Green); 	if(Go){run("32-bit"); run("16-bit");}	if(Manipulate){setMinAndMax(0,4100);}		getMinAndMax(MinGreen,MaxGreen);	 if(Show){print("");waitForUser("Go"+Go+"___MinGreen__"+MinGreen+"___MaxGreen__"+MaxGreen);print("");}		
ScaleTimelapse(Red);	if(Go){run("32-bit"); run("16-bit");}							getMinAndMax(MinRed  ,MaxRed); 		 if(Show){print("");waitForUser("Go"+Go+"___MinRed__"+MinRed+"___MaxRed__"+MaxRed);print("");}		




// background subtract - here APPLY
	BackgroundSubtract(Green);
	BackgroundSubtract(Red);
	if(isOpen("ROI Manager")){selectWindow("ROI Manager"); run("Close");}
	


// make Binned Windows
GreenBinned="";RedBinned="";
if(BinFactor>1){
	DoBinning=1;
	selectWindow(Green);	run("Scale...", "x="+(1/BinFactor)+" y="+(1/BinFactor)+" z=1.0 interpolation=Bilinear average process create title=["+Green+"_Binned_("+BinFactor+")]");	GreenBinned = getTitle();	GreenToFindOptimum = GreenBinned;
	selectWindow(Red);	run("Scale...", "x="+(1/BinFactor)+" y="+(1/BinFactor)+" z=1.0 interpolation=Bilinear average process create title=["+Red  +"_Binned_("+BinFactor+")]");	RedBinned   = getTitle();	RedToFindOptimum   =   RedBinned;
}else{
	DoBinning=0;
	GreenToFindOptimum = Green;
	RedToFindOptimum   = Red  ;
}










// set threshold GREEN & RED
ArrayThresholdsGreenPlanes	= newArray(slices); 
ArrayThresholdsRedPlanes	= newArray(slices); 

if(BitDepth== 8){UpperThreshold = 255; }
if(BitDepth==12){UpperThreshold = 4096; }
if(BitDepth==16){UpperThreshold = 65536; }


	// INITIALIZE ... for the PopUp
	selectWindow(Green);
	WidthTemp = getWidth(); HeightTemp = getHeight(); 
	HorizontalZoom 	= 90 *((0.5*(screenWidth ))/WidthTemp );				print(HorizontalZoom);
	VerticalZoom   	= 100*((0.9*(screenHeight))/HeightTemp);				print(VerticalZoom);
	ZoomFactor	= minOf(HorizontalZoom, VerticalZoom); 					print(ZoomFactor); 	
	
	XLocationMin=10; YLocationMin=10; XLocationStep=0;YLocationMax=2; YLocationMin=1; YWindowFraction=0; 		

	// Position GREEN and RED
	Previous="";
			run("Threshold..."); resetThreshold(); 	selectWindow("Threshold"); 	setLocation(xTemp+2*TempWidth+20,yTemp+0.4*TempHeight); 
																						
																							
																							
																							
			PopUp(a, ZoomFactor,100); 			setSlice(floor(0.5*slices));	setLocation(1,1); getLocationAndSize(xTemp,yTemp,TempWidth,TempHeight); 	
	if(DoBinning){	PopUp(RedBinned  , ZoomFactor,100*BinFactor); 	setSlice(floor(0.5*slices));	setLocation(xTemp+TempWidth+10,1); 						
			PopUp(GreenBinned, ZoomFactor,100*BinFactor); 	setSlice(floor(0.5*slices));	setLocation(xTemp+TempWidth+10,1); 						
	}
			PopUp(Red, ZoomFactor,100); 			setSlice(floor(0.5*slices));	setLocation(xTemp+TempWidth+10,1); 						
			PopUp(Green, ZoomFactor,100); 			setSlice(floor(0.5*slices));	setLocation(xTemp+TempWidth+10,1); 						
																	

	


	//  let user make a choice for Green and Red  at the slice halfway --> 0.5*slices;	
	if(TestThresholdFinding){
		ThisSlice=1;	slice=getSliceNumber - 1; RememberSliceThresholdFinding = getSliceNumber;
 
		LowerThreshold = FindOptimum(GreenToFindOptimum, 3, 1);	
		selectWindow("TestStack"); rename("Green - TestStack");  	run("glow"); 	resetMinAndMax(); run("Enhance Contrast", "saturated=0.2");			// die 3 is voor spek en bonen, maar mag geen 0 zijn
		aa=getTitle; PopUp(aa, ZoomFactor,100); 	setLocation(xTemp+TempWidth+10,1);
		print(""); waitForUser("GREEN  -  halfway the stack to determine threshold \n \n choose desired Threshold"); print(""); 	GreenThresholdNumber = getSliceNumber();	close();
			// en welke surface levert dat op?
			selectWindow(Green); setSlice(floor(0.5*slices));
			LowerThresholdGreenAfterTesting = FindOptimum(GreenToFindOptimum,GreenThresholdNumber,0);
			selectWindow(Green); setThreshold(0,LowerThresholdGreenAfterTesting); 	run("Create Selection");	run("Make Inverse");  run("Add to Manager");	 nROIs = roiManager("count");    	
			resetThreshold(); run("Select None"); roiManager("Deselect"); roiManager("Select",nROIs-1); run("Measure");  AreaGreenAfterTesting = getResult("Area", nResults-1);
		
		LowerThreshold = FindOptimum(RedToFindOptimum, 3, 1);	
		selectWindow("TestStack"); rename("Red - TestStack"); 		run("glow"); 	resetMinAndMax(); run("Enhance Contrast", "saturated=0.1");
		aa=getTitle; PopUp(aa, ZoomFactor,100); 	setLocation(xTemp+TempWidth+10,1);
		print(""); waitForUser("RED    -  halfway the stack to determine threshold \n \n choose desired Threshold"); print(""); 	RedThresholdNumber   = getSliceNumber();	close();
		

		File.saveString(GreenThresholdNumber , DumpLocation + ResultDump + TempDump + "GreenThresholdNumber.txt");
		File.saveString(  RedThresholdNumber , DumpLocation + ResultDump + TempDump + "RedThresholdNumber.txt");
	}


	// automated  GREEN
	for(slice=0; slice<slices; slice++){														//	print(""); waitForUser("GreenThresholdNumber "+GreenThresholdNumber); print("");
		ThisSlice=slice+1;
		Continue=1;
		while(Continue){
			Redo=0;
			selectWindow(a);			setSlice(slice+1);
			selectWindow(GreenToFindOptimum);	setSlice(slice+1);	
			run("Enhance Contrast", "saturated=0.45");	
			LowerThreshold = FindOptimum(GreenToFindOptimum,GreenThresholdNumber,0);
			aa=getSliceNumber(); if(aa!=slice+1){print(""); waitForUser("YOU CHANGED THE SLICE !!! \n \n  DO AGAIN "); print(""); Redo=1; }
			if(Redo==0){
				Continue=0; 
				ArrayThresholdsGreenPlanes[slice]=LowerThreshold;
				Previous = LowerThreshold;
			}
		}
	}
	run("Select None");	print("ArrayThresholdsGreenPlanes"); Array.print(ArrayThresholdsGreenPlanes);	Remember= ArrayThresholdsGreenPlanes[0]; 																		// waitForUser("ArrayThresholdsGreenPlanes[0]___"+ArrayThresholdsGreenPlanes[0]);
	if(isOpen(GreenBinned)){selectWindow(GreenBinned); close();}
	run("Collect Garbage");	print("");


	// automated  RED
	selectWindow(Red); run("Threshold..."); resetThreshold();  Previous="";
	for(slice=0; slice<slices; slice++){																			//	print(""); waitForUser("RedThresholdNumber "+RedThresholdNumber); print("");
		ThisSlice=slice+1;
		Continue=1;
		while(Continue){
			Redo=0;
			selectWindow(a);			setSlice(slice+1);		getMinAndMax(minTemp,maxTemp); setMinAndMax(minTemp,0.6*maxTemp); 
			selectWindow(RedToFindOptimum);		setSlice(slice+1);
			run("Enhance Contrast", "saturated=0.45");	
			LowerThreshold = FindOptimum(RedToFindOptimum,RedThresholdNumber,0);
			aa=getSliceNumber(); if(aa!=slice+1){print(""); waitForUser("YOU CHANGED THE SLICE !!! \n \n  DO AGAIN "); print(""); Redo=1; }
			if(Redo==0){
				Continue=0; 
				ArrayThresholdsRedPlanes[slice]=LowerThreshold;
				Previous = LowerThreshold;
			}
		}
	}
	selectWindow(Red);  run("Select None"); run("Red"); 		print("ArrayThresholdsRedPlanes"); Array.print(ArrayThresholdsRedPlanes);
	if(isOpen(RedBinned)){selectWindow(RedBinned); close();}
	run("Collect Garbage");	print("");
















//  UITLEZEN  !!!
//  UITLEZEN  !!!
ArrayAreaGreenPlanes	= newArray(slices); 
ArrayAreaRedPlanes	= newArray(slices); 
ArrayRatioPerPlane	= newArray(slices); 

	// GREEN
	nROIs = roiManager("count");
	selectWindow(Green); run("Set Measurements...", "area limit redirect=None decimal=1");
	for(i=0;i<slices;i++){
		run("Threshold..."); resetThreshold(); 
		setSlice(1 + i); setThreshold(ArrayThresholdsGreenPlanes[i],UpperThreshold);												
		run("Create Selection"); run("Measure"); roiManager("Add"); roiManager("Deselect"); roiManager("Select",nROIs+i); roiManager("Rename", "ROI Green Z_"+Lowest+i); 
		ArrayAreaGreenPlanes[i] = getResult("Area", nResults-1);
	}
	SummedGreenArea = 0 ;	for(i=0;i<slices;i++){SummedGreenArea = SummedGreenArea + ArrayAreaGreenPlanes[i];}															print("ArrayAreaGreenPlanes"); Array.print(ArrayAreaGreenPlanes); print("SummedGreenArea "+SummedGreenArea); print(" ");
	run("Collect Garbage");	print("");

	// RED
	nROIs = roiManager("count");
	selectWindow(Red); run("Set Measurements...", "area limit redirect=None decimal=1");
	for(i=0;i<slices;i++){
		run("Threshold..."); resetThreshold(); 
		setSlice(1 + i); setThreshold(ArrayThresholdsRedPlanes[i],UpperThreshold);
		run("Create Selection"); run("Measure"); roiManager("Add"); roiManager("Deselect"); roiManager("Select",nROIs+i);roiManager("Rename", "ROI Red Z_"+Lowest+i); 
		ArrayAreaRedPlanes[i] = getResult("Area", nResults-1);
	}
	SummedRedArea = 0 ;	for(i=0;i<slices;i++){SummedRedArea = SummedRedArea + ArrayAreaRedPlanes[i];}																print("ArrayAreaRedPlanes"); Array.print(ArrayAreaRedPlanes); print("SummedRedArea "+SummedRedArea); print(" "); 
	run("Collect Garbage");	print("");

	Ratio = SummedRedArea / SummedGreenArea ;													
	nPlanes = slices;

	for(i=0;i<slices;i++){	ArrayRatioPerPlane[i] = ArrayAreaRedPlanes[i] / ArrayAreaGreenPlanes[i] ; }
	StringRatioPerPlane=""; Comma=", ";
	for(i=0;i<slices;i++){	if(i==slices-1){Comma="";} StringRatioPerPlane = StringRatioPerPlane + d2s(ArrayRatioPerPlane[i],3) + Comma; }


	// and view the GREEN & RED
	ViewBC=0;
	nROIs = roiManager("count");
	selectWindow("B&C"); setLocation(xTemp+2*TempWidth+10 , 0.25*TempHeight);
	selectWindow(Green); 	setSlice(floor(0.5*slices)); run("Select None"); run("Enhance Contrast", "saturated=0.35");  if(ViewBC){print(""); waitForUser("GREEN \n \nalter B&C for output avi ??"); } getMinAndMax(MinGreenOutput,MaxGreenOutput);
	selectWindow(Red); 	setSlice(floor(0.5*slices)); run("Select None"); run("Enhance Contrast", "saturated=0.35");  if(ViewBC){print(""); waitForUser("RED   \n \nalter B&C for output avi ??"); } getMinAndMax(MinRedOutput  ,MaxRedOutput  );

	
	DrawRim(Green, nROIs-2*slices);
	DrawRim(Red  , nROIs-1*slices);
	run("Combine...", "stack1="+Green+" stack2="+Red);	getMinAndMax(MinGlow,MaxGlow); setMinAndMax(MinGlow, 0.5*MaxGlow);
	rename("For Checking"); Check=getTitle();
		// draw a line
		run("Colors...", "foreground=white");
		xS=floor(getWidth/2);
		Width = getWidth/400;
		makeRectangle(  xS-0.5*Width , 0, Width , getHeight);	
		run("Set...", "value="+UpperThreshold+" stack"); run("Select None");










//  SAVE STUFF 
//  SAVE STUFF 
	Separator = ";";
	SaveName =  "Neon&PI_" + ExperimentDate +"_"+ ArrayWells[Pos-1] +"_" + ArrayConditions[Pos-1] ;     
	roiManager("Save", DumpLocation + ResultDump + ZipDump + SaveName + ".zip");

	// read from file (previous Analyses)
	folder = DumpLocation + ResultDump + TempDump;
	drs = getFileList(folder);
	CountOpened=0;
	ArraySavedPrintStrings = newArray(1010);

	for (ii=0; ii<drs.length; ii++){											
		for (j=0; j<drs.length; j++) {
		     dr = drs[j];
		     SameDate=0; if(indexOf(dr,ExperimentDate)!=-1){SameDate=1;}						
		     if (endsWith(dr,".txt")  &&  startsWith(dr,"PrintString_"+ii+1+"_")  && SameDate==1){
		 		ThisPrintString = File.openAsRawString(folder + dr);									
				ArraySavedPrintStrings[CountOpened] = ThisPrintString;
		   		CountOpened = CountOpened + 1;
		   		j=drs.length;
		     }
		}
	}
	// add a white line??
	
	// current combi of GreenThresholdNumber  &  GreenThresholdNumber?
	CurrentStringLastThresholdNumbers = "GTN"+d2s(GreenThresholdNumber,0) + "_RTN"+d2s(RedThresholdNumber,0)+"_";
	WhiteLine=0;
	FileExistsYes=0;
	if(File.exists(DumpLocation + ResultDump + TempDump + "PreviousStringLastThresholdNumbers.txt")){ 
		FileExistsYes=1;
		PreviousStringLastThresholdNumbers = File.openAsRawString( DumpLocation + ResultDump + TempDump + "PreviousStringLastThresholdNumbers.txt");
		if(CurrentStringLastThresholdNumbers != PreviousStringLastThresholdNumbers){WhiteLine=1;}
	}
	// now save current as previous, for the next round
	File.saveString(CurrentStringLastThresholdNumbers, DumpLocation + ResultDump + TempDump + "PreviousStringLastThresholdNumbers.txt");
	//
	ArraySavedPrintStrings 	= Array.trim(ArraySavedPrintStrings,  CountOpened);										



// now, in between jobs ; must be done here becuase 'CountOpened' must be determined, and first we want to save as avi and only then watch it
						// SAVE Avi (Combined Frame)
						selectWindow(Check); 	setLocation(1,1);
							SaveNameAvi =  "Drawn_Thresholds_Analysis #" + CountOpened+1 + "_" + ExperimentDate +"_"+ ArrayWells[Pos-1]+"_" + ArrayConditions[Pos-1] ;	
							MovieFrameRate = 3;
							selectWindow(Check);	run("AVI... ", "compression=JPEG frame="+MovieFrameRate+" save=["+DumpLocation + ResultDump + AviDump + SaveNameAvi+".avi]");
									
						CheckAtEnd=1;		
						if(CheckAtEnd){
							selectWindow(Check); setLocation(1,1); run("Animation Options...", "speed="+MovieFrameRate); doCommand("Start Animation [\\]");
						}
				
						Remark = "";
// now, in between jobs ; must be done here becuase 'CountOpened' must be determined, and first we want to save as avi and only then watch it











	ArrayHeader1String 	= newArray(1010); 	
	ArrayHeader2String 	= newArray(1010); 	
	ArrayForPrintString  	= newArray(1010);
	PrintStringArray 	= newArray(1010);
	
		//   first 6 lines  (line 7 will be Header)
		PrintStringArray[0] = ExperimentDate;
		PrintStringArray[1] = "";
		PrintStringArray[2] = "";

		i=0;
		aa = 0 ;
				if(i==0){ArrayHeader1String[aa]="  ";			ArrayHeader2String[aa]=" ";}		ArrayForPrintString[aa] = "";	
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]=" Date";		ArrayHeader2String[aa]=" ";}		ArrayForPrintString[aa] = ExperimentDate;	
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="Well";			ArrayHeader2String[aa]=" ";}		ArrayForPrintString[aa] = ArrayWells[Pos-1] ;
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="Condition";		ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = NakedCondition;
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="";			ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = "" ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="Green";	     ArrayHeader2String[aa]="ThresholdNumber";}	ArrayForPrintString[aa] = GreenThresholdNumber ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="Red";		     ArrayHeader2String[aa]="ThresholdNumber";}	ArrayForPrintString[aa] = RedThresholdNumber ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="";			ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = "" ;		

	
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="nPlanes";		ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = toString(nPlanes);	
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="SummedGreenArea";	ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = toString(SummedGreenArea);			
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="SummedRedArea";	ArrayHeader2String[aa]=" ";}		ArrayForPrintString[aa] = toString(SummedRedArea);			
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="Ratio R/G";		ArrayHeader2String[aa]=" ";}		ArrayForPrintString[aa] = toString(Ratio);		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="";			ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = "" ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="Lowest plane";		ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = Lowest ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="Highest plane";	ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = Highest ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="";			ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = "" ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="REMARK";		ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = Remark ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="";			ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = "" ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="";			ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = "" ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="";			ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = "" ;		


		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="";			ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = "" ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="GREEN_Thr";		ArrayHeader2String[aa]=" ";}		ArrayForPrintString[aa] = "  G Thr" ;		
		for(slice=0;slice<OriginalNumberOfSlices;slice++){
		    if(slice+1<Lowest || slice+1>Highest){Fill=" - "+slice+1+" - ";}else{Fill=d2s(ArrayThresholdsGreenPlanes[slice+1-Lowest],3);}							
		    aa=aa+1;	if(i==0){ArrayHeader1String[aa]="Plane_"+slice;		ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = Fill;		
		}
		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="";			ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = "" ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="GREEN";		ArrayHeader2String[aa]=" ";}		ArrayForPrintString[aa] = "    G " ;		
		for(slice=0;slice<OriginalNumberOfSlices;slice++){
		    if(slice+1<Lowest || slice+1>Highest){Fill=" - "+slice+1+" - ";}else{Fill=d2s(ArrayAreaGreenPlanes[slice+1-Lowest],3);}						
		    aa=aa+1;	if(i==0){ArrayHeader1String[aa]="Plane_"+slice;		ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = Fill;		
		}
		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="";			ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = "" ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="RED_Thr";		ArrayHeader2String[aa]=" ";}		ArrayForPrintString[aa] = "  R Thr" ;		
		for(slice=0;slice<OriginalNumberOfSlices;slice++){
		    if(slice+1<Lowest || slice+1>Highest){Fill=" - "+slice+1+" - ";}else{Fill=d2s(ArrayThresholdsRedPlanes[slice+1-Lowest],3);}						
		    aa=aa+1;	if(i==0){ArrayHeader1String[aa]="Plane_"+slice;		ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = Fill;		
		}
		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="";			ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = "     xx" ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="RED";			ArrayHeader2String[aa]=" ";}		ArrayForPrintString[aa] = "    R" ;		
		for(slice=0;slice<OriginalNumberOfSlices;slice++){
		    if(slice+1<Lowest || slice+1>Highest){Fill=" - "+slice+1+" - ";}else{Fill=d2s(ArrayAreaRedPlanes[slice+1-Lowest],3);}						
		    aa=aa+1;	if(i==0){ArrayHeader1String[aa]="Plane_"+slice;		ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = Fill;		
		}
		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="";			ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = "     xx" ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="RATIOs";		ArrayHeader2String[aa]="RATIOs";}	ArrayForPrintString[aa] = "    RATIO" ;		
		for(slice=0;slice<OriginalNumberOfSlices;slice++){
		    if(slice+1<Lowest || slice+1>Highest){Fill=" - "+slice+1+" - ";}else{Fill=d2s(ArrayRatioPerPlane[slice+1-Lowest],3);}						
		    aa=aa+1;	if(i==0){ArrayHeader1String[aa]="Plane_"+slice;		ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = Fill;		
		}
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="";			ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = "" ;		
		aa=aa+1;	if(i==0){ArrayHeader1String[aa]="";			ArrayHeader2String[aa]="";}		ArrayForPrintString[aa] = "" ;		



	
		NumberOfParameters = aa+1;	
		ArrayHeader1String 	= Array.trim(ArrayHeader1String,  NumberOfParameters);											print("ArrayHeader1String"); Array.print(ArrayHeader1String);
		ArrayHeader2String 	= Array.trim(ArrayHeader2String,  NumberOfParameters); 											print("ArrayHeader2String"); Array.print(ArrayHeader2String);	
		ArrayForPrintString  	= Array.trim(ArrayForPrintString, NumberOfParameters); 											print("ArrayForPrintString"); Array.print(ArrayForPrintString);		
	
			// build the HeaderStrings (HeaderString1 & HeaderString2) and put in the PrintStringArray
					HeaderString1 = " ";															
					for (j=1 ; j<NumberOfParameters ; j++){HeaderString1 = HeaderString1 + Separator + ArrayHeader1String[j];}				
					PrintStringArray[3] = HeaderString1;
					HeaderString2 = "";
					for (j=1 ; j<NumberOfParameters ; j++){HeaderString2 = HeaderString2 + Separator + ArrayHeader2String[j];}
					PrintStringArray[4] = HeaderString2;
			
			nUpperLines = 5;
			
			// build the PrintString BASED  ON SAVED PRINTSTRINGS !!
			for(k=0;k<CountOpened;k++){	PrintStringArray[5+k]	= ArraySavedPrintStrings[k]; }
					
			// build the PrintString and put in the PrintStringArray
			PosForNewestPrintString = 5  + CountOpened;															
				// but first, was there a white line??
				if(WhiteLine){
					PrintStringArray[PosForNewestPrintString] = " x "+Separator+" "+Separator+" "+Separator+" "+Separator; 
					PosForNewestPrintString=PosForNewestPrintString+1;
				}
			PrintString = "";																	
			for (j=1 ; j<NumberOfParameters ; j++){PrintString = PrintString + Separator + ArrayForPrintString[j];}						
			PrintStringArray[PosForNewestPrintString] = PrintString;
			if(Pos==EndPos){PrintStringArray[PosForNewestPrintString+1] = " x "; }

//V47
Analysis_Output = PrintStringArray;
Array.show(Analysis_Output); selectWindow("Analysis_Output"); setLocation(1,1);
IJ.renameResults(SaveName);
	// problems with overwriting?
	ContinueChangingFileName = 1;
	while(ContinueChangingFileName){
		ContinueChangingFileName = 0 ;
		XlsAlreadySavedWithThisName 	= File.exists(DumpLocation + ResultDump + SaveName+".xls");
		if(XlsAlreadySavedWithThisName){
			SaveName = SaveName + "_"; 
			ContinueChangingFileName = 1 ;
		}
	}

// SAVE xls
saveAs("Results", DumpLocation + ResultDump + "Analysis #"+CountOpened+1+"_" + SaveName+".xls");
saveAs("Results", TempDumpPerCondition      + "Analysis #"+CountOpened+1+"_" + SaveName+".xls");		
run("Close");

// SAVE txt
//  every time : asve this particular PrintString 
File.saveString(PrintString, DumpLocation + ResultDump + TempDump + "PrintString_"+CountOpened+1+"__"+ExperimentDate +"_" + ArrayWells[Pos-1] +"_" + ArrayConditions[Pos-1]+".txt");

	
// and round up
print(" "); print(" ");print("that was well  "+ArrayWells[Pos-1]);print("that was condition   "+NakedCondition); print("SummedGreenArea "+SummedGreenArea); print("SummedRedArea "+SummedRedArea); print("Ratio "+Ratio); 
selectWindow(a);  setLocation(0.7*screenWidth,0.5*screenHeight);

		if(isOpen(a)){selectWindow(a); 	close();}
		if(isOpen(b)){selectWindow(b); 	close();}
		selectWindow(Check); 	close();

if(CheckAtEnd==0){beep();}


} // vd if(RunAnalysis)

} // vd if(Skip==0)

}  // vd for(Pos=StartPos ; Pos<EndPos+1 ; Pos++)



}  // vd  for(RTN=RedThresholdNumberSTART  ;  RTN<RedThresholdNumberSTOP  ;  RTN++){

}  // vd  for(GTN=GreenThresholdNumberSTART  ;  GTN<GreenThresholdNumberSTOP  ;  GTN++){


	Line0  = "EXIT  !!  \n \n \n \n \n \n";
	Line1  = "Data are written away in xls format (the numbers) and in avi format (so you can see how the thresholds worked out in the two channels)  \n \n";
	Line1b = "Find them in  -->    D/ANALYSIS DUMP/Results PI versus H2B   ; avi's are in the avi-subfolder \n \n";

	
	Line2 = "For opening in Excel, you should know the following : \n";
	Line3 = "        output values are Semicolon-delimited  \n";
	Line4 = "        decimal separator is a dot (.) \n";
	Line5 = "        there's NO thousands separator \n \n";
	Line6 = "Every new xls-output file also contains previous analysis results, so you don't need to open them one by one, but ALL are listed in the last saved xls \n";

	Line7 = "      most important : experiment date, well, condition and the signal for the 2 channels and their Ratio ";
	Line8 = "      please note that results come in 'blocks', one block for each set of thresholding parameters for green and/or red ";
	Line9 = "  ";
	Line10 = "  ";
	
	print(""); waitForUser(Line0 +Line1 + Line1b + Line2 + Line3 + Line4 + Line5 + Line6 + Line7 + Line8 + Line9 + Line10 ); print("");


exit("done");





















///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
function CropZ(Title){
  	selectWindow(Title);
	if(Highest<slices){	run("Slice Remover", "first="+Highest+1+" last="+slices+" increment=1");	}
	if(Lowest>1){		run("Slice Remover", "first=1 last="+Lowest-1+" increment=1");			}
}



function BackgroundSubtract (Title){
	run("Set Measurements...", "  mean standard redirect=None decimal=6");
	selectWindow(Title);	
	for(i=0;i<slices;i++){
		setSlice(1+i);
		makeRectangle(xROI,yROI,ROIwidth,ROIheight);
		run("Measure");	Mean = getResult("Mean", nResults-1);   		
		run("Select None");
		run("Subtract...", "value="+Mean+" slice");
	}
	run("Select None");
}



function ScaleTimelapse(Title){
	
		if(isOpen("Results")) 	{selectWindow("Results"); run("Close");}
		selectWindow(Title); 
		run("Statistics");	max = getResult("Max", nResults-1);   		// THIS IS THE ONLY WAY i CAN SIMPLY GET THE MAX OF THE WHOLE STACK!!
											// getStatistics only does the active slice   //  also problematic  via run("Histogram", "stack")  &  Plot.getValues(ArrayX, ArrayY);
		selectWindow(Title); 	setMinAndMax (0, max+1);
		if(isOpen("Results")) 	{selectWindow("Results"); run("Close");}
}  // vd function ScaleTimelapse


//V97
function PopUp(Title, OriginalZoom, Percentage){
	setBatchMode(true);
	selectWindow(Title); setLocation(1,1); 
		ZoomFactor = (Percentage/100)*OriginalZoom;
	Zooms = newArray(16.7, 25,33.3, 50,75,100,150,200,300,400,600,800);  i=0;  while(ZoomFactor>Zooms[i]){i=i+1;}	
	Z="";nTimes=0;
	if(Zooms[i]<100){Z="Out [-]"; nTimes = 5-i;}
	if(Zooms[i]>100){Z="In [+]";  nTimes = i-5;}
	setBatchMode(false);
	SetAtZoom(Title);
	setLocation((XLocationMin + 0.5*XLocationStep) , (YLocationMin + YWindowFraction*(YLocationMax-YLocationMin))); 
}

function SetAtZoom(Title){
	wait(101);
	selectWindow(Title); 	run("Select None");	setLocation(1,1); 	run("View 100%");
	setBatchMode(true);
		for(j=0;j<nTimes;j++){run(Z);}	
		run("Set... ", "zoom="+ZoomFactor);
	setBatchMode(false);
}


function DrawRim(Title, FirstROI){
	
	ConvertToRGB=1;
	
	nROIsTemp = roiManager("count");
	selectWindow(Title); resetThreshold(); run("Select None");
		if(ConvertToRGB){
			selectWindow(Title);	if(Title==Green){ setMinAndMax(MinGreenOutput,MaxGreenOutput);	print(""); 	run("Colors...", "foreground=magenta");}
						if(Title==Red  ){ setMinAndMax(MinRedOutput,  MaxRedOutput  );	print(""); 	run("Colors...", "foreground=yellow");}
			run("RGB Color", "slices"); 
		}

	setBatchMode(true);

	for(i=0;i<slices;i++){
		setSlice(i+1);
		roiManager("Deselect"); roiManager("Select",FirstROI+i); run("Enlarge...", "enlarge=1 pixel"); roiManager("Add");
		ArrayForXOR=newArray(2);  ArrayForXOR[0]=FirstROI+i; ArrayForXOR[1]=nROIsTemp; 
		roiManager("Select", ArrayForXOR); roiManager("XOR"); 
			if(ConvertToRGB==0){run("Set...", "value="+UpperThreshold+" slice");}				
			if(ConvertToRGB==1){run("Draw", "slice");}
		roiManager("Deselect");  roiManager("Select", nROIs);  roiManager("Delete");
	}
	setSlice(1);

	setBatchMode(false);
}




function SliceOfHighestIntensity(Title){
	
	ArrayIntensities=newArray(slices);
	run("Set Measurements...", "  mean standard redirect=None decimal=6");
	selectWindow(Title); run("Plot Z-axis Profile"); zz=getTitle(); selectWindow(zz); close;
	for(i=0;i<slices;i++){ArrayIntensities[i] = getResult("Mean", (nResults-slices+i));}									
	Array.getStatistics(ArrayIntensities, min, max, mean, stdDev); 			HighestIntensity = max ;	

	rankPosArray = Array.rankPositions(ArrayIntensities);		/* rank numbers, from small to large */								print(" ");print("ArrayIntensities");	Array.print(ArrayIntensities); 		print("rankPosArray = Array.rankPositions(ArrayIntensities)");  Array.print(rankPosArray);
	rankPosArray = Array.reverse(rankPosArray);			/* rank numbers, from small to large */							
	selectWindow(Title);  setSlice(rankPosArray[0]);
	run("Enhance Contrast", "saturated=0.35");														

}





function FindOptimum(Title, ThresholdNumber, GenerateTestWindow){	

	
	if(Title==RedToFindOptimum  ){	RescaleTheStep=0.25;  }
	if(Title==GreenToFindOptimum){	RescaleTheStep=0.25;  }
	
	WAF_normal  = 3 ;
	WAF_1st_deriv = 5 ;
	WAF_2nd_deriv = 5 ;
	
	Test1 = 0;																				
	Test2 = 0;



	resetMinAndMax();
	getMinAndMax(dummy,Max); print("");  		
																							print("FUNCTION "+Title+"!!!!");	print("FUNCTION "+Title+"!!!!");	print("FUNCTION "+Title+"!!!!");	print("FUNCTION "+Title+"!!!! GenerateTestWindow___"+GenerateTestWindow+"______slice "+slice+Lowest+"__Max__"+Max);

	UpperTestedThresholdFraction = 0.15 ;		UTTF = UpperTestedThresholdFraction;  
	// so, test UNTIL a threshold that is set at 5% of max-value in that image
	
	MinThreshold = 0;
	MaxThreshold = UpperTestedThresholdFraction*Max;
	run("Set Measurements...", "area mean limit redirect=None decimal=0");

	setBatchMode(false);
	if(SetBatchModeOn){	setBatchMode(true); 	run("Duplicate...", "title=[BatchModeSlice]");	}
	
	ArrayTestThresholds 		= newArray(nSteps);
	ArrayAreaPerTestThreshold 	= newArray(nSteps);
	ArrayMeanPerTestThreshold 	= newArray(nSteps);

	// trick for location Results-window
	run("Select All"); run("Measure"); run("Select None"); 	selectWindow("Results"); setLocation(0.97*screenWidth,0.6*screenHeight);
	
	for(i=0;i<nSteps;i++){
		TestThreshold = MinThreshold + (i/nSteps)*(MaxThreshold-MinThreshold);	ArrayTestThresholds[i]=TestThreshold;
		setThreshold(TestThreshold , UpperThreshold); run("Create Selection"); run("Measure");		 
			ArrayAreaPerTestThreshold[i] = getResult("Area", nResults-1);
			ArrayMeanPerTestThreshold[i] = getResult("Mean", nResults-1);
																									bb=25; if(Test2 && floor(i/bb) == i/bb  && i<0.2*nSteps){print(""); waitForUser("kijk    i:"+i+"________TestThreshold "+TestThreshold);print("");}		
	}

	// make 1st derivative
	ArrayAreaFirstDerivative = newArray(nSteps-1);
	ArrayMeanFirstDerivative = newArray(nSteps-1);
	for(i=0;i<nSteps-1;i++){
		ArrayAreaFirstDerivative[i] = ArrayAreaPerTestThreshold[i+1] - ArrayAreaPerTestThreshold[i] ;
		ArrayMeanFirstDerivative[i] = ArrayMeanPerTestThreshold[i+1] - ArrayMeanPerTestThreshold[i] ;
	}
	
	// get rid of jumps
	// first search the zeros
	ArraySubstitutions = newArray(2*(nSteps-1));
	nZeros=0;
	nSubst=0;
	for(i=0;i<nSteps-1;i++){
		if(i==0){PreviousValue=101;}else{PreviousValue = ArrayAreaFirstDerivative[i-1]; }
		if(ArrayAreaFirstDerivative[i]==0  &&  PreviousValue!=0){	ArraySubstitutions[2*nSubst] = i ;		nZeros=1;	}
		if(ArrayAreaFirstDerivative[i]==0  &&  PreviousValue==0){	nZeros=nZeros+1;						}
		if(ArrayAreaFirstDerivative[i]!=0  &&  PreviousValue==0){	ArraySubstitutions[2*nSubst+1] = nZeros ;   nSubst=nSubst+1;	}
	}

	ArraySubstitutions = Array.trim(ArraySubstitutions, 2*nSubst);
		print("nSubst"+nSubst);
		print("ArrayAreaPerTestThreshold");Array.print(ArrayAreaPerTestThreshold);
		print("ArrayAreaFirstDerivative");Array.print(ArrayAreaFirstDerivative);
		print("ArraySubstitutions");Array.print(ArraySubstitutions);					if(Test2){ waitForUser("ArraySubstitutions OK?");}
	
	//  now correct the plateaus
	for(S=0; S<nSubst; S++){
		PosFirstZero	= ArraySubstitutions[2*S];
		nZeros		= ArraySubstitutions[2*S+1];
		if(PosFirstZero==0){Exc=1; /*waitForUser("Exc=1");*/}else{Exc=0;}
										
		TempOld = Array.copy(ArrayAreaPerTestThreshold);
		Temp1 = Array.copy(ArrayAreaPerTestThreshold);			
		Temp2 = Array.copy(ArrayMeanPerTestThreshold);

		for(z=Exc; z<nZeros; z++){
																						ervoor=Temp1[PosFirstZero-1+Exc];	erna=Temp1[PosFirstZero+nZeros];
			Temp1[PosFirstZero+z] = Temp1[PosFirstZero+z] + ((nZeros-z-Exc)/(nZeros+1-Exc))*(Temp1[PosFirstZero-1+Exc] - Temp1[PosFirstZero+nZeros]);
			Temp2[PosFirstZero+z] = Temp2[PosFirstZero+z] + ((nZeros-z-Exc)/(nZeros+1-Exc))*(Temp2[PosFirstZero-1+Exc] - Temp2[PosFirstZero+nZeros]);
																						uitkomst=Temp1[PosFirstZero+z];		if(Test1 && S<1){print("");print("");print("");print("");print("");waitForUser("___S__"+S+"___z__"+z+"___Exc__"+Exc+"_\n \n __PosFirstZero__"+PosFirstZero+"___nZeros__"+nZeros+"_\n \n __DE BREUK  (nZeros-z-Exc)/(nZeros+1-Exc)__"+(nZeros-z-Exc)/(nZeros+1-Exc)+"___\n \n _PosFirstZero-1+Exc_"+PosFirstZero-1+Exc+"___\n \n _PosFirstZero+nZeros_"+PosFirstZero+nZeros+"___\n \n UITKOMST  _"+uitkomst+"___\n \n _namelijk ervoor_"+ervoor+" en erna :"+erna); print("");}
		}
		ArrayAreaPerTestThreshold = Array.copy(Temp1);
		ArrayMeanPerTestThreshold = Array.copy(Temp2);
	}
	
	// Walking AVG 
	//  normal arrays
	WAF = WAF_normal;
	Temp=newArray(nSteps-WAF+1);
	for(i=0;i<nSteps-WAF+1;i++){	Sum=0; for(j=0;j<WAF;j++){Sum=Sum+ArrayAreaPerTestThreshold[i+j];}		Temp[i]=(1/WAF)*Sum;	}		ArrayAreaPerTestThreshold = Array.copy(Temp);
	for(i=0;i<nSteps-WAF+1;i++){	Sum=0; for(j=0;j<WAF;j++){Sum=Sum+ArrayMeanPerTestThreshold[i+j];}		Temp[i]=(1/WAF)*Sum;	}		ArrayMeanPerTestThreshold = Array.copy(Temp);

																				if(nSubst>0){print("ArrayAreaPerTestThreshold old");Array.print(TempOld);}
																				if(nSubst>0){print("ArrayAreaPerTestThreshold corrected");Array.print(ArrayAreaPerTestThreshold);print("");}
	//  1st DER.
	//  1st DER.
	// again de FIRST DERIVATIVE , now that from the CORRECTED array
	L=ArrayAreaPerTestThreshold.length;
	ArrayAreaFirstDerivative = newArray(L-1);
	ArrayMeanFirstDerivative = newArray(L-1);
	for(i=0;i<L-1;i++){
		ArrayAreaFirstDerivative[i] = ArrayAreaPerTestThreshold[i+1] - ArrayAreaPerTestThreshold[i] ;
		ArrayMeanFirstDerivative[i] = ArrayMeanPerTestThreshold[i+1] - ArrayMeanPerTestThreshold[i] ;
	}
	// Walking AVG
	// arrays 1st derivative
	WAF = WAF_1st_deriv;
	L=ArrayAreaFirstDerivative.length;	Temp=newArray(L-WAF+1);
	for(i=0;i<L-WAF+1;i++){	Sum=0; for(j=0;j<WAF;j++){Sum=Sum+ArrayAreaFirstDerivative[i+j];}		Temp[i]=(1/WAF)*Sum;	}			ArrayAreaFirstDerivative = Array.copy(Temp);
	for(i=0;i<L-WAF+1;i++){	Sum=0; for(j=0;j<WAF;j++){Sum=Sum+ArrayMeanFirstDerivative[i+j];}		Temp[i]=(1/WAF)*Sum;	}			ArrayMeanFirstDerivative = Array.copy(Temp);



	//  2nd DER.
	//  2nd DER.
	//   SECOND DERIVATIVE 
	ArrayAreaSecondDerivative = newArray(ArrayAreaFirstDerivative.length-1);
	ArrayMeanSecondDerivative = newArray(ArrayMeanFirstDerivative.length-1);
	for(i=0 ; i<ArrayAreaFirstDerivative.length-1 ; i++){
		if(Test2 &&  i>nSteps-5){print("");waitForUser("_ArrayAreaFirstDerivative.length__"+ArrayAreaFirstDerivative.length+"__nSteps-3__"+nSteps-3+"____i+1_"+i+1);print("");}
		ArrayAreaSecondDerivative[i] = ArrayAreaFirstDerivative[i+1] - ArrayAreaFirstDerivative[i] ;		
		ArrayMeanSecondDerivative[i] = ArrayMeanFirstDerivative[i+1] - ArrayMeanFirstDerivative[i] ;
	}																			print("ArrayMeanSecondDerivative");Array.print(ArrayMeanSecondDerivative);
		// Sliding AVG 2nd derivative
		WAF = WAF_2nd_deriv;
		L=ArrayAreaSecondDerivative.length;	Temp=newArray(L-WAF+1);
		for(i=0;i<L-WAF+1;i++){	Sum=0; for(j=0;j<WAF;j++){Sum=Sum+ArrayAreaSecondDerivative[i+j];}		Temp[i]=(1/WAF)*Sum;	}		ArrayAreaSecondDerivative = Array.copy(Temp);
		for(i=0;i<L-WAF+1;i++){	Sum=0; for(j=0;j<WAF;j++){Sum=Sum+ArrayMeanSecondDerivative[i+j];}		Temp[i]=(1/WAF)*Sum;	}		ArrayMeanSecondDerivative = Array.copy(Temp);


		// NORMALIZE AREA
		// NORMALIZE AREA
		// new way of normalizing : based on 2nd derivative of the AREA
		SearchFraction = 0.01;
		SearchValue = SearchFraction * ArrayAreaSecondDerivative[0];
		Continue=1; i=1; StartPlateauSecondDerivative=0; 
		while(Continue){
			if(ArrayAreaSecondDerivative[i] < SearchValue){	StartPlateauSecondDerivative=i; Continue=0; print("StartPlateauSecondDerivative "+StartPlateauSecondDerivative); if(Test2<0){waitForUser("StartPlateauSecondDerivative "+i);}}	
			i=i+1;
		}
		NormalizationFactorForAreaTrace = ArrayAreaPerTestThreshold[StartPlateauSecondDerivative];	
		NFA = NormalizationFactorForAreaTrace;															

		// NORMALIZE MEAN
		// NORMALIZE MEAN
		// also a normalization-factor for the MEAN-trace ;;;  we pick the highest value at the end of the array ; HEAVILY DETERMINED BY UPPER TESTING VALUE  
									//   (( 	// dus testen TOT een threshold die is gesteld op 5% van max-value in plaatje  ))
		L=ArrayMeanPerTestThreshold.length;
		Array.getStatistics(ArrayMeanPerTestThreshold, min, max, mean, stdDev);	
		NormalizationFactorForMeanTrace = max;															

		NFM = NormalizationFactorForMeanTrace;







	
	// combine AREA-info and MEAN-info

	// first NORMALIZE the AREA- and MEAN-trace
	L=ArrayAreaPerTestThreshold.length;
	ArrayAreaNormalized 		= newArray(L);
	ArrayMeanNormalized 		= newArray(L);
	ArraySumNormalizedAreaAndMean 	= newArray(L);
	for(i=0; i<L; i++){	ArrayAreaNormalized[i] = 100 * ArrayAreaPerTestThreshold[i] / NormalizationFactorForAreaTrace ;	}
	for(i=0; i<L; i++){	ArrayMeanNormalized[i] = 100 * ArrayMeanPerTestThreshold[i] / NormalizationFactorForMeanTrace ;	}
	//  then add them up , so we can find a minimum later
	for(i=0; i<L; i++){	ArraySumNormalizedAreaAndMean[i] = ArrayAreaNormalized[i] + ArrayMeanNormalized[i] ;		}

	MinOfSummedGraph=-101;
	Array.getStatistics(ArraySumNormalizedAreaAndMean, min, max, mean, stdDev);	
	for(i=0; i<L; i++){	if(ArraySumNormalizedAreaAndMean[i] == min){	MinOfSummedGraph=i;  if(Test2){print("");waitForUser("aan het zoeken i___"+i);}	}}								

	if(MinOfSummedGraph==-101){Array.print(ArrayAreaNormalized);Array.print(ArrayMeanNormalized);Array.print(ArraySumNormalizedAreaAndMean); print("");waitForUser("heeft min niet herkend (op slice "+slice+1+") :       min = "+min+"_________[L-3]_"+ArraySumNormalizedAreaAndMean[L-3]+"_________[L-2]_"+ArraySumNormalizedAreaAndMean[L-1]+"_________[L-1]_"+ArraySumNormalizedAreaAndMean[L-1]);}

	if(MinOfSummedGraph == L-1){print("");waitForUser("WARNING !!!      Min is gewoon et laatste punt, dus de curve had geen minimum ....");}
	
	Step = RescaleTheStep*(MinOfSummedGraph - StartPlateauSecondDerivative);

	StepLowerThreshold_1 = StartPlateauSecondDerivative + 1*Step;
	StepLowerThreshold_2 = StartPlateauSecondDerivative + 2*Step;
	StepLowerThreshold_3 = StartPlateauSecondDerivative + 3*Step;
	StepLowerThreshold_4 = StartPlateauSecondDerivative + 4*Step;
	StepLowerThreshold_5 = StartPlateauSecondDerivative + 5*Step;
	StepLowerThreshold_6 = StartPlateauSecondDerivative + 6*Step;
	StepLowerThreshold_7 = StartPlateauSecondDerivative + 7*Step;
	StepLowerThreshold_8 = StartPlateauSecondDerivative + 8*Step;
	StepLowerThreshold_9 = StartPlateauSecondDerivative + 9*Step;
																														
																														
	if(StepLowerThreshold_1 < ArrayTestThresholds.length){	LowerThreshold_1 = ArrayTestThresholds[StepLowerThreshold_1];	if(ThresholdNumber>=1){LowerThreshold = LowerThreshold_1; LowerThresholdNumberPicked=1;	print("LowerThreshold = LowerThreshold_1");	 }	}else{LowerThreshold_1=0; print("NOT  met criterium : StepLowerThreshold_1 < ArrayTestThresholds.length"); }
	if(StepLowerThreshold_2 < ArrayTestThresholds.length){	LowerThreshold_2 = ArrayTestThresholds[StepLowerThreshold_2];	if(ThresholdNumber>=2){LowerThreshold = LowerThreshold_2; LowerThresholdNumberPicked=2;	print("LowerThreshold = LowerThreshold_2");	 }	}else{LowerThreshold_2=0; print("NOT  met criterium : StepLowerThreshold_2 < ArrayTestThresholds.length"); }
	if(StepLowerThreshold_3 < ArrayTestThresholds.length){	LowerThreshold_3 = ArrayTestThresholds[StepLowerThreshold_3];	if(ThresholdNumber>=3){LowerThreshold = LowerThreshold_3; LowerThresholdNumberPicked=3;	print("LowerThreshold = LowerThreshold_3");	 }	}else{LowerThreshold_3=0; print("NOT  met criterium : StepLowerThreshold_3 < ArrayTestThresholds.length"); }
	if(StepLowerThreshold_4 < ArrayTestThresholds.length){	LowerThreshold_4 = ArrayTestThresholds[StepLowerThreshold_4];	if(ThresholdNumber>=4){LowerThreshold = LowerThreshold_4; LowerThresholdNumberPicked=4;	print("LowerThreshold = LowerThreshold_4");	 }	}else{LowerThreshold_4=0; print("NOT  met criterium : StepLowerThreshold_4 < ArrayTestThresholds.length"); }
	if(StepLowerThreshold_5 < ArrayTestThresholds.length){	LowerThreshold_5 = ArrayTestThresholds[StepLowerThreshold_5];	if(ThresholdNumber>=5){LowerThreshold = LowerThreshold_5; LowerThresholdNumberPicked=5;	print("LowerThreshold = LowerThreshold_5");	 }	}else{LowerThreshold_5=0; print("NOT  met criterium : StepLowerThreshold_5 < ArrayTestThresholds.length"); }
	if(StepLowerThreshold_6 < ArrayTestThresholds.length){	LowerThreshold_6 = ArrayTestThresholds[StepLowerThreshold_6];	if(ThresholdNumber>=6){LowerThreshold = LowerThreshold_6; LowerThresholdNumberPicked=6;	print("LowerThreshold = LowerThreshold_6");	 }	}else{LowerThreshold_6=0; print("NOT  met criterium : StepLowerThreshold_6 < ArrayTestThresholds.length"); }
	if(StepLowerThreshold_7 < ArrayTestThresholds.length){	LowerThreshold_7 = ArrayTestThresholds[StepLowerThreshold_7];	if(ThresholdNumber>=7){LowerThreshold = LowerThreshold_7; LowerThresholdNumberPicked=7;	print("LowerThreshold = LowerThreshold_7");	 }	}else{LowerThreshold_7=0; print("NOT  met criterium : StepLowerThreshold_7 < ArrayTestThresholds.length"); }
	if(StepLowerThreshold_8 < ArrayTestThresholds.length){	LowerThreshold_8 = ArrayTestThresholds[StepLowerThreshold_8];	if(ThresholdNumber>=8){LowerThreshold = LowerThreshold_8; LowerThresholdNumberPicked=8;	print("LowerThreshold = LowerThreshold_8");	 }	}else{LowerThreshold_8=0; print("NOT  met criterium : StepLowerThreshold_8 < ArrayTestThresholds.length"); }
	if(StepLowerThreshold_9 < ArrayTestThresholds.length){	LowerThreshold_9 = ArrayTestThresholds[StepLowerThreshold_9];	if(ThresholdNumber>=9){LowerThreshold = LowerThreshold_9; LowerThresholdNumberPicked=9;	print("LowerThreshold = LowerThreshold_9");	 }	}else{LowerThreshold_9=0; print("NOT  met criterium : StepLowerThreshold_9 < ArrayTestThresholds.length"); }

																															
	

	// Concatenate 9 arrays  (for outputting to EXCEL)
	nArrays=0;
	A1 = Array.copy(ArrayAreaPerTestThreshold);		L1=A1.length;			nArrays=nArrays+1;
	A2 = Array.copy(ArrayMeanPerTestThreshold);		L2=A2.length;			nArrays=nArrays+1;	L=minOf(L1,L2);
	A3 = Array.copy(ArrayAreaFirstDerivative);		L3=A3.length;			nArrays=nArrays+1;	L=minOf(L ,L3);
	A4 = Array.copy(ArrayMeanFirstDerivative);		L4=A4.length;			nArrays=nArrays+1;	L=minOf(L ,L4);
	A5 = Array.copy(ArrayAreaSecondDerivative);		L5=A5.length;			nArrays=nArrays+1;	L=minOf(L ,L5);
	A6 = Array.copy(ArrayMeanSecondDerivative);		L6=A6.length;			nArrays=nArrays+1;	L=minOf(L ,L6);
	A7 = Array.copy(ArrayAreaNormalized);			L7=A7.length;			nArrays=nArrays+1;	L=minOf(L ,L7);
	A8 = Array.copy(ArrayMeanNormalized);			L8=A8.length;			nArrays=nArrays+1;	L=minOf(L ,L8);
	A9 = Array.copy(ArraySumNormalizedAreaAndMean);		L9=A9.length;			nArrays=nArrays+1;	L=minOf(L ,L9);		

	if(ThisSlice==1 && Title==GreenToFindOptimum && GenerateTestWindow){
		L = getNumber("how many data points you want save away into xls? here's the Array-length (now "+L+")" , 240);  
		FilledL=L;
		File.saveString(FilledL , DumpLocation + ResultDump + TempDump + "FilledL.txt");
	}else{	L = File.openAsRawString( DumpLocation + ResultDump + TempDump + "FilledL.txt");	L = parseFloat(L);}																	// print("");waitForUser("slice = "+slice+1+"___L__"+L);print("");

	
	A1 = Array.trim(A1,L);
	A2 = Array.trim(A2,L);
	A3 = Array.trim(A3,L);
	A4 = Array.trim(A4,L);
	A5 = Array.trim(A5,L);
	A6 = Array.trim(A6,L);
	A7 = Array.trim(A7,L);
	A8 = Array.trim(A8,L);
	A9 = Array.trim(A9,L);

	ArrayForSaving = Array.concat(A1,A2,A3,A4,A5,A6,A7,A8,A9);

	SaveName =  "Neon&PI_" + ExperimentDate +"_"+ ArrayWells[Pos-1]+"_" + ArrayConditions[Pos-1] ;															print("ArrayAreaPerTestThreshold"); Array.print(ArrayAreaPerTestThreshold); 	
	if(Title==GreenToFindOptimum){Color="GREEN";}
	if(Title==RedToFindOptimum  ){Color="__RED";}
	ParameterString = Title+"__SLICE_"+slice+Lowest+"____BinFactor "+BinFactor+"___Max "+Max+"____ThresholdNumber "+ThresholdNumber+"______StartPlateauSecondDerivative "+StartPlateauSecondDerivative+"______Step  = "+Step+"_______LowerThresholdNumberPicked "+LowerThresholdNumberPicked+"________THE EVENTUAL LOWER THRESHOLD___"+LowerThreshold+"_____WAF_normal__"+WAF_normal+"______WAF_1st_deriv_"+WAF_1st_deriv+"______WAF_2nd_deriv_"+WAF_2nd_deriv;

	File.saveString(ParameterString , TempDumpPerCondition + "ParameterString_of_"+Color+"_PLANE_#"+ThisSlice-1+Lowest+"_( "+SaveName+" ).txt");
	ArrayForSaving2 = Array.concat(ParameterString,ArrayForSaving);
	
	Array.show(ArrayForSaving2); 	selectWindow("ArrayForSaving2"); 	saveAs("Results", TempDumpPerCondition + "Test_thresholds_in_"+Color+"_PLANE_#"+ThisSlice-1+Lowest+"_( "+SaveName+" )_("+nArrays+"x"+L+" data points) (+ParameterString).xls");	run("Close");	
	
	if(isOpen("BatchModeSlice")){selectWindow("BatchModeSlice"); close();}
	setBatchMode(false);

	selectWindow(Title); run("Select None");
	
	print("test : LowerThreshold "+LowerThreshold);

	
					if(GenerateTestWindow){	

						TheArray = newArray(LowerThreshold_1,LowerThreshold_2,LowerThreshold_3,LowerThreshold_4,LowerThreshold_5,LowerThreshold_6,LowerThreshold_7,LowerThreshold_8,LowerThreshold_9);			print(Title);print("TheArray"); Array.print(TheArray); print("");
						ArrayRatios=newArray(TheArray.length);  
						run("Set Measurements...", "area limit redirect=None decimal=1");
						run("ROI Manager...");
						
						if(Title==GreenToFindOptimum){BigWindow=Green;}
						if(Title==RedToFindOptimum  ){BigWindow=Red;  }
						setBatchMode(false);
						for(i=0;i<TheArray.length;i++){
							if(TheArray[i]>0){
								selectWindow(BigWindow);	setSlice(floor(0.5*slices));    	aaa=getSliceNumber; if(i==0 && aaa!=RememberSliceThresholdFinding){print("");waitForUser("PROBLEM with sliceNumber !! aaa = "+aaa+"_________RememberSliceThresholdFinding__"+RememberSliceThresholdFinding);print("");}  if(i==0 && aaa==RememberSliceThresholdFinding){print("");waitForUser("sliceNumber OK, ie same as RememberSliceThresholdFinding \n \n aaa = "+aaa+"_________RememberSliceThresholdFinding__"+RememberSliceThresholdFinding);print("");}
								run("Duplicate...", "title=["+BigWindow+"_Temp_"+i+1+"]");
								if(BigWindow==Red){
								setThreshold(0,TheArray[i]); 	run("Create Selection");	run("Make Inverse");  run("Add to Manager");	 nROIs = roiManager("count");   
								resetThreshold(); run("Select None"); roiManager("Deselect"); roiManager("Select",nROIs-1);    run("Measure"); 
								AreaRed = getResult("Area", nResults-1); 	ArrayRatios[i] = AreaRed / AreaGreenAfterTesting ;	
								}
								setThreshold(0,TheArray[i]); 	run("Create Selection"); 	run("Set...", "value=NaN slice");
						
								if(BigWindow==Red){
									Font = getHeight/30; run("Colors...", "foreground=white");
									Text = "Ratio R/G = " + d2s(ArrayRatios[i],3); yWrite = 10 + getStringWidth(Text);
									run("Label...", "format=Text x="+10+" y="+yWrite+" font="+Font+" text=["+Text+"]");		
								} 
	
							}		else{waitForUser("1 overgeslagen : "+i+1); print("");}
						} // vd for(i=0;i<TheArray.length;i++)
						run("Images to Stack", "name=[TestStack] title=["+BigWindow+"_Temp_] use");	
						setBatchMode(false);
					}
	
	return LowerThreshold;
	
} // vd function

