//  Wellcome to the organoid macro
print("");waitForUser("Welcome to the Macro for Drug & Release Analysis, made in the lab of Hugo 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("");









// default fills in the dialog ;; you could change them here
DateTemp 	= "160902";
OrganoidTemp 	= "p18T";
DrugTemp 	= "Sel+Afa";


























// ARRAYS
ArraySurfaceH2B		= newArray(1000);
ArraySurfaceH2B_Alive	= newArray(1000);
ArraySurfaceH2B_Dead	= newArray(1000);
ArraySliceNumbers	= newArray(1000);
ArrayMeanNucleusArea	= newArray(10);

ArrayTimePoints 	= newArray(5);
ArrayTimePointsTemp	= newArray(5);

	ArrayTimePointsTemp[0]="prior to drugs";
	ArrayTimePointsTemp[1]="after 72 hrs drugs";
	ArrayTimePointsTemp[2]="72 hr after drug release";
	ArrayTimePointsTemp[3]="7 days after drug release";

	nTimePoints = ArrayTimePointsTemp.length;

//  PARAMETERS (some may be obsolete...)
Reload=0; 
ReUseROIs=0;
SaveBackups=0;	

SkipLineDrawing=0;
SetStandardRectangless=0;
HuangThresholding=1;


testImageCalculator=0; 		if(testImageCalculator){waitForUser("testImageCalculator is at 1 !!!");}
setOption("BlackBackground", true);

min			= 0;
FractionForFontSize	= 20;
Separator		= "; ";
nTimePoints		= 3 ;	
TranssectionStep	= 3 ;	
testFunctionSaveRawData	= 0 ;
HideWindows		= 0;
MeanArea 		= 63;
FractionDeadParticle	= 0.7;
DrawLiving		= 0;
MarginToDuckBehind	= 55;
ShownPlanesAbove	=2;
test=0;	test2=0;test22=0;test3=0;testImageCalculator=0; ManipulateValues=0; // obsolete stuff
	
FixedDump 		= "D:\\ANALYSIS DUMP\\";				
OutputDump		= "D:\\ANALYSIS DUMP\\RESULTS Drug & Release\\";		

// herstel
nTimePoints = ArrayTimePointsTemp.length;

DoPrepare();

// DIALOG	

		Line1 = "In the upcoming dialog ... \n \n";
		Line2 = "      Transsection every x slices : it would be too much work to analyze ALL slices, so we pick representative slices every x planes \n \n";
		Line3 = "      Fraction Dead Particle : for initial automated recognition of dead particles";
		Line4 = "";
	print("");waitForUser(Line1+Line2+Line3+Line4);print("");
	
	Dialog.create(" ");
	Dialog.addString("Date Experiment", DateTemp , 40);
	Dialog.addString("Tumor Organoid", OrganoidTemp , 40);
	Dialog.addString("Condition (drug)", DrugTemp , 40);
	Dialog.addMessage(" ");
	Dialog.addString("Time Point 1", ArrayTimePointsTemp[0] , 40);
	Dialog.addString("Time Point 2", ArrayTimePointsTemp[1] , 38);
	Dialog.addString("Time Point 3", ArrayTimePointsTemp[2] , 36);
	Dialog.addString("Time Point 4", ArrayTimePointsTemp[3] , 34);
	Dialog.addString("Time Point 5", "" , 32);
	Dialog.addMessage(" ");
	Dialog.addNumber("analyze transsection every ", TranssectionStep , 0 , 5 , "z-planes");
	Dialog.addNumber("Fraction Dead Particle ", FractionDeadParticle , 2 , 5 , "relative to living nucleus");
		Dialog.show();
	Date  = Dialog.getString;		
	Tumor = Dialog.getString;		
	Drug  = Dialog.getString;		

	Defined=0; 
	if(nTimePoints>=1){	TP1 = Dialog.getString;			ArrayTimePoints[0]=TP1;		if(TP1=="" && Defined==0){	nTimePoints=0;	Defined=1; } 	}
	if(nTimePoints>=2){	TP2 = Dialog.getString;			ArrayTimePoints[1]=TP2;		if(TP2=="" && Defined==0){	nTimePoints=1;	Defined=1; }	}
	if(nTimePoints>=3){	TP3 = Dialog.getString;			ArrayTimePoints[2]=TP3;		if(TP3=="" && Defined==0){	nTimePoints=2;	Defined=1; }	}
	if(nTimePoints>=4){	TP4 = Dialog.getString;			ArrayTimePoints[3]=TP4;		if(TP4=="" && Defined==0){	nTimePoints=3;	Defined=1; }		}	
	if(nTimePoints>=5){	TP5 = Dialog.getString;			ArrayTimePoints[4]=TP5;		if(TP5=="" && Defined==0){	nTimePoints=4;	Defined=1; }else{nTimePoints=5;}	}			

	ArrayTimePoints   = Array.trim(ArrayTimePoints,   nTimePoints); 	print("ArrayTimePoints"); Array.print(ArrayTimePoints);
	TranssectionStep = Dialog.getNumber;					OriginalTranssectionStep=TranssectionStep;
	FractionDeadParticle = Dialog.getNumber;

	LastTimePointForROIs=1;
	GammaManually=1;
	GaussManually=1;



// OPEN ALL TIME POINTS
ArrayTransm	= newArray(nTimePoints);
ArrayH2B	= newArray(nTimePoints);

for(i=0;i<nTimePoints;i++){
	if(i==0  &&  SaveBackups){waitForUser("OK, for backupping .... \n \n show folder "); BackupLocation = getDirectory("OK, for backupping ....  show folder ");	}

	if(test2==0 && test22==0   &&  Reload==0  ){ waitForUser(" Open Tiled Scan of ____ "+Tumor+" ___ "+Drug+" ___ "+ArrayTimePoints[i]+"  \n \n Open in virtual mode, and split channels    \n \n (macro assumes 2 channels : 1) H2B-fluo 2) transmitted light "); open();}
	rename(Drug+"_"+ArrayTimePoints[i]+"_TRANSM");	Transm=getTitle();		
			if(SaveBackups){saveAs("Tiff", BackupLocation+Transm+".tif");	rename(Transm);}
			run("Put Behind [tab]");
	rename(Drug+"_"+ArrayTimePoints[i]+"_H2B");	H2B=getTitle();
			if(SaveBackups){saveAs("Tiff", BackupLocation+H2B+".tif");	rename(H2B);}
	run("Brightness/Contrast...");	 run("ROI Manager...");																				print("a_"+i);
	selectWindow(Transm);	getDimensions(x, y, channels, slices, frames);		Stack.setPosition(1, floor(slices/2) , 1);	run("Enhance Contrast", "saturated=0.35");
	selectWindow(H2B);	getDimensions(x, y, channels, slices, frames);		Stack.setPosition(1, floor(slices/2) , 1);	run("Enhance Contrast", "saturated=0.35");					print("b_"+i);
	
	ArrayTransm[i]=Transm;	
	ArrayH2B[i]=H2B;
}

run("Tile");
waitForUser("Where shall we create folders for analysis data ??"); DumpLocation = getDirectory("Where shall we create folders for analysis data ??");




if(ReUseROIs==0){
	// SHOW ROI ALL TIMEPOINTS
	// SHOW ROI ALL TIMEPOINTS
	for(i=0;i<nTimePoints;i++){																							
		
		if(i==0){j=nTimePoints-1;	LastTimePointForROIs=1;	}	// want we beginnen met de laatste
		if(i>0)	{j=nTimePoints-1-i;	LastTimePointForROIs=0;	}	// en daarna door met de derde-tweede-eerste
		Transm		= ArrayTransm[j];	
		H2B		= ArrayH2B[j];
		TimePoint	= ArrayTimePoints[j];
		Last		= nTimePoints-1;	// voor in de arrays
			// i is aantal keren door de loop
			// j correspondeert met timepoint in array
	
		ShuffleWindows(j);	
	
				// a ROI for each organoid		ONLY LAST TIME POINT
				// a ROI for each organoid		ONLY LAST TIME POINT
				//					OTHER CASES  -->  VIA adaptROI function
				if(LastTimePointForROIs){																					print("c");
					selectWindow(Transm);	run("Duplicate...", "title=[TEMP_LastTimePointForROIs]"); TempWindow=getTitle(); setLocation(0.5*(screenWidth-(getWidth*getZoom)) , 0.5*(screenHeight-(getHeight*getZoom)));
					run("Select None"); setOption("Show All", 1);
					if(SetStandardRectangless && j==3){ makeRectangle(1264, 2004, 424, 388);}// temp

					makeRectangle(1300, 2052, 284, 348);
					
					nROIs=0; ContinueIndicateROIs=1;	 																					if(test){setTool("rectangle");selectWindow(H2B); makeRectangle(157, 194, 253, 318);}
					while(ContinueIndicateROIs){ print("");print("");print("");print("");print("");waitForUser(Drug+" ___ "+ArrayTimePoints[j]+" \n \n draw rectangle for the positions and store in ROI Manager \n \n "+nROIs+" ROIs \n \n                     TO CONTINUE, draw nothing");print("");
						if(selectionType==-1){ContinueIndicateROIs=0;}
						if(ContinueIndicateROIs){
							roiManager("Add");	 roiManager("Select",nROIs);	 x=d2s(nROIs+1,0); roiManager("Rename","#"+x + "_(T"+j+1+")");
							nROIs=nROIs+1;
							run("Select None");																									if(test && nROIs==1){setTool("rectangle"); selectWindow(H2B);makeRectangle(338, 53, 122, 120);}
						}
					}
					SaveROIs();
				}
	
																															print("d");
	
							// MAKE Grey-Green merge and define XY-shift
							// MAKE Grey-Green merge and define XY-shift
							MakeGreyGreenMerge=0;		if(j<Last){MakeGreyGreenMerge=1;}
																															// waitForUser("TimePoint__"+TimePoint+" \n \n LastTimePointForROIs__"+LastTimePointForROIs+"   \n \n we  gaan MISSCHIEN binnen in : _____ if(MakeGreyGreenMerge)    "+MakeGreyGreenMerge);
							if(MakeGreyGreenMerge){
									xShift=0;yShift=0;																				print("d 1");print(""); // waitForUser("JAAAAAAAA    we  gaan  binnen in : _____ if(MakeGreyGreenMerge)");
									// Green																	
									open(FixedDump+"GREEN (time point "+j+1+" of "+nTimePoints+").tif"); 	GREEN=getTitle();   print("");print(""); 								print("d 2");
									// Grey
									selectWindow(Transm); run("Duplicate...", "title=[TEMP]"); GREY=getTitle();	run("RGB Color");  
									// Combine
									imageCalculator("Average create", GREEN, GREY); rename("User determines XY-shift"); xyShift=getTitle();
									selectWindow(GREEN); close(); selectWindow(GREY); close();
									selectWindow(xyShift); setLocation(0.5*(screenWidth-(getWidth*getZoom)) , 0.5*(screenHeight-(getHeight*getZoom))); setTool("line"); 
									ContinueShift=1;ArrayShiftX=newArray(0);ArrayShiftY=newArray(0);New=newArray(1);
									while(ContinueShift){
										print("");wait(200);  if(SkipLineDrawing==0){waitForUser("draw a line representing the XY-shift  \n \n from GREEN (previous) to GREY (current) \n \n do a number of times \n \n           TO CONTINUE, draw nothing ");	}				// print("");waitForUser("__selectionType"+selectionType);print("");
										if(selectionType==-1){ContinueShift=0;}
										else{	getLine(x1, y1, x2, y2, lineWidth);	xShift=x2-x1;		yShift=y2-y1;
											New[0]=xShift; ArrayShiftX = Array.concat(ArrayShiftX, New);
											New[0]=yShift; ArrayShiftY = Array.concat(ArrayShiftY, New);
											run("Draw");
										}run("Select None"); 
									}																						print("f");
									if(ArrayShiftX.length>0){
										Array.getStatistics(ArrayShiftX, dummy, dummy, xShift, dummy);
										Array.getStatistics(ArrayShiftY, dummy, dummy, yShift, dummy);																//  waitForUser("__gelukt met array vullen   _width_"+xShift+"_yShift__"+yShift);
									}
									selectWindow(xyShift);close();
									setTool("rectangle");
							} //  vd  if(MakeGreyGreenMerge)
	
			//  ADAPT ROIs
			if(j<Last){AdaptROIs(j); SaveROIs();}
	
			
			//  save an image with ROIs in there
			if(i<nTimePoints){																										// waitForUser("if(i<nTimePoints) \n \n moet dus alle behalve laatste tijdspunt-analyse \n \n i = "+i+" \n \n nTimePoints "+nTimePoints+" \n \n TimePoint "+TimePoint);
				nROIs=roiManager("count"); 
				selectWindow(Transm);	 Stack.setPosition(1, floor(slices/2) , 1);	run("Duplicate...", "title=[TEMP]"); run("RGB Color");
				run("Colors...", "foreground=magenta");
				for(k=0;k<nROIs;k++){
					getDimensions(x, y, dummy, dummy, dummy);	FontSize=((x+y)/2)/FractionForFontSize;
					roiManager("Select",k);	  getSelectionBounds (xROI, yROI, dummy, dummy);
					Stack.setPosition(1, floor(slices/2) , 1);	run("Draw");	
					LabelText=d2s(k+1,0);	run("Label...", "format=Text x="+xROI+(0.5*FontSize)+" y="+yROI+(1.5*FontSize)+" font="+FontSize+" text="+LabelText);															// waitForUser("label ");
				}
				Title="ROI Landscape ("+ArrayTimePoints[j]+")";
				selectWindow("TEMP"); rename(Title); run("Select None"); 
				saveAs("Tiff", DumpLocation+Title+".tif"); 	
				saveAs("Tiff", FixedDump+Title+".tif"); 
				NumberOfROIs=toString(nROIs);	File.saveString(NumberOfROIs, DumpLocation+"nROIs.txt");	
				SavedFileWithROIs=getTitle(); 
			}
	
			
			// after indicating the ROI in the last time point 
					// * make GREEN and save it
					// * go back to first time point
			if(j>0){
				MakeGreenForMerge(SavedFileWithROIs);	// only with LAST TIME POINT
			}else{
			if(i<nTimePoints){selectWindow(SavedFileWithROIs); close();print("huh 4");}	// deze ELSE  is about TimePoint = ArrayEtc[0], [1], [2]
			}
																																								// waitForUser("EINDE VAN DE LOOP");print("huh 5");
	if(isOpen("ROI Manager"))		{selectWindow("ROI Manager");		 	run("Close");}
	if(isOpen("TEMP_LastTimePointForROIs"))	{selectWindow("TEMP_LastTimePointForROIs");	close();}
	} // vd for(i=0i<nTimePoints)
																											
}



if(ReUseROIs){
	nROIFill=10; if(File.exists(DumpLocation+"nROIs.txt")){		nROIFill = File.openAsRawString(DumpLocation+"nROIs.txt");}
	BeginROI=1 ; if(File.exists(DumpLocation+"BeginROI.txt")){	BeginROI = File.openAsRawString(DumpLocation+"BeginROI.txt");	BeginROI=parseFloat(BeginROI)+1;}

	Dialog.create(""); Dialog.addNumber("nROIs", nROIFill); Dialog.addNumber("en waar te beginnen???", BeginROI); Dialog.addMessage("nota bene , het gewone getal");	Dialog.show();		nROIs = Dialog.getNumber; ROIStart = Dialog.getNumber; 
	
}else{ROIStart=1;}















	WindowForTPsArray		= newArray(nTimePoints);
	Reversed			= newArray(nTimePoints);
	LowestPlaneArray		= newArray(nTimePoints);
	HighestPlaneArray		= newArray(nTimePoints);
	MiddlePlaneArray		= newArray(nTimePoints);
	ArraynRealSlices		= newArray(nTimePoints);
	RestArray 			= newArray(nTimePoints);
	OnePlaneAboveMiddle		= newArray(nTimePoints);
	OnePlaneBelowMiddle		= newArray(nTimePoints);
	MarkMiddleArray			= newArray(nTimePoints);
	WeightsArrayStringArray		= newArray(nTimePoints);
	WeightCodeArrayStringArray	= newArray(nTimePoints);
	AllowManipulationArray		= newArray(nTimePoints);
	ArraySkipAnalysis		= newArray(nROIs);
	ArrayAnalyzedROIs		= newArray(nROIs);


nPos = nROIs * nTimePoints;
	ArrayOrganoidH2B_Total		= newArray(nPos);
	ArrayOrganoidH2B_Alive		= newArray(nPos);
	ArrayOrganoidH2B_Dead		= newArray(nPos);
	ArrayOrganoidPercentageAlive	= newArray(nPos);
	ArrayOrganoidnPlanes		= newArray(nPos);
	ArrayOrganoidnRealSlices	= newArray(nPos);
	ArrayWeightsArrayString		= newArray(nPos);
	ArrayWeightCodeArrayString	= newArray(nPos);
	ArraySumWeights			= newArray(nPos);
	ArrayReversed			= newArray(nPos);
	ArrayMarkMiddle			= newArray(nPos);
	ArrayAllowManipulation		= newArray(nPos);
			
	
	ArrayOrganoidH2B_Total_50	= newArray(nPos);
	ArrayOrganoidH2B_Alive_50	= newArray(nPos);
	ArrayOrganoidH2B_Dead_50	= newArray(nPos);
	ArrayOrganoidPercentageAlive_50	= newArray(nPos);
	ArrayOrganoidnPlanes_50		= newArray(nPos);

	
	
	
	
	
	// idea : [ROI1-T1 , ROI1-T2 , ROI1-T3 , ROI2-T1 , ROI2-T2 , ROI2-T3 , etc]

// ANALYSIS LOOP
// ANALYSIS LOOP

for(i=ROIStart-1;i<nROIs;i++){
	SkipThisOrganoid = 0 ;
	ArrayAnalyzedROIs[i] = 1;
	AllowManipulationArray		= newArray(nTimePoints);

	// windows voor de TPs naast elkaar zetten
	for(j=0;j<nTimePoints;j++){

		if(isOpen("ROI Manager"))	{selectWindow("ROI Manager");	run("Close");} run("ROI Manager..."); 		print("just entered the for(j=0;j<nTimePoints;j++)");	
		Transm		= ArrayTransm[j];	
		H2B		= ArrayH2B[j];
		TimePoint	= ArrayTimePoints[j];
		roiManager("Open", DumpLocation+"RoiSet Drug&Release_("+TimePoint+").zip");

		if(j==0){run("Tile"); 	ShuffleWindows(j);}		print("net na   ShuffleWindows");

		selectWindow(Transm); 	run("Select None"); setLocation(screenWidth,1); roiManager("Select",i);
		selectWindow(H2B); 	roiManager("Select",i);	run("Duplicate...", "title=[H2B_ROI-stack#"+i+1+"_("+TimePoint+")] duplicate");	H2B_ROI=getTitle();		WindowForTPsArray[j] = H2B_ROI;
		selectWindow(H2B_ROI); 	Stack.setPosition(1, floor(slices/2) , 1);	run("Enhance Contrast", "saturated=0.35");

		if(j==0){	Zoom(H2B_ROI, "Left", "" , 1);}
		else{		Zoom(H2B_ROI, "Right", WindowForTPsArray[j-1] , 1 );}
	}													


	
	
	// For each ROI, determine highest and lowest z-plane ; or decide to skip at all
	Three=0;
	for(j=0;j<nTimePoints;j++){
		if(SkipThisOrganoid==0){
			
		if(test){HighestH2B=5;LowestH2B=27;}	
		if(test==0 && test3==0){
			selectWindow(WindowForTPsArray[j]); getDimensions(dummy, dummy, dummy, slices, frames);  	run("Green");											
			if(j==0){getLocationAndSize(xTemp,yTemp,WidthTemp,HeightTemp);} setLocation(xTemp+0.2*WidthTemp , yTemp+0.15*HeightTemp); 									
			Zoom("B&C", "Right", WindowForTPsArray[j] , 0); 
			selectWindow(WindowForTPsArray[j]); Stack.setPosition(1,1,1);						
				if(Three<8){setSlice(1);}		
				print(""); waitForUser(ArrayTimePoints[j]+" \n \n Set at LOWEST  plane with meaningful H2B-signal");	
				Stack.getPosition(dummy,LowestH2B ,dummy);	LowestPlaneArray[j]  = LowestH2B ;
				
				HighSlice=slices; if(LowestH2B>(0.5*slices)){HighSlice=1;};
			selectWindow(WindowForTPsArray[j]); 	
				run("Next Slice [>]");	
				if(Three){setSlice(floor(0.5*slices));} 
				print(""); print(""); waitForUser("Set at HIGHEST plane with H2B");						
				Stack.getPosition(dummy,HighestH2B,dummy);	HighestPlaneArray[j] = HighestH2B ;													
		}

		zStackOrientation=1;Reversed[j]=0; 	
		if(HighestH2B<LowestH2B){
			Reversed[j]=1; selectWindow(WindowForTPsArray[j]); run("Reverse"); 
			Temp1=LowestH2B; Temp2=HighestH2B; 	
				HighestH2B = slices - (Temp2-1); 
				LowestH2B  = 1 + (slices - Temp1);  	 waitForUser("LowestH2B "+LowestH2B+"            HighestH2B "+HighestH2B);	 // high en low geswapped
		}																														


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			selectWindow(WindowForTPsArray[j]); aaa=getTitle();	getDimensions(dummy,dummy,dummy, slicesTemp, framesTemp);	if(framesTemp>slicesTemp){slicesTemp=framesTemp;}													
			TestCalculatePlanes=0;
			ContinueCalculatePlanes=1; MarkMiddle=0;
			while(ContinueCalculatePlanes){			
				ContinueCalculatePlanes=0;
				selectWindow(aaa);
				
				PlanesArray = newArray(0); 
				New=newArray(1);
				
				nPlanesTemp = 0; zPlane = LowestH2B; 
				if(MarkMiddle==0){MiddleH2BReal = LowestH2B  +  zStackOrientation*0.5*(HighestH2B-LowestH2B) + 0.1;}   	// 0.1 is a little trick to be sure that  : 7  --> 7.1 	becomes  7
				if(MarkMiddle==1){MiddleH2BReal = MiddleH2B + 0.1;}
				MiddleH2B = round(MiddleH2BReal);	if(MiddleH2B>slicesTemp){MiddleH2B=slicesTemp;} 		print("___MiddleH2B_"+MiddleH2B);
				setSlice(MiddleH2B);					//						7.5 --> 7.6	becomes 8
				Difference = MiddleH2B-MiddleH2BReal ; if(Difference > 0.3){Rest=1;}else{Rest=0;} RestArray[j]=Rest;
				if(MarkMiddle==0){MiddlePlaneArray[j] = MiddleH2B;} 
				run("Enhance Contrast", "saturated=0.35");
																														if(TestCalculatePlanes){	waitForUser("j__"+j+"__MiddleH2BReal__"+MiddleH2BReal+"__MiddleH2B__"+MiddleH2B+"__Difference__"+Difference+"__Rest__"+Rest);}
					Continue=1;																								print("*************************************** \n Date_"+Date+"___Tumor_"+Tumor+"___Drug_"+Drug); print("TimePoint__ "+ArrayTimePoints[j]); 
					while(Continue){
						OldValue=OnePlaneAboveMiddle[j];
						OnePlaneAboveMiddle[j]=0;
						if(OnePlaneAboveMiddle[j] != OldValue){print("");print("");}
						
						zPlane   = round(LowestH2B + (nPlanesTemp*TranssectionStep*zStackOrientation));
						
						if(zStackOrientation ==  1){	
							if(zPlane <= MiddleH2B){		if(zPlane == MiddleH2B - 1){	OnePlaneBelowMiddle[j]=1;			} 	}
							else{Continue=0;			if(zPlane == MiddleH2B + 1){ 	OnePlaneAboveMiddle[j]=1;	Continue=1;	} 	}
						}
						if(zStackOrientation == -1){	
							if(zPlane >= MiddleH2B){		if(zPlane == MiddleH2B + 1){	OnePlaneBelowMiddle[j]=1;			} 	}
							else{Continue=0;			if(zPlane == MiddleH2B - 1){ 	OnePlaneAboveMiddle[j]=1;	Continue=1;	} 	}
						}

						if(Continue){	New[0] = zPlane;	
								if(OnePlaneAboveMiddle[j]==1){New[0] = zPlane-1; }
								PlanesArray = Array.concat(PlanesArray, New);	
								nPlanesTemp=nPlanesTemp+1;														
																															print("nPlanesTemp__"+nPlanesTemp+"_____zPlane__"+zPlane);	print(""); 
																															if(TestCalculatePlanes){	if(OnePlaneBelowMiddle[j] + OnePlaneAboveMiddle[j] >0){	waitForUser("zPlane__"+zPlane+"___MiddleH2B__"+MiddleH2B+"__OnePlaneBelowMiddle[j]__"+OnePlaneBelowMiddle[j]+"__OnePlaneAboveMiddle[j]__"+OnePlaneAboveMiddle[j]);}}
						}
					}  // vd while(Continue)


				if(zStackOrientation==-1){PlanesArray = Array.reverse(PlanesArray);}																			print(" *****");print("de PlanesArray"); Array.print(PlanesArray); 
				nPlanes 	= nPlanesTemp; 																								print("nPlanes : "+nPlanes);		if(nPlanes != PlanesArray.length){waitForUser("something's wrong !!");};
				nSteps  	= nPlanesTemp-1;																							print("nSteps : "+nSteps);
				nRealSlices	= HighestH2B-LowestH2B+1;		ArraynRealSlices[j] = nRealSlices;						
				
			ContinueDeciding=1; nLoops=0;
			while(ContinueDeciding){
				nLoops=nLoops+1; 
				print("");print("net in de ContinueDeciding ; kijk Log"); Array.print(PlanesArray);		

		
		//  make a window to show to the user
		//  make a window to show to the user
		OldOne=0;
				SubStackString = ""; Comma=","; for(t=0;t<PlanesArray.length;t++){if(t==PlanesArray.length-1){Comma="";} SubStackString = SubStackString + PlanesArray[t] + Comma; }		
		if(OldOne){				
				selectWindow(aaa); 	run("Make Substack...", "  slices="+SubStackString); bbb=getTitle();selectWindow(bbb);
		}else{
				selectWindow(aaa);	/*definition*/  nPlanesBelowLowest=1; if(LowestH2B==1){nPlanesBelowLowest=0;}
							L = PlanesArray.length; 
							From = PlanesArray[0]-1; 	if(From<0){From=0;}
							To   = PlanesArray[L-1]+ShownPlanesAbove; 	
							run("Duplicate...", "title=[Chosen slices in red] duplicate range="+From+"-"+To); bbb=getTitle();selectWindow(bbb);
							run("RGB Color"); run("Colors...", "foreground=red"); LW= getWidth() /25; run("Line Width...", "line="+LW); 
							for(m=0;m<L;m++){
								R=1+nPlanesBelowLowest+PlanesArray[m]-PlanesArray[0]; F=2*LW; T=m+1;  if(m==0){T=d2s(m+1,0)+" (lo)"; }  if(m==L-1){T=d2s(m+1,0)+" (hi)"; HighestSelectedSlice=R; }
								setSlice(R); run("Select All");  run("Draw", "slice");run("Select None");
								run("Label...", "format=Text x="+F+" y="+2*F+" font="+F+" text="+T+" range="+R+"-"+R);
							}
							 run("Line Width...", "line=1");  Zoom(bbb, "Left", "" , 0); 
							 setSlice(HighestSelectedSlice);    
		}
				
				
				waitForUser("NOW  "+nPlanes+"  PLANES \n \n "+SubStackString+" \n \n good idea? \n \n or change # of zPlanes ?");
		
					Dialog.create(""); 
					Dialog.addMessage("# planes : "+nPlanes + "     (# steps "+nSteps+")");
					Dialog.addMessage(" --> "+SubStackString);
					Dialog.addCheckbox("Highest H2B : 1 higher"  , 0); 													
					Dialog.addCheckbox("Highest H2B : 1 lower "  , 0); 
					Dialog.addMessage("  ");
					Dialog.addCheckbox("One slice more ( + 1 transsection step ) "  , 0); 
					Dialog.addCheckbox("One slice less ( - 1 transsection steps) "  , 0); 
					Dialog.addMessage("  ");
					Dialog.addCheckbox("Mark MIDDLE plane instead of highest "  , 0); 
					Dialog.addMessage("  ");
					Dialog.addCheckbox("SKIP THIS ORGANOID !! "  , 0); 
						Dialog.show();											Changed=0;
					HighestOneHigher = Dialog.getCheckbox; 		
					HighestOneLower = Dialog.getCheckbox; 		
					OneSliceMore  = Dialog.getCheckbox; 		
					OneSliceLess = Dialog.getCheckbox; 		
					MarkMiddle = Dialog.getCheckbox; 			if(MarkMiddle){MarkMiddleArray[j]=1;}		
					SkipThisOrganoid = Dialog.getCheckbox; 			
												if(ArraySkipAnalysis[i]==0){	if(SkipThisOrganoid){ArraySkipAnalysis[i]=1;} 		}

					if(Changed){    // inactive, Changed is never at 1
						TranssectionStep = (nRealSlices-1) / nSteps ; 									
						nPlanes = nSteps+1;
						SecondPlanesArray = newArray(nPlanes);
						for(t=0;t<nPlanes;t++){SecondPlanesArray[t] = round(LowestH2B + (t * TranssectionStep * zStackOrientation));}	
						if(zStackOrientation==-1){SecondPlanesArray = Array.reverse(SecondPlanesArray);}
																										print("CHANGED ****** CHANGED ****** "); print("CHANGED  SecondPlanesArray"); Array.print(SecondPlanesArray); 
																										print("nPlanes : "+nPlanes);	if(nPlanes != SecondPlanesArray.length){waitForUser("CHANGED something's wrong !!");};
																										print("nSteps : "+nSteps);
																								 		print("nRealSlices : "+nRealSlices);			selectWindow("Log"); 
					}
					L=PlanesArray.length;
					if(Changed==0){									ContinueDeciding=0;}
					if(HighestOneHigher){	PlanesArray[L-1] = PlanesArray[L-1] + 1 ;		ContinueDeciding=1;}
					if(HighestOneLower){	PlanesArray[L-1] = PlanesArray[L-1] - 1 ;		ContinueDeciding=1;}
					if(OneSliceMore){	New[0]=PlanesArray[L-1] + TranssectionStep; 
								PlanesArray = Array.concat(PlanesArray, New);		
								nPlanes=nPlanes+1;					ContinueDeciding=1;}
					if(OneSliceLess){	PlanesArray = Array.trim(PlanesArray , L-1); 
								nPlanes=nPlanes-1;					ContinueDeciding=1;}
					if(SkipThisOrganoid){	for(q=0;q<nTimePoints;q++){
								if(isOpen(WindowForTPsArray[q])){selectWindow(WindowForTPsArray[q]);close();}
								}
					}
					if(MarkMiddle){		selectWindow(bbb); 
								// eerst uitbreiden
								if(To+1 < slicesTemp){
									selectWindow(aaa); run("Duplicate...", "title=[Temp] duplicate range="+To+1+"-"+slicesTemp); 	run("RGB Color");				
									run("Concatenate...", "  title=[VeryTemp] image1=["+bbb+"] image2=[Temp] image3=[-- None --]"); rename(bbb);	Zoom(bbb, "Left", "" , 0);	
								}
								setSlice(1+nPlanesBelowLowest); waitForUser(ArrayTimePoints[j]+" \n \n Set at MIDDLE  plane");  
								Stack.getPosition(dummy,Temp ,dummy); MiddleH2B = LowestH2B + (Temp-1-nPlanesBelowLowest);
								HighestH2B = LowestH2B + 2*(MiddleH2B-LowestH2B);													
									MiddlePlaneArray[j]  = MiddleH2B ; 
									HighestPlaneArray[j] = HighestH2B ;
									OnePlaneBelowMiddle[j]=0;
									OnePlaneAboveMiddle[j]=0;
								ContinueCalculatePlanes=1;
					}
					if(isOpen(bbb))	{	selectWindow(bbb);	close();}
				}  // vd  while(ContinueDeciding)
		}  // vd while(ContinueCalculatePlanes)	
				
				
				
				if(j==0){PlanesArrayTP1 = Array.copy(PlanesArray);}
				if(j==1){PlanesArrayTP2 = Array.copy(PlanesArray);}
				if(j==2){PlanesArrayTP3 = Array.copy(PlanesArray);}
				if(j==3){PlanesArrayTP4 = Array.copy(PlanesArray);}
				if(j==4){PlanesArrayTP5 = Array.copy(PlanesArray);}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		if(SkipThisOrganoid==0){selectWindow(WindowForTPsArray[j]); setLocation(screenWidth+1,1);}
	}   //   vd  if(SkipThisOrganoid==0)
	}   //   vd  for(j=0;j<nTimePoints;j++)    
	// For each ROI, determine highest and lowest z-plane ; or decide to skip at all

TestWeights=1;			if(TestWeights && SkipThisOrganoid==0){														print("xxxxxxxx"); print("xxxxxxxx"); print("xxxxxxxx");     print("xxxxxxxx"); 
												for(j=0;j<nTimePoints;j++){
																if(j==0){nPlanes = PlanesArrayTP1.length; }
																if(j==1){nPlanes = PlanesArrayTP2.length; }
																if(j==2){nPlanes = PlanesArrayTP3.length; }
																if(j==3){nPlanes = PlanesArrayTP4.length; }
																if(j==4){nPlanes = PlanesArrayTP5.length; }
																
																Rest = RestArray[j];
																OPB = OnePlaneBelowMiddle[j];
																OPA = OnePlaneAboveMiddle[j];					

																New=newArray(1); WeightsArray=newArray(0); WeightCodeArray=newArray(0);		SumWeights=0;

																nP = nPlanes;
																for(c=0;c<nPlanes;c++){
																										Weight = 3;	WeightCode="THREE";
																	if(c==0){								Weight = 2;	WeightCode="A";}
																/*1*/	if(c!=0  &&  OPB==0  &&  OPA==0  &&  Rest==0  && c==nP-1){		Weight = 1.5;	WeightCode="B";}
																/*2*/	if(c!=0  &&  OPB==0  &&  OPA==0  &&  Rest==1  && c==nP-2){		Weight = 2;	WeightCode="C";}
																	if(c!=0  &&  OPB==0  &&  OPA==0  &&  Rest==1  && c==nP-1){		Weight = 2;	WeightCode="D";}
																/**/	if(c==0  &&  OPB==0  &&  OPA==0  &&  Rest==1              &&  nP==2){	Weight = 1.5;	WeightCode="A_2";}
																	if(c!=0  &&  OPB==0  &&  OPA==0  &&  Rest==1  && c==nP-1  &&  nP==2){	Weight = 1.5;	WeightCode="D_2";}
																/*3*/	if(c!=0  &&  OPB==0  &&  OPA==1  &&  Rest==0  && c==nP-2){		Weight = 2;	WeightCode="E";}		
																	if(c!=0  &&  OPB==0  &&  OPA==1  &&  Rest==0  && c==nP-1){		Weight = 1.5;	WeightCode="F";}		
																/**/	if(c==0  &&  OPB==0  &&  OPA==1  &&  Rest==0              &&  nP==2){	Weight = 1.5;	WeightCode="A_2_2";}		
																	if(c!=0  &&  OPB==0  &&  OPA==1  &&  Rest==0  && c==nP-1  &&  nP==2){	Weight = 1;	WeightCode="F_2";}		
																/*4*/	if(c!=0  &&  OPB==0  &&  OPA==1  &&  Rest==1  && c==nP-2){		Weight = 1.5;	WeightCode="G";}		
																	if(c!=0  &&  OPB==0  &&  OPA==1  &&  Rest==1  && c==nP-1){		Weight = 1.5;	WeightCode="H";}		
																/**/	if(c==0  &&  OPB==0  &&  OPA==1  &&  Rest==1              &&  nP==2){	Weight = 1;	WeightCode="A_2_2_2";}		
																	if(c!=0  &&  OPB==0  &&  OPA==1  &&  Rest==1  && c==nP-1  &&  nP==2){	Weight = 1;	WeightCode="H_2";}		
																/*5*/	if(c!=0  &&  OPB==1  &&  OPA==0  &&  Rest==0  && c==nP-1){		Weight = 2.5;	WeightCode="I";}		
																/*6*/	if(c!=0  &&  OPB==1  &&  OPA==0  &&  Rest==1  && c==nP-1){		Weight = 2;	WeightCode="J";}		
																								
																	New[0]=Weight;		WeightsArray 	= Array.concat(WeightsArray	, New);
																	New[0]=WeightCode;	WeightCodeArray = Array.concat(WeightCodeArray	, New);
																	SumWeights = SumWeights + Weight;
																}	print("");  print("PRINTING THE WEIGHTS !!!! for j="+j); print("length array : "+WeightsArray.length); print("SumWeights :"+SumWeights); Array.print(WeightsArray); print("WeightCode :");Array.print(WeightCodeArray); selectWindow("Log"); // waitForUser("kijk naar de WeightsArray in de LOG");
												}
}
























	
	//  and now analyze all consecutive timepoints
	//  and now analyze all consecutive timepoints
	if(SkipThisOrganoid==0){
	
	for(j=0;j<nTimePoints;j++){																								
		
		if(isOpen("ROI Manager"))	{selectWindow("ROI Manager");	run("Close");} run("ROI Manager..."); 				
		
		Transm		= ArrayTransm[j];	
		H2B		= ArrayH2B[j];
		TimePoint	= ArrayTimePoints[j];
		roiManager("Open", DumpLocation+"RoiSet Drug&Release_("+TimePoint+").zip");

		selectWindow(WindowForTPsArray[j]); H2B_ROI=getTitle();		Zoom(H2B_ROI, "Left", "" , 0);																											// waitForUser("windows shuffeld OK ?");
	
		if(isOpen("AllDead"))	{} else{newImage("AllDead"   , "RGB black", 300, 100, 1);setFont("SansSerif", 30, " antialiased");run("Colors...", "foreground=red");		drawString("all dead"      , 0.5*getWidth-0.5*getStringWidth("All Dead")      , getHeight-30);} setLocation(screenWidth, 1);
		if(isOpen("DrawLiving")){} else{newImage("DrawLiving", "RGB black", 300, 100, 1);setFont("SansSerif", 30, " antialiased");run("Colors...", "foreground=green");		drawString("draw alive H2B", 0.5*getWidth-0.5*getStringWidth("draw alive H2B"), getHeight-30);} setLocation(screenWidth, 1);
		

		if(j>0){print(""); waitForUser(" NEXT TIMEPOINT \n NEXT TIMEPOINT \n NEXT TIMEPOINT \n NEXT TIMEPOINT \n \n  "+TimePoint); print("");}



		if(j==0){PlanesArray = Array.copy(PlanesArrayTP1);}
		if(j==1){PlanesArray = Array.copy(PlanesArrayTP2);}
		if(j==2){PlanesArray = Array.copy(PlanesArrayTP3);}
		if(j==3){PlanesArray = Array.copy(PlanesArrayTP4);}
		if(j==4){PlanesArray = Array.copy(PlanesArrayTP5);}

		if(zStackOrientation==-1){PlanesArray = Array.reverse(PlanesArray);}

		DrewAway=0; nPixelsDrawnAway=0; PreviousIndexROIDrawAway=0; PreviousDrewAway=0;
		PreviousMin=0;
		nPlanes=0;

		for(Plane=0 ; Plane<PlanesArray.length;Plane++){		// the consecutive zPlanes of a stack
			zPlane = PlanesArray[Plane];	
				selectWindow(H2B_ROI); Stack.setPosition(1,zPlane,1); run("Duplicate...", "title=[slice_"+zPlane+"]"); run("glow"); ThisPlane=getTitle();
				Zoom(ThisPlane, "Left", "" , 0);
				selectWindow(H2B_ROI); getMinAndMax(min,max); selectWindow(ThisPlane);  setMinAndMax(min,max); Zoom(H2B_ROI, "Right", ThisPlane , 0);
					
				Title=ThisPlane;
					// Enhance
					setOption("Show All", 0); 
					selectWindow(Title); run("Select None");
					run("Enhance Contrast", "saturated=0.05"); 	
					getMinAndMax(min,max); 	newMin=0.9*PreviousMin;		if(newMin<0) {newMin=0;} 	

					if(GaussManually){	if(newMin==0){print("");waitForUser("Set Gauss blur factor around  ~0.7");print("");}	run("Gaussian Blur...");}					else{run("Gaussian Blur...", "sigma=0.7 stack");}		run("Enhance Contrast", "saturated=0.05");
					if(GammaManually){	if(newMin==0){print("");waitForUser("play around to see whether gamma helps   (often OK : ~0.85 ) ");print("");}	run("Gamma...");}		else{run("Gamma...", "value=0.7");}				run("Enhance Contrast", "saturated=0.1"); 	/*setMinAndMax(min,max);*/ selectWindow("B&C"); 
					Zoom("B&C", "Right", Title , 0); selectWindow(Title);
					getMinAndMax(min,max); 
								newMin=0.9*PreviousMin;		if(newMin<0) {newMin=0;} 	
								newMax=max; 
						if(Plane>0){	newMax=0.9*PreviousMax; 	if(newMax<10){newMax=10;} 	}
						Warning=""; if(newMin==0){Warning=" SCALING STARTS AT ZERO \n";}
						setMinAndMax(newMin,newMax);selectWindow("B&C"); selectWindow(Title); 
					waitForUser("Adjust B&C ; find offset to eliminate background \n \n"+Warning+Warning+Warning+Warning+Warning+Warning+Warning+Warning);
					getMinAndMax(min,max); run("Select None"); PreviousMin=min;PreviousMax=max;
					if(min==0 && max==255){min=1;}if(max==255){max=254;} setMinAndMax(min,max); run("8-bit");  	run("Brightness/Contrast...");	/*waitForUser("test 1 ");	*/	getMinAndMax(min_2,max_2); setMinAndMax(min_2 , max_2-1); run("Apply LUT");	/*waitForUser("test 2 ");	*/		
					selectWindow(H2B_ROI); setMinAndMax(min,max);   // store the min in 'H2B_ROI' 
					
					// draw away other organoids , that may be in the corners
					setTool("freehand"); selectWindow(Title);  run("Select None");
					if(DrewAway){roiManager("Select",IndexROIDrawAway);}
					nROIsStart=roiManager("count");
					selectWindow(H2B_ROI); 	getLocationAndSize(xTemp1,yTemp1,dummy,dummy); setLocation(screenWidth,1);
					selectWindow(Title); 	getLocationAndSize(xTemp2,yTemp2,dummy,dummy); setLocation(xTemp2 + 0.05*screenWidth , yTemp2 + 0.08*screenHeight);
					run("glow"); 
					waitForUser(" draw away stuff that TO EXCLUDE from analysis  \n \n (e.g. parts of other organoids) \n \n                TO CONTINUE, select nothing");
						selectWindow(Title);
						if(selectionType==-1){	DrewAway=0;} 
						if(selectionType!=-1){	DrewAway=1; run("Set...", "value=0");
									roiManager("Add"); roiManager("Select",nROIsStart); roiManager("Rename","DrawAway"); 		IndexROIDrawAway=nROIsStart; 
									if(PreviousDrewAway){roiManager("Select",PreviousIndexROIDrawAway); roiManager("Delete"); 	IndexROIDrawAway=IndexROIDrawAway-1;}
									PreviousIndexROIDrawAway = IndexROIDrawAway;							
						}
									PreviousDrewAway = DrewAway;
						
					run("Select None");
					selectWindow(H2B_ROI); 	setLocation(xTemp1,yTemp1);	
					selectWindow(Title);	setLocation(xTemp2,yTemp2);

					// what is more or less the size of a nucleus
					if(test==0){
					if(nPlanes==0 && i==0){
						selectWindow(Title); run("Select None"); Area=newArray(3);
						for(k=0;k<3;k++){
							waitForUser("Please draw a nucleus 3 times \n to measure average surface \n (this is used as a reference for the automatic detection of the smaller dead particles) \n \n #"+k+1); run("Measure"); Area[k] = getResult("Area", nResults-1); 
							if(k>0){if(Area[k]==Area[k-1]){k=4;}}	
							q=1; if(selectionType==-1){k=4; MeanArea=66; q=0; }
							run("Select None");
						}
						if(q){Array.getStatistics(Area, dummy, dummy, MeanArea, dummy);} 
						run("Select None"); 							 													 //waitForUser("MeanArea "+MeanArea+ " pixels" );
						ArrayMeanNucleusArea[j] = MeanArea;																		print("ArrayMeanNucleusArea"); Array.print(ArrayMeanNucleusArea); selectWindow("Log"); 			// waitForUser("check ArrayMeanNucleusArea");
					}
					else{
						MeanArea = ArrayMeanNucleusArea[j]; 												
					}
					if(test){MeanArea=63;}
					}
					// double
					run("Duplicate...", "title=[Enhanced H2B]"); 
					selectWindow(Title); 
					// threshold --> all H2B
					if(isOpen("Threshold"))	{selectWindow("Threshold");run("Close");}
					selectWindow(Title); getLocationAndSize(x,y,width,height); run("Threshold..."); if(HuangThresholding){setAutoThreshold("Huang dark");}else{setAutoThreshold("Default dark");} 
					nROIsStart=roiManager("count"); selectWindow("Threshold"); setLocation(x+width+10, y+(0.3*height));
					selectWindow(Title); selectWindow("Threshold"); 						
					selectWindow(Title); selectWindow("Threshold"); 						

					
					ContinueSeThreshold=1;	
					while(ContinueSeThreshold){ContinueSeThreshold=0; print(""); waitForUser("Set Threshold to include ALL H2B  (dead or alive)");
						if(getTitle()!=Title){waitForUser("watch out , wrong window !!"); selectWindow(Title); ContinueSeThreshold=1;}
					}
					getThreshold(LowerThreshold, UpperThreshold);
					run("Create Selection"); 	roiManager("Add");	roiManager("Select",nROIsStart); roiManager("Rename","All H2B signal"); 	
					IndexAllH2B=nROIsStart;

				
					//  binary for all-H2B
					run("Convert to Mask");  run("Watershed"); a=getTitle(); run("Duplicate...", "title=[Watershed #2]"); selectWindow(a);
					setAutoThreshold("Default dark"); CloseThisOne=getTitle();														
					run("Analyze Particles...", "size=0-Infinity pixel show=Masks display clear");
					rename("Masks All-H2B"); 																			
					selectWindow(CloseThisOne);  close(); 
																						if(MeanArea==0){MeanArea=66; ArrayMeanNucleusArea[j]=66;}
					//  binary minus small particles
					selectWindow("Watershed #2");																								
					run("Analyze Particles...", "size="+FractionDeadParticle*MeanArea+"-Infinity pixel show=Masks display clear"); 
					rename("Masks H2B without small particles");  																		
					selectWindow("Watershed #2");  close(); 
					selectWindow("Enhanced H2B"); 	run("Duplicate...", "title=[Enhanced H2B_#2]");  													
					
																																
					//  now green channel with first-particles-already-removed
					RemoveParticlesFromH2B("Masks H2B without small particles" , "Enhanced H2B");
					selectWindow("Enhanced H2B"); 		a=getTitle();	setLocation(screenWidth-getWidth , 0.5*screenHeight);	run("Duplicate...", "title=[H2B Alive]");	c=getTitle();	run("glow");	
					selectWindow("Enhanced H2B_#2"); 	b=getTitle();	setLocation(screenWidth-getWidth , 0.5*screenHeight);	run("Duplicate...", "title=[H2B All]");		d=getTitle();	run("glow");

					setBatchMode(false);

					// Mark Dead Particles
					MarkedDeadParticles = MarkDeadParticles("H2B Alive" , "H2B All" , "Masks H2B without small particles" , "Masks H2B without dead particles");													
					//  now  remove from H2B
					RemoveParticlesFromH2B("Masks H2B without dead particles" , "Enhanced H2B");														
					
					//  once again ??	
					ContinueRemoveDead=1;
					while(ContinueRemoveDead){																				
						selectWindow("Masks H2B without dead particles"); run("Measure"); MeasureBinary = getResult("Area", nResults-1); 
						Zoom(a	, "Left" , "" , 0);		rename("H2B Alive");																	
						Zoom(b	, "Right", c , 0);		rename("H2B All");																	
						Fill="no, ready";  Old = FractionDeadParticle*MeanArea;
						if(MeasureBinary==0){MoreDrawing="no, ready"; ContinueRemoveDead=0;}else{
							Dialog.create(""); Dialog.addRadioButtonGroup("draw more dead particles?", newArray("yes","no, ready"), 2, 1, Fill);	
							Dialog.addMessage("");Dialog.addMessage("FractionDeadParticle*MeanArea = now ___"+FractionDeadParticle*MeanArea+"  pixels");
							Dialog.addCheckbox("10% less sensitive in detecting dead particles", 0); Dialog.addCheckbox("5% less sensitive in detecting dead particles", 0);  Dialog.addCheckbox("5% more sensitive in detecting dead particles", 0); Dialog.addCheckbox("10% more sensitive in detecting dead particles", 0);
						//	Dialog.addMessage("");
						//	Dialog.addCheckbox("Or just define Fraction manually", 0);
							Dialog.show(); 
							MoreDrawing = Dialog.getRadioButton; 		if(MoreDrawing=="yes"){}else{ContinueRemoveDead=0;}
							LessSensitive10 = Dialog.getCheckbox;		if(LessSensitive10){	FractionDeadParticle = FractionDeadParticle*1.1;}
							LessSensitive5 = Dialog.getCheckbox;		if(LessSensitive5 ){	FractionDeadParticle = FractionDeadParticle*1.05;}
							MoreSensitive5 = Dialog.getCheckbox;		if(MoreSensitive5 ){	FractionDeadParticle = FractionDeadParticle*0.95;}
							MoreSensitive10 = Dialog.getCheckbox;		if(MoreSensitive10){	FractionDeadParticle = FractionDeadParticle*0.9;}
						//	DefineManually = Dialog.getCheckbox;		if(DefineManually){	New = getNumber("Fraction*MeanArea",Old); FractionDeadParticle = New / MeanArea; }
							DefineManually = 0;
						}
						if(ContinueRemoveDead){
							selectWindow(c); 	run("Duplicate...", "title=["+a+"]");
							selectWindow(d);  	run("Duplicate...", "title=["+b+"]");														
				
							MarkedDeadParticles = MarkDeadParticles("H2B Alive" , "H2B All" , "Masks H2B without dead particles" , "Masks H2B without dead particles");								
							RemoveParticlesFromH2B("Masks H2B without dead particles" , "Enhanced H2B");												
						}
					}

					// complete the MASKS																
					// complete the MASKS																
					selectWindow("Masks All-H2B"); 				rename("Binary All H2B ("+  ThisPlane+")"); 	a=getTitle();							if(testImageCalculator){run("Tile"); print(""); waitForUser("__a_"+a);}
					selectWindow("Masks H2B without dead particles"); 	rename("Binary H2B Alive ("+ThisPlane+")"); 	b=getTitle();							if(testImageCalculator){run("Tile"); print(""); waitForUser("__b_"+b);}
					imageCalculator("XOR create", a,b);			rename("Binary H2B dead ("+ ThisPlane+")");	c=getTitle();	
							// some more to do with  H2B-dead
							run("Convert to Mask");	
							//
							OffsetThrowAway = 0.15*FractionDeadParticle*MeanArea; 											
							nROIsBefore=roiManager("count");
							run("Analyze Particles...", "size=0-"+OffsetThrowAway+" pixel add"); 
							nROIsAfter=roiManager("count");
							nParticlesThrowAway = nROIsAfter-nROIsBefore; ArrayThrowAwayParticles = newArray(nParticlesThrowAway);					
							nP=nParticlesThrowAway;
							if(nP>0){
								for(p=0;p<nP;p++){ArrayThrowAwayParticles[p] = nROIsBefore + p; print("");  	}
								qq=getTitle(); rename(qq+"_2"); run("Duplicate...", "title=["+qq+"]");selectWindow(qq+"_2"); close(); 
								selectWindow(qq);  	if(nP==1){roiManager("Select", nROIsAfter-1);}else{roiManager("Select", ArrayThrowAwayParticles); 	roiManager("OR");}  run("Set...", "value=0"); 	run("Select None");	print("Set...", "value=0");
								selectWindow(a);  	if(nP==1){roiManager("Select", nROIsAfter-1);}else{roiManager("Select", ArrayThrowAwayParticles); 	roiManager("OR");}  run("Set...", "value=0"); 	run("Select None");	print("Set...", "value=0");
								selectWindow(qq); 	if(nP==1){roiManager("Select", nROIsAfter-1);}else{roiManager("Select", ArrayThrowAwayParticles);}	roiManager("Delete"); 				run("Select None");	print("Delete");		
							}
							//
																							if(testImageCalculator){run("Tile"); print(""); waitForUser("__c_"+c);}

					selectWindow(c); setAutoThreshold("Default"); run("Measure"); DeadArea = getResult("Area", nResults-1); if(DeadArea==0){selectWindow(c); run("Convert to Mask");	if(testImageCalculator){run("Tile"); print(""); waitForUser("__c DeadArea==0_"+c);}}
					
					imageCalculator("AND create", "H2B All", b);		rename("H2B Alive ("+ThisPlane+")");		d=getTitle();	run("Green");					if(testImageCalculator){run("Tile"); print(""); waitForUser("__d_"+d);}
					imageCalculator("AND create", "H2B All", c);		rename("H2B dead ("+ ThisPlane+")");		e=getTitle();	run("Red");					if(testImageCalculator){run("Tile"); print(""); waitForUser("__e_"+e);}

					if(nPlanes==0)						{selectWindow("Results");			setLocation(0.82*screenWidth,1);}
					run("Merge Channels...", "c1=["+e+"] c2=["+d+"]");	rename("H2B dead or alive ("+ThisPlane+")");	setLocation(0.7*(screenWidth-(getWidth*getZoom)) , 0.2*(screenHeight-(getHeight*getZoom))); ccc=getTitle();


							nPlanes=nPlanes+1;
																															
							//  measure and then close
							k=nPlanes-1;																						
							ArraySliceNumbers[k]=zPlane;
							run("Set Measurements...", "area limit redirect=None decimal=1");

							//  by the way, AREA measurement outputs sq. micrometer
							selectWindow("Binary All H2B ("+  ThisPlane+")"); setAutoThreshold("Default");		run("Measure"); ArraySurfaceH2B[k] 	= getResult("Area", nResults-1);	close();	
							selectWindow("Binary H2B Alive ("+ThisPlane+")"); setAutoThreshold("Default");		run("Measure"); ArraySurfaceH2B_Alive[k]= getResult("Area", nResults-1);	close();
							selectWindow("Binary H2B dead ("+ ThisPlane+")"); setAutoThreshold("Default dark");	run("Measure"); ArraySurfaceH2B_Dead[k]	= getResult("Area", nResults-1);	close();	

						selectWindow(ccc);
						Dialog.create(" check result"); 	Dialog.addRadioButtonGroup("is it OK??"	,  newArray("yes","NO , REDO !!") ,2,1, "yes");	
						MonitorValues=0;
						if(MonitorValues){Dialog.addMessage("nParticles Removed = "+nP); 
						Dialog.addMessage("ArraySurfaceH2B[k] = "+ArraySurfaceH2B[k]); 
						Dialog.addMessage("ArraySurfaceH2B_Alive[k] = "+ArraySurfaceH2B_Alive[k]); 
						Dialog.addMessage("ArraySurfaceH2B_Dead[k] = "+ArraySurfaceH2B_Dead[k]);
						Dialog.addMessage("Surfaces  Alive + Dead = "+ArraySurfaceH2B_Alive[k]+ArraySurfaceH2B_Dead[k]);}
						Dialog.show();
						RedoButton  	= Dialog.getRadioButton;
							if(RedoButton=="yes"){		Redo=0;}
							if(RedoButton=="NO , REDO !!"){	Redo=1;}
							
					
					selectWindow("H2B dead or alive ("+ThisPlane+")");	
					if(Redo){close();}else{	setLocation(0.88*screenWidth,nPlanes*(0.05*screenHeight));}

						
						
						
						
						if(Redo){Plane=Plane-1; nPlanes=nPlanes-1;}

						testwaardes=0;
						if(testwaardes){waitForUser("__ArraySurfaceH2B[k]_"+ArraySurfaceH2B[k]+"__ArraySurfaceH2B_Alive[k]_"+ArraySurfaceH2B_Alive[k]+"__ArraySurfaceH2B_Dead[k]_"+ArraySurfaceH2B_Dead[k]);}
						
				//  close superfluous windows
				if(isOpen("H2B All"))		{selectWindow("H2B All"); 	close();}
				if(isOpen("H2B Alive"))		{selectWindow("H2B Alive"); 	close();}
				if(isOpen(ThisPlane))		{selectWindow(ThisPlane); 	close();}
		
				PreviousMin=min; 				PreviousMax=max; 
				PreviousLowerThreshold=LowerThreshold;		PreviousUpperThreshold=UpperThreshold;
		}  // vd for(Plane=0)  // that's for the zPlanes


							

		
		
		// Sum up per organoid  (TOTAL , in entire z-stack)
																				if(nPlanes!=PlanesArray.length){waitForUser("klopt niet");}
		OPB = OnePlaneBelowMiddle[j];
		OPA = OnePlaneAboveMiddle[j];
		Rest=RestArray[j];
		
		StackH2B	= 0 ;
		StackH2B_Alive	= 0 ;
		StackH2B_Dead	= 0 ;
		
		New=newArray(1); WeightsArray=newArray(0); WeightCodeArray=newArray(0);		SumWeights=0;
		
			nP = nPlanes;
			for(c=0;c<nPlanes;c++){    																		
													Weight = 3;	WeightCode="THREE";
				if(c==0){								Weight = 2;	WeightCode="A";}
			/*1*/	if(c!=0  &&  OPB==0  &&  OPA==0  &&  Rest==0  && c==nP-1){		Weight = 1.5;	WeightCode="B";}
			/*2*/	if(c!=0  &&  OPB==0  &&  OPA==0  &&  Rest==1  && c==nP-2){		Weight = 2;	WeightCode="C";}
				if(c!=0  &&  OPB==0  &&  OPA==0  &&  Rest==1  && c==nP-1){		Weight = 2;	WeightCode="D";}
			/**/	if(c==0  &&  OPB==0  &&  OPA==0  &&  Rest==1              &&  nP==2){	Weight = 1.5;	WeightCode="A_2";}
				if(c!=0  &&  OPB==0  &&  OPA==0  &&  Rest==1  && c==nP-1  &&  nP==2){	Weight = 1.5;	WeightCode="D_2";}
			/*3*/	if(c!=0  &&  OPB==0  &&  OPA==1  &&  Rest==0  && c==nP-2){		Weight = 2;	WeightCode="E";}		
				if(c!=0  &&  OPB==0  &&  OPA==1  &&  Rest==0  && c==nP-1){		Weight = 1.5;	WeightCode="F";}		
			/**/	if(c==0  &&  OPB==0  &&  OPA==1  &&  Rest==0              &&  nP==2){	Weight = 1.5;	WeightCode="A_2_2";}		
				if(c!=0  &&  OPB==0  &&  OPA==1  &&  Rest==0  && c==nP-1  &&  nP==2){	Weight = 1;	WeightCode="F_2";}		
			/*4*/	if(c!=0  &&  OPB==0  &&  OPA==1  &&  Rest==1  && c==nP-2){		Weight = 1.5;	WeightCode="G";}		
				if(c!=0  &&  OPB==0  &&  OPA==1  &&  Rest==1  && c==nP-1){		Weight = 1.5;	WeightCode="H";}		
			/**/	if(c==0  &&  OPB==0  &&  OPA==1  &&  Rest==1              &&  nP==2){	Weight = 1;	WeightCode="A_2_2_2";}		
				if(c!=0  &&  OPB==0  &&  OPA==1  &&  Rest==1  && c==nP-1  &&  nP==2){	Weight = 1;	WeightCode="H_2";}		
			/*5*/	if(c!=0  &&  OPB==1  &&  OPA==0  &&  Rest==0  && c==nP-1){		Weight = 2.5;	WeightCode="I";}		
			/*6*/	if(c!=0  &&  OPB==1  &&  OPA==0  &&  Rest==1  && c==nP-1){		Weight = 2;	WeightCode="J";}		
											
				New[0]=Weight;		WeightsArray 	= Array.concat(WeightsArray	, New);
				New[0]=WeightCode;	WeightCodeArray = Array.concat(WeightCodeArray	, New);
				SumWeights = SumWeights + Weight;
											
				Add = Weight * ArraySurfaceH2B[c]      ;	StackH2B 	= StackH2B 		+ Add;		// THIS IS WHERE VALUES OF EACH SLICE IS SUMMED
				Add = Weight * ArraySurfaceH2B_Alive[c];	StackH2B_Alive	= StackH2B_Alive 	+ Add;
				Add = Weight * ArraySurfaceH2B_Dead[c] ;	StackH2B_Dead 	= StackH2B_Dead 	+ Add;
			}															

		WeightsArrayString=""; WeightCodeArrayString=""; Comma=", "; 
		for(c=0;c<nPlanes;c++){
			if(c==nPlanes-1){Comma="";} 	
			Decimals=0; if(WeightsArray[c] != floor(WeightsArray[c])){Decimals=1;}
			WeightsArrayString = WeightsArrayString + d2s(WeightsArray[c],Decimals) + Comma;

			WeightCodeArrayString = WeightCodeArrayString + WeightCodeArray[c] + Comma;
		}
		WeightsArrayStringArray[j] 	= WeightsArrayString;		
		WeightCodeArrayStringArray[j] 	= WeightCodeArrayString;	
		print("PRINTING THE WEIGHTS !!!!  for j="+j); print("length array : "+WeightsArray.length); print("SumWeights :"+SumWeights); Array.print(WeightsArray); print("WeightCode :");Array.print(WeightCodeArray); print("WeightsArrayString : __"+WeightsArrayString); print("WeightCodeArrayString : __"+WeightCodeArrayString); selectWindow("Log");	// waitForUser("kijk naar de WeightsArray in de LOG");

		//  getallen afronden
		if(AllowManipulationArray[j] != 0){	StackH2B 	= AllowManipulationArray[j] * StackH2B ; 	}		StackH2B 		= floor(StackH2B);			
		if(AllowManipulationArray[j] != 0){	StackH2B_Alive 	= AllowManipulationArray[j] * StackH2B_Alive; 	}		StackH2B_Alive 		= floor(StackH2B_Alive);		
		if(AllowManipulationArray[j] != 0){	StackH2B_Dead 	= AllowManipulationArray[j] * StackH2B_Dead; 	}		StackH2B_Dead 		= floor(StackH2B_Dead);			
																	StackPercentageAlive 	= 100*(StackH2B_Alive/StackH2B);

		// and fill the arrays for later FunctionSaveRawData
		Pos = i*nTimePoints + j;
		ArrayOrganoidnPlanes[Pos]	 	= nPlanes;
		ArrayOrganoidnRealSlices[Pos]	 	= ArraynRealSlices[j];
		ArrayOrganoidH2B_Total[Pos] 	  	= StackH2B;
		ArrayOrganoidH2B_Alive[Pos] 	  	= StackH2B_Alive;
		ArrayOrganoidH2B_Dead [Pos] 	  	= StackH2B_Dead;
		ArrayOrganoidPercentageAlive[Pos] 	= StackPercentageAlive;
		ArrayWeightsArrayString[Pos] 		= WeightsArrayString;
		ArrayWeightCodeArrayString[Pos] 	= WeightCodeArrayString;
		ArraySumWeights[Pos] 			= SumWeights;
		ArrayReversed[Pos] 			= Reversed[j];
		ArrayMarkMiddle[Pos]			= MarkMiddleArray[j];
		ArrayAllowManipulation[Pos]		= AllowManipulationArray[j];

		
		run("Images to Stack", "method=[Copy (top-left)] name=[ROI_"+i+1+"_H2B dead or alive (stack)] title=[dead or alive] use"); GreenRedStack=getTitle();
		selectWindow(H2B_ROI);close();
		// and save
		selectWindow(GreenRedStack);
		run("Colors...", "foreground=magenta"); F= getWidth() /12; 
		for(c=0;c<nPlanes;c++){
			TheSlice=1+c; setSlice(TheSlice);  
			W=WeightsArray[c]; Decimals=0; if(W!=floor(W)){Decimals=1;} Text=d2s(W, Decimals);
			run("Label...", "format=Text x="+0.5*F+" y="+1.5*F+" font="+F+" text="+Text+" range="+TheSlice+"-"+TheSlice);									// waitForUser("run(Label...__c__"+c);
		}
		Zero=""; if(i<10){Zero="0";}  saveAs("Tiff", DumpLocation + "GREEN-RED "+Date+"_"+Tumor+"_"+Drug+"__"+ArrayTimePoints[j]+"_ROI#"+i+1+".tif"); close();

	} // vd for(j=0;j<nTimePoints;j++)
	
	} // vd if(SkipThisOrganoid)
	FunctionSaveRawData();

	BeginROI=toString(i+1);	File.saveString(BeginROI, DumpLocation+"BeginROI.txt");	

} // vd for(i=0;i<nROIs;i++)


run("Close All");


	Line0 = "DONE !!  \n \n \n \n \n \n";
	Line1 = "Raw data are written away in xls format   -->  Check D/ANALYSIS DUMP/RESULTS Drug & Release  \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 = "Output file lists the measured surfaces for dead and alive H2B (and their ratios), for all separate organoids (vertically : ROI1 - ROI(last)) \n";
	
	print(""); waitForUser(Line0 + Line1 + Line2 + Line3 + Line4 + Line5 + Line6 ); print("");


exit("that was it");
 
//////    END
//////    END
//////    END






testFunctionSaveRawData=1;	FunctionSaveRawData();


	


//						FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//						FUNCTIONS




function MeasureSurface(Title){
	selectWindow(Title);	
	setAutoThreshold("Default");	
	run("Measure"); Area[k] = getResult("Area", nResults-1);
	resetThreshold();
}


function RemoveParticlesFromH2B (Binary , H2B){
	selectWindow(Binary);																								 
	run("Measure"); MeasureBinary = getResult("Area", nResults-1); 
	if(MeasureBinary==0){																						
		selectWindow(H2B); run("Select All"); 	run("Set...", "value=NaN");
	}else{
		setAutoThreshold("Default");		run("Create Selection");
		selectWindow(H2B);			run("Restore Selection");																		
		run("Make Inverse");																						
		run("Set...", "value=NaN");  		run("glow");  run("Select None");	
		selectWindow(Binary);			run("Select None");
	}																							
}


		

function MarkDeadParticles (WindowToDraw1 , WindowToDraw2 , BinaryToAdapt , OutputName){
	
	MarkedDeadParticles=0;
	
	run("Synchronize Windows");																						print("3.1");
	Zoom(WindowToDraw1, "Left", "" , 0);
	Zoom(WindowToDraw2, "Right" , WindowToDraw1 , 0);
	if(isOpen("Synchronize Windows")){					getLocationAndSize(x, y, width, height); selectWindow("Synchronize Windows"); 	setLocation(x+width+10 , y+0.4*height);			}
	if(isOpen("AllDead")){		selectWindow(WindowToDraw1);		getLocationAndSize(x, y, width, height); selectWindow("AllDead"); 		setLocation(x+ 0.75*width - 0.5*getWidth , y+height - MarginToDuckBehind);	run("Select None");}
	if(isOpen("DrawLiving")){	selectWindow(WindowToDraw1);		getLocationAndSize(x, y, width, height); selectWindow("DrawLiving"); 		setLocation(x+0.1*width - 0.1*getWidth , y+height - MarginToDuckBehind);	 run("Select None"); }


	if(isOpen("Enhanced H2B")){	selectWindow("Enhanced H2B"); 												setLocation(screenWidth,1);				}
	if(isOpen("Enhanced H2B_#2")){	selectWindow("Enhanced H2B_#2"); 											setLocation(screenWidth,1);				}
	
	selectWindow(WindowToDraw2); run("The Real Glow");																			print("3.15");
	Continue=1; ArrayDeadROIs=newArray(0); New=newArray(1); nROIsStart=roiManager("count"); run("Line Width...", "line=1");
	selectWindow(WindowToDraw1); 
	DrawLiving=0; One=1;
	while(Continue){																							print("3.2");
		if(DrawLiving==0){waitForUser(" draw around DEAD particles / fragmented nuclei     (in any of the 2 windows) \n \n use shift for multiple ROIs at the same time \n \n             TO CONTINUE, select nothing");}
		if(DrawLiving==1){waitForUser(" OK, allocate ALIVE H2B  \n \n use shift for multiple ROIs at the same time \n \n             TO CONTINUE, select nothing");}
		currentID=getImageID();
		Temp=getTitle(); 	if(Temp=="AllDead"){	Continue=0; selectWindow(WindowToDraw2); run("Select All");} 
					if(Temp=="DrawLiving"){	DrawLiving=1; print(""); if(One){waitForUser(" OK, allocate ALIVE H2B  \n \n use shift for multiple ROIs at the same time \n \n             TO CONTINUE, select nothing");One=0; } }

			if(selectionType!=-1){
				New[0] = nROIsStart + ArrayDeadROIs.length -1 +1 ; ArrayDeadROIs = Array.concat(ArrayDeadROIs, New); 
				if(DrawLiving){run("Make Inverse");}
				roiManager("Add");  
				selectWindow(WindowToDraw1); roiManager("Select",New[0]); run("Draw"); run("Select None");
				selectWindow(WindowToDraw2); roiManager("Select",New[0]); run("Draw"); run("Select None");												print("3.3");
			}
			else{Continue=0;}
		selectImage(currentID); run("Select None");
	}
	nSelections=ArrayDeadROIs.length;
	if(nSelections==1){	roiManager("Select",nROIsStart); 		roiManager("Rename","Dead cells");												}
	if(nSelections >1){	roiManager("Select",ArrayDeadROIs); 		if(DrawLiving==0){roiManager("OR");}
										if(DrawLiving==1){roiManager("AND");}		roiManager("Add"); 									print("*");Array.print(ArrayDeadROIs);	// waitForUser("AND ????  2222  ");
				roiManager("Select",ArrayDeadROIs); 		roiManager("Delete");
				roiManager("Select",nROIsStart);		roiManager("Rename","Dead cells"); 
	}
	if(nSelections>0){	
		selectWindow(BinaryToAdapt);	roiManager("Select",nROIsStart);	run("Set...", "value=0");	run("Select None");	
		rename(OutputName);
		MarkedDeadParticles=1;
	}else{selectWindow(BinaryToAdapt); rename(OutputName);}

	selectWindow("AllDead"); 	run("Select None");	setLocation(screenWidth, 1);
	selectWindow("DrawLiving"); 	run("Select None");	setLocation(screenWidth, 1);
	selectImage(currentID); 																						
	selectWindow(WindowToDraw1); close();
	selectWindow(WindowToDraw2); close();
																									
	return MarkedDeadParticles;
}


function DoPrepare () {

	File.makeDirectory(FixedDump);
	File.makeDirectory(OutputDump);

	run("Close All");
	if(isOpen("Results"))			 {selectWindow("Results");		 run("Close");}
	if(isOpen("B&C"))			 {selectWindow("B&C");			 run("Close");}
	if(isOpen("Synchronize Windows"))	 {selectWindow("Synchronize Windows");	run("Close");}
	if(isOpen("Threshold"))			 {selectWindow("Threshold");		 run("Close");}
	if(isOpen("ROI Manager"))		 {selectWindow("ROI Manager");		 run("Close");}
	if(isOpen("Log"))			 {selectWindow("Log");			 run("Close");}
	
	run("Colors...", "selection=magenta");
	run("Colors...", "foreground=magenta");
	setTool("freehand");
	setTool("rectangle");
	run("Set Measurements...", "area limit redirect=None decimal=1");
	run("Line Width...", "line=3");
	print("");
}


function AdaptROIs(k){
	TimePoint=ArrayTimePoints[k];																								

	selectWindow(Transm); 	run("Duplicate...", "title=[Compare with previous ROI (yellow) and set new ROI (magenta)]"); a=getTitle();
	selectWindow(a);	run("RGB Color");						Zoom(a , "Left"  , "" , 0);		
	open(DumpLocation+"ROI Landscape ("+ArrayTimePoints[j+1]+").tif");	b=getTitle();	Zoom(b , "Right" , a , 0);
	selectWindow(a);
	run("ROI Manager..."); 
	roiManager("Open", FixedDump+"RoiSet Drug&Release_("+ArrayTimePoints[j+1]+").zip");
																									
	TotalnROIs=roiManager("count");
																									
	for(i=0;i<TotalnROIs;i++){

		setOption("Show All", 0); roiManager("Label");																				
		run("Colors...", "foreground=yellow"); run("Line Width...", "line=4");
		selectWindow(b);	roiManager("Select",i);  run("Draw"); run("Select None"); 
		selectWindow(a);	roiManager("Select",i);  run("Draw"); 
		// XY-shift
		getSelectionBounds(x, y, width, height); run("Select None"); makeRectangle(x+xShift, y+yShift, width, height);
			run("Colors...", "selection=red");
			if(SetStandardRectangless && k==2){makeRectangle(1276, 2052, 300, 296);}
			if(SetStandardRectangless && k==1){makeRectangle(1496, 1940, 268, 308);}
			if(SetStandardRectangless && k==0){makeRectangle(1564, 2296, 252, 264);}
			
			waitForUser("adapt the selections that you have made earlier \n \n #"+i+1+" of "+TotalnROIs+" ROIs ");
			run("Colors...", "selection=magenta");
		roiManager("Add"); 
		//
		run("Colors...", "foreground=green");
		selectWindow(b);	roiManager("Select",i);  run("Draw");
		selectWindow(a);	roiManager("Select",i);  run("Draw");		
	}
	ArrayROI=newArray(TotalnROIs); 
	for(k=0;k<TotalnROIs;k++){ArrayROI[k]=k;} roiManager("Select", ArrayROI); roiManager("Delete");	
	for(k=0;k<TotalnROIs;k++){roiManager("Select",k); roiManager("Rename","#"+k+1 + "_(T"+j+1+")");}
	selectWindow(Transm); run("Select None");
	selectWindow(a); close();																					print("function ADAPT ROI - c");
	selectWindow(b); close();

	// and nicely  save
	roiManager("Save", DumpLocation+"RoiSet Drug&Release_("+TimePoint+").zip");
	run("Line Width...", "line=1"); 
}


function Zoom(Title, Place, WhichIsLeft, Four){
	xFraction = 0.5 ;	if(Four){xFraction = 0.25 ;}
	yFraction = 0.77 ;

	selectWindow(Title); run("View 100%"); setLocation(1,1);
	//
	XZoomForDrawing = 100*(xFraction *screenWidth/getWidth);
	YZoomForDrawing = 100*(yFraction *screenHeight/getHeight);
	ZoomForDrawing  = minOf(XZoomForDrawing, YZoomForDrawing);				
	//
	Zooms = newArray(16.7, 25,33.3, 50,75,100,150,200,300,400,600,800,1200,1600);
	i=0;  while(ZoomForDrawing>Zooms[i]){i=i+1;}																
	//
	Z="";nTimes=0;
	if(Zooms[i]<100){Z="Out [-]"; nTimes = 5-i;}	// because 100 is at position 5 in the array
	if(Zooms[i]>100){Z="In [+]";  nTimes = i-5;}
	for(j=0;j<nTimes;j++){run(Z);}

	run("Set... ", "zoom="+ZoomForDrawing); 
	run("Out [-]");
	
	if(Place=="Left" ){selectWindow(Title); setLocation(1,1);}
	if(Place=="Right"){selectWindow(WhichIsLeft); getLocationAndSize(x, y, width, height); selectWindow(Title); setLocation(x+width+10,1);}
}
 



function MakeGreenForMerge(Title){
	selectWindow(Title); 
	run("8-bit");  run("Enhance Contrast", "saturated=0.35");
	run("RGB Color"); run("8-bit Color", "number=256");
	run("Green");	run("Enhance Contrast", "saturated=0.35"); selectWindow("B&C"); 
	selectWindow(Title); setLocation(0.5*(screenWidth-(getWidth*getZoom)) , 0.5*(screenHeight-(getHeight*getZoom)));
	selectWindow(Title);  run("RGB Color"); 
	saveAs("Tiff", FixedDump+"GREEN (time point "+j+" of "+nTimePoints+").tif");
	close();
}




function ShuffleWindows(i){
	selectWindow(ArrayTransm[j]); a=getTitle(); Zoom(a, "Left", "" , 0); 
	ZoomFactor = getZoom();
	
	for(j=0;j<nTimePoints;j++){
		if(j!=i){	selectWindow(ArrayTransm[j]); 	run("View 100%");	setLocation(0.95*screenWidth 	, 1);		run("Set... ", "zoom="+100*ZoomFactor);	
				selectWindow(ArrayH2B[j]);	run("View 100%");	setLocation(0.95*screenWidth 	, 1);		run("Set... ", "zoom="+100*ZoomFactor);
		}else{		selectWindow(ArrayTransm[j]); 	run("View 100%");	setLocation(1		 	, 1);		run("Set... ", "zoom="+100*ZoomFactor);		b=getTitle();
				selectWindow(ArrayH2B[j]);	run("View 100%"); 	a=getTitle();	Zoom(a, "Right", b , 0);	run("Set... ", "zoom="+100*ZoomFactor);
		}
	}
}




function FunctionSaveRawData(){																		print("FunctionSaveRawData   ");

	SaveRawDataName = "Drug & Release (raw data) "+Date+"_"+Tumor+"_"+Drug;
		
	ArrayHeader1String 	= newArray(101); 		
	ArrayHeader2String 	= newArray(101); 	
	ArrayForPrintString  	= newArray(101);		Array.fill(ArrayForPrintString , 777);
	PrintStringArray 	= newArray(nROIs + 101);	for(y=0;y<PrintStringArray.length;y++){PrintStringArray[y]="";}

	if(nTimePoints>0)	{T1 = ArrayTimePoints[0];}
	if(nTimePoints>1)	{T2 = ArrayTimePoints[1];}
	if(nTimePoints>2)	{T3 = ArrayTimePoints[2];}
	if(nTimePoints>3)	{T4 = ArrayTimePoints[3];}
	if(nTimePoints>4)	{T5 = ArrayTimePoints[4];}																			


	for(p=0;p<nROIs;p++){																							
	
	nLines=0;
	//   first 5 lines  (line 6 will be Header)
	PrintStringArray[nLines] = SaveRawDataName;							nLines=nLines+1;
	PrintStringArray[nLines] = "Date " + Separator +Date;						nLines=nLines+1;
	PrintStringArray[nLines] = "Tumor "+ Separator +Tumor;						nLines=nLines+1;
	PrintStringArray[nLines] = "Drug " + Separator +Drug;						nLines=nLines+1;
	PrintStringArray[nLines] = "";									nLines=nLines+1;
	PrintStringArray[nLines] = "";									nLines=nLines+1;

		// p is loopnummer (ROI1 , ROI2 , etc)
		// Pos is plaats in Arrays ArrayOrganoidH2B_Total etc	
			// die waren ingevuld als : Pos = i*nTimePoints + j;
				// i being ROI  ;  j being TP
		Pos 	= p*nTimePoints;	// en niet " i*nTimePoints + j " zoals je zou verwachten want we moeten iedere keer alles schrijven ; anders werkt het niet met de nColumns ; en dus iedere keer +1 , en +2 en +3 etc achter de array-Pos gezet
		nT 	= nTimePoints;
		iString	= toString(p+1);  //   want p is in deze loop de ROI																					print("FunctionSaveRawData  1 ");
			Skip=0; WriteWhite=0; WW=0; 
			AliveNorm1=""; AliveNorm2=""; AliveNorm3=""; AliveNorm4=""; AliveNorm5="";
			DeadNorm1="";  DeadNorm2="";  DeadNorm3="";  DeadNorm4="";  DeadNorm5="";
			if(ArraySkipAnalysis[p]==1){iString	= iString + " (skipped)"; 	Skip=1;}
			if(ArrayAnalyzedROIs[p]==0){iString	= iString + " (not analyzed)"; 	WriteWhite=1; WW=1;}
			
		
		//  
		c = 0 ;		//  c staat voor de kolommen
		x = "";

			if(p==0){ArrayHeader1String[c]="";			ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	

		c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="ROI ";}	ArrayForPrintString[c] = " #"+iString;		//  i = de ROI number	

	
	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="H2B alive (um^2)";	ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Alive[Pos]);				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}	if(Skip==0){N=ArrayOrganoidH2B_Alive[Pos];	AN1=100*(ArrayOrganoidH2B_Alive[Pos  ]/N);	AliveNorm1 =  toString(AN1); if(AliveNorm1=="NaN"){AliveNorm1="";}	DN1=100*(ArrayOrganoidH2B_Dead[Pos  ]/N);	DeadNorm1 =  toString(DN1); if(DeadNorm1=="NaN"){DeadNorm1="";}	/*print(""); waitForUser("2_____AliveNorm1 "+AliveNorm1);*/	}	if(WW){ArrayForPrintString[c]="";	}}
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "_"+x	 ;		ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Alive[Pos+1]);			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}	if(Skip==0){					AN2=100*(ArrayOrganoidH2B_Alive[Pos+1]/N);	AliveNorm2 =  toString(AN2); if(AliveNorm2=="NaN"){AliveNorm2="";}	DN2=100*(ArrayOrganoidH2B_Dead[Pos+1]/N);	DeadNorm2 =  toString(DN2); if(DeadNorm2=="NaN"){DeadNorm2="";}	/*print(""); waitForUser("3_____AliveNorm2 "+AliveNorm2);*/	}	if(WW){ArrayForPrintString[c]="";	}}
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Alive[Pos+2]);			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}	if(Skip==0){					AN3=100*(ArrayOrganoidH2B_Alive[Pos+2]/N);	AliveNorm3 =  toString(AN3); if(AliveNorm3=="NaN"){AliveNorm3="";}	DN3=100*(ArrayOrganoidH2B_Dead[Pos+2]/N);	DeadNorm3 =  toString(DN3); if(DeadNorm3=="NaN"){DeadNorm3="";}									}	if(WW){ArrayForPrintString[c]="";	}}
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Alive[Pos+3]);			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}	if(Skip==0){					AN4=100*(ArrayOrganoidH2B_Alive[Pos+3]/N);	AliveNorm4 =  toString(AN4); if(AliveNorm4=="NaN"){AliveNorm4="";}	DN4=100*(ArrayOrganoidH2B_Dead[Pos+3]/N);	DeadNorm4 =  toString(DN4); if(DeadNorm4=="NaN"){DeadNorm4="";}									}	if(WW){ArrayForPrintString[c]="";	}}
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Alive[Pos+4]);			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}	if(Skip==0){					AN5=100*(ArrayOrganoidH2B_Alive[Pos+4]/N);	AliveNorm5 =  toString(AN5); if(AliveNorm5=="NaN"){AliveNorm5="";}	DN5=100*(ArrayOrganoidH2B_Dead[Pos+4]/N);	DeadNorm5 =  toString(DN5); if(DeadNorm5=="NaN"){DeadNorm5="";}									}	if(WW){ArrayForPrintString[c]="";	}}
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
	
	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="H2B alive (norm.)";	ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = AliveNorm1;							if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}}	
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "_"+x	 ;		ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = AliveNorm2;							if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}}
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = AliveNorm3;							if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}}
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = AliveNorm4;							if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}}
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = AliveNorm5;							if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}}
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
	
	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="%age alive";		ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidPercentageAlive[Pos  ]));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}	
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "_"+x	 ;		ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidPercentageAlive[Pos+1]));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidPercentageAlive[Pos+2]));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidPercentageAlive[Pos+3]));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidPercentageAlive[Pos+4]));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	

	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="H2B dead (norm.)";	ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = DeadNorm1;							if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}}	
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "_"+x	 ;		ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = DeadNorm2;							if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}}
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = DeadNorm3;							if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}}
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = DeadNorm4;							if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}}
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = DeadNorm5;							if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}}
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
	
	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="H2B dead (um^2)";	ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Dead[Pos]);				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}	
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "_"+x	 ;		ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Dead[Pos+1]);			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Dead[Pos+2]);			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Dead[Pos+3]);			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Dead[Pos+4]);			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
	
	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="H2B total (um^2)";	ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Total[Pos  ]);			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}	
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "_"+x	 ;		ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Total[Pos+1]);			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Total[Pos+2]);			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Total[Pos+3]);			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = toString(ArrayOrganoidH2B_Total[Pos+4]);			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
	
	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="# real planes";		ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidnRealSlices[Pos  ]));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}		a1=ArrayOrganoidnRealSlices[Pos  ];			if(WW){ArrayForPrintString[c]="";	}}
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "_"+x	 ;		ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidnRealSlices[Pos+1]));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}		a2=ArrayOrganoidnRealSlices[Pos+1];			if(WW){ArrayForPrintString[c]="";	}}
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidnRealSlices[Pos+2]));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}		a3=ArrayOrganoidnRealSlices[Pos+2];			if(WW){ArrayForPrintString[c]="";	}}
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidnRealSlices[Pos+3]));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}		a4=ArrayOrganoidnRealSlices[Pos+3];			if(WW){ArrayForPrintString[c]="";	}}
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidnRealSlices[Pos+4]));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}		a5=ArrayOrganoidnRealSlices[Pos+4];			if(WW){ArrayForPrintString[c]="";	}}
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
	
	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="# planes analyzed";	ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidnPlanes[Pos  ]));			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}	
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "_"+x	 ;		ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidnPlanes[Pos+1]));			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidnPlanes[Pos+2]));			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidnPlanes[Pos+3]));			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = toString(round(ArrayOrganoidnPlanes[Pos+4]));			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="sum of weights";	ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = toString(ArraySumWeights[Pos  ]);				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}		b1=ArraySumWeights[Pos  ];	Ratio1 = b1/a1;		if(WW){ArrayForPrintString[c]="";	}}	
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "_"+x	 ;		ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = toString(ArraySumWeights[Pos+1]);				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}		b2=ArraySumWeights[Pos+1];	Ratio2 = b2/a2;		if(WW){ArrayForPrintString[c]="";	}}
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = toString(ArraySumWeights[Pos+2]);				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}		b3=ArraySumWeights[Pos+2];	Ratio3 = b3/a3;		if(WW){ArrayForPrintString[c]="";	}}
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = toString(ArraySumWeights[Pos+3]);				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}		b4=ArraySumWeights[Pos+3];	Ratio4 = b4/a4;		if(WW){ArrayForPrintString[c]="";	}}
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = toString(ArraySumWeights[Pos+4]);				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}		b5=ArraySumWeights[Pos+4];	Ratio5 = b5/a5;		if(WW){ArrayForPrintString[c]="";	}}
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
			
	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="Ratio check";		ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = toString(Ratio1);						if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}	
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "MOET 0.5 ZIJN !!"+x ;	ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = toString(Ratio2);						if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = toString(Ratio3);						if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = toString(Ratio4);						if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = toString(Ratio5);						if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
			
	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="Mark Middle";		ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = toString(round(ArrayMarkMiddle[Pos  ]));			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}	
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "_"+x	 ;		ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = toString(round(ArrayMarkMiddle[Pos+1]));			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = toString(round(ArrayMarkMiddle[Pos+2]));			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = toString(round(ArrayMarkMiddle[Pos+3]));			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = toString(round(ArrayMarkMiddle[Pos+4]));			if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
	
	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="weight arrays";		ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = ArrayWeightsArrayString[Pos  ];				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}	
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "_"+x	 ;		ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = ArrayWeightsArrayString[Pos+1];				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = ArrayWeightsArrayString[Pos+2];				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = ArrayWeightsArrayString[Pos+3];				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = ArrayWeightsArrayString[Pos+4];				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
	
	
	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="weight-code arrays";	ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = ArrayWeightCodeArrayString[Pos  ];				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}	
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "_"+x	 ;		ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = ArrayWeightCodeArrayString[Pos+1];				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = ArrayWeightCodeArrayString[Pos+2];				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = ArrayWeightCodeArrayString[Pos+3];				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = ArrayWeightCodeArrayString[Pos+4];				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
			
	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="Reverse";		ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = toString(round(ArrayReversed[Pos  ]));				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}	
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "_"+x	 ;		ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = toString(round(ArrayReversed[Pos+1]));				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = toString(round(ArrayReversed[Pos+2]));				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = toString(round(ArrayReversed[Pos+3]));				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = toString(round(ArrayReversed[Pos+4]));				if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}}
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
			
	if(nT>0){	c=c+1;	if(p==0){ArrayHeader1String[c]="Manipulate Size Factor";ArrayHeader2String[c]=T1;}	ArrayForPrintString[c] = toString(d2s(ArrayAllowManipulation[Pos  ],2));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}	if(ArrayAllowManipulation[Pos  ]==0){ArrayForPrintString[c]="";}}	
	if(nT>1){	c=c+1;	if(p==0){ArrayHeader1String[c]= "_"+x	 ;		ArrayHeader2String[c]=T2;}	ArrayForPrintString[c] = toString(d2s(ArrayAllowManipulation[Pos+1],2));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}	if(ArrayAllowManipulation[Pos+1]==0){ArrayForPrintString[c]="";}}	
	if(nT>2){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T3;}	ArrayForPrintString[c] = toString(d2s(ArrayAllowManipulation[Pos+2],2));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}	if(ArrayAllowManipulation[Pos+2]==0){ArrayForPrintString[c]="";}}	
	if(nT>3){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T4;}	ArrayForPrintString[c] = toString(d2s(ArrayAllowManipulation[Pos+3],2));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}	if(ArrayAllowManipulation[Pos+3]==0){ArrayForPrintString[c]="";}}	
	if(nT>4){	c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]=T5;}	ArrayForPrintString[c] = toString(d2s(ArrayAllowManipulation[Pos+4],2));		if(ArrayForPrintString[c]==777){ArrayForPrintString[c]="x";}	if(Skip){ArrayForPrintString[c]="";}									if(WW){ArrayForPrintString[c]="";	}	if(ArrayAllowManipulation[Pos+4]==0){ArrayForPrintString[c]="";}}									
	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
			c=c+1;	if(p==0){ArrayHeader1String[c]="        ";		ArrayHeader2String[c]="";}	ArrayForPrintString[c] = "";	
	
	
	
nColumns = c+1;
ArrayForPrintString  	= Array.trim(ArrayForPrintString,nColumns); 
ArrayHeader1String 	= Array.trim(ArrayHeader1String, nColumns);
ArrayHeader2String 	= Array.trim(ArrayHeader2String, nColumns); 
																								print("FunctionSaveRawData 3  _______nColumns_: "+nColumns);
																								print(" **** ArrayHeader1String"); Array.print(ArrayHeader1String);
																								print(" **** ArrayHeader2String"); Array.print(ArrayHeader2String);
																								print(" **** ArrayForPrintString"); Array.print(ArrayForPrintString); 														// waitForUser("printed stuff");
		// build the HeaderStrings (HeaderString1 & HeaderString2) and put in the PrintStringArray
				HeaderString1 = "   ";																	
					for(k=1 ; k<nColumns ; k++){HeaderString1 = HeaderString1 + Separator + ArrayHeader1String[k];}							
					PrintStringArray[nLines] = HeaderString1;
				HeaderString2 = "   ";
					for(k=1 ; k<nColumns ; k++){HeaderString2 = HeaderString2 + Separator + ArrayHeader2String[k];}
					PrintStringArray[nLines+1] = HeaderString2;
		
		nLines=nLines+1+1;
		// build the PrintString and put in the PrintStringArray
		PrintString = " ";																				
			for(k=1 ; k<nColumns ; k++){PrintString = PrintString + Separator + ArrayForPrintString[k];}									
			PrintStringArray[p+nLines] = PrintString;
	} // vd for(p , ROIs)
																							
Analysis_Output = PrintStringArray;
Array.show(Analysis_Output); selectWindow("Analysis_Output"); setLocation(1, 1);
IJ.renameResults(SaveRawDataName);
	// problems with overwriting?
	ContinueChangingFileName = 1;
	while(ContinueChangingFileName){
		ContinueChangingFileName = 0 ;
		XlsAlreadySavedWithThisName 	= File.exists(DumpLocation + SaveRawDataName+".xls");
		if(XlsAlreadySavedWithThisName){
			SaveRawDataName = SaveRawDataName + "_"; 
			ContinueChangingFileName = 1 ;
		}
	}																							print("FunctionSaveRawData 5  ");
saveAs("Results", DumpLocation + SaveRawDataName+".xls");	run("Close");															print("FunctionSaveRawData 6  ");


			//	FYI : 
			//	} // vd for(j=0;j<nTimePoints;j++)
			//	} // vd for(i=0;i<nROIs;i++)


}  //  vd SaveRawDataFunction



function SaveROIs(){ 		
	roiManager("Save", FixedDump+"RoiSet Drug&Release_("+ArrayTimePoints[j]+").zip");
	roiManager("Save", DumpLocation+"RoiSet Drug&Release_("+ArrayTimePoints[j]+").zip");
	roiManager("Deselect");
}

//continue working 
function unzoom25 (){ 
	i=1; 
	do{
	run("Out"); 
	i++; 
	}while(i<25); 
}
