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




























//  first we have to know whether the required directories exist 
Mac=0; FileSeparator = File.separator; if(FileSeparator=="/"){Dialog.create(" "); Dialog.addCheckbox("Running on a Mac ?", 1); Dialog.show(); Mac = Dialog.getCheckbox();}else{print("this is a PC");}
FileSeparator = FileSeparator + FileSeparator;	


DoPrepare();


//  first we have to know whether the required directories exist 
Disk				= "D:";
DumpLocation			=  Disk+FileSeparator+"ANALYSIS DUMP"+FileSeparator;
ResultDump			= "ScoreEvents RESULTS"+FileSeparator;
SettingsDump			= "ScoreEvents Settings"+FileSeparator;
BackupDump			= "Backup"+FileSeparator;
FateTrackSettingsDump		= DumpLocation + "FateTrack Settings"+FileSeparator;

//  if not, create them
if(Mac){
	newImage("set file path", "RGB black", 200, 100, 1);
	waitForUser("set file path");
	saveAs("Tiff");		PathMac=File.directory(); 
	Disk		= "";
	DumpLocation	= PathMac+FileSeparator+"ANALYSIS DUMP"+FileSeparator;					
	selectWindow("set file path.tif"); close();
}

FixSaveDirectories ();											


//  DIM THE PARAMETERS   ;  Don't touch
//  DIM THE PARAMETERS   ;  Don't touch
	Separator 	= "; ";
	Blank		= "";

	ObservedEvent = Blank;
	Slice = Blank;
	x = Blank; 
	y = Blank;
	
	MitosisRemark 			= Blank;
	DiscardPreviousEvent		= 0 ;
	DiscardPreviousEventNoSelection = 0 ;
	PreviousEvent	 		= Blank;




///  Retrieve stored parameters
///  Retrieve stored parameters
if(File.exists(DumpLocation + SettingsDump +"ImageForParametersAndSettings(ScoreEvents).tif")){
print("Parameters & settings from the stored file:");					ParameterFile = 1 ;
open(DumpLocation + SettingsDump +"ImageForParametersAndSettings(ScoreEvents).tif"); 	TempName = getTitle();	
info = getMetadata("info");
List.setList(info);  		List.getList;
	ExperimentName		=  List.get("ExperimentName");
  	PosNumber 		=  List.get("PosNumber");
	TimeInterval		=  List.get("TimeInterval");
  	MarkSize 		=  List.get("MarkSize");
	TextSize		=  List.get("TextSize");
  	DrawInXFrames 		=  List.get("DrawInXFrames");	
	WriteNumbers		=  List.get("WriteNumbers");
	AddChronologicalData	=  List.get("AddChronologicalData");
	DoubleImage		=  List.get("DoubleImage");
	SaveAnnotatedMovie	=  List.get("SaveAnnotatedMovie");
	ExpDate			=  List.get("ExpDate");
	OrgLine			=  List.get("OrgLine");
	EditImageTitle		=  List.get("EditImageTitle");	
	selectWindow(TempName); close();
}
else	{waitForUser("die file bestaat dus nog niet");	print("die file bestaat dus nog niet");	ParameterFile = 0 ;
	ExperimentName		=  "";
  	PosNumber 		=  1 ;
  	TimeInterval		=  10 ;
  	DrawInXFrames		=  5 ;
	MarkSize 		=  10 ;		
  	TextSize		=  20 ;	
  	Linking			=  0 ;
  	AddChronologicalData	=  0 ;
  	DoubleImage		=  1 ;
  	SaveAnnotatedMovie	= "Save to ScoreEvents Result-dump";
	ExpDate			= "151515"; 
	OrgLine			= "p9T"; 
	EditImageTitle		= 0;
}

if(ExpDate==""){	ExpDate="151515";}
if(OrgLine==""){	OrgLine="p9T";}
WaitTimeOrderWindows	= 30 ;


EventOptionsArray = newArray("Mitosis", "Apoptosis");
EventOptionsFill = EventOptionsArray[0];
PrintStringsToLog = 1 ;

/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////

//  CHECKBOX : Split VIERLUIK in 2 ?
	  Dialog.create("");	Shift=15;
	  Dialog.setInsets(0, 10,0); Dialog.addCheckbox("Open from file  ???" , 1);
	  Dialog.setInsets(20,10,0); Dialog.addCheckbox("Crop manually ??"  , 1);
		  Dialog.show();
	  Opening  = Dialog.getCheckbox();
	  Cropping = Dialog.getCheckbox();
	  ChopnImages = 1;   WithMargin = 1 ;  FractionForMargin = 0.07;  AdjustSelection = 1;


//  OPENING & NAMING /// 
//  OPENING & NAMING /// 
if(Opening==1){  run("Close All"); waitForUser("advise : open using virtual stack"); 	print("");	open();}	else {setTool("rectangle"); waitForUser("Select window for analysis");	print("");	}	
ImageTitle = getTitle;	print("ImageTitle : "+ImageTitle);
if(Cropping==1){selectWindow(ImageTitle); 	getDimensions(xImage, yImage, dummy, NumberOfTimepoints, dummy);	
	if(WithMargin){Fraction=(ChopnImages+FractionForMargin)/((1+ChopnImages)+FractionForMargin);}else{Fraction=ChopnImages/(1+ChopnImages);}		
	makeRectangle(0, 0, xImage, Fraction*yImage);	
	if(AdjustSelection){ setTool("rectangle");  print(""); waitForUser("adjust the selection manually?"); print(""); setTool("point"); }
	run("Crop");
	}


//  ORDER WINDOWS
selectWindow(ImageTitle); run("View 100%"); run("Select None");
ZoomFactorHorizontal 	= 0.9*screenWidth/getWidth;
ZoomFactorVertical 	= 0.9*screenHeight/getHeight;
ZoomFactor		= minOf(ZoomFactorHorizontal , ZoomFactorVertical);		
ZoomFactor 		= ZoomFactor*100;

	XLocationMin=10; YLocationMin=10; XLocationStep=0;YLocationMax=2; YLocationMin=1; YWindowFraction=0; 		
	setLocation(1,1); PopUp(ImageTitle  , ZoomFactor , 100);	





				
getLocationAndSize(dummy, dummy, RealWindowWidth, RealWindowHeight);			print("RealWindowWidth : "+RealWindowWidth); 
run("ROI Manager..."); 	selectWindow("ROI Manager"); setLocation(RealWindowWidth+5 , 1);

TotalNumberOfROIs = roiManager("count"); if(TotalNumberOfROIs > 0){roiManager("Deselect"); roiManager("Delete");} 
TotalNumberOfROIs = 0;
//
	

//  Starting DIALOG
if(ExperimentName==""){ExperimentName=ImageTitle;}
	Dialog.create(" ");		Dialog.addString("Experiment name ?", ExperimentName, 45); 
	Dialog.setInsets(-6, 160,0);	Dialog.addCheckbox("Edit Image title as Experiment Name ?", EditImageTitle);
	Dialog.setInsets(0, 0,0);	Dialog.addMessage(""); 
	Dialog.setInsets(0, 0,0);	Dialog.addString("Date Experiment", ExpDate, 10); 
	Dialog.setInsets(0, 0,0);	Dialog.addString("Organoid Line", OrgLine, 10); 
	Dialog.setInsets(0, 0,0);	Dialog.addNumber("Position number", PosNumber, 0 , 7 , ""); 
	Dialog.setInsets(3, 0,0);	Dialog.addNumber("Time Interval  (in minutes) ", TimeInterval, 0, 7, "min"); 
	Dialog.setInsets(0, 160,0);	Dialog.addCheckbox("Double Image", DoubleImage);
	Dialog.setInsets(40, 0,0);	Dialog.addNumber("Mark size", MarkSize, 0 , 4 , ""); 
	Dialog.setInsets(10, 0,0);	Dialog.addNumber("Text size", TextSize, 0 , 4 , ""); 
	Dialog.setInsets(5, 160,0);	Dialog.addCheckbox("Test Mark Size & Text Size", 0);
	Dialog.setInsets(15, 0,0);	Dialog.addNumber("Draw mark in ", DrawInXFrames, 0 , 4 , " frames"); 
	Dialog.setInsets(25, 0,0); 	Dialog.addMessage("********************************************************************************************************************");
	Dialog.setInsets(5, 160,0); 	Dialog.addCheckbox("Retrieve backupped data first", 0);
		Dialog.show();
	ExperimentName  = Dialog.getString();
	EditImageTitle 	= Dialog.getCheckbox();
	ExpDate  	= Dialog.getString();			
	OrgLine  	= Dialog.getString();
	PosNumber  	= Dialog.getNumber();
	TimeInterval  	= Dialog.getNumber();
	DoubleImage 	= Dialog.getCheckbox();
	MarkSize  	= Dialog.getNumber();
	TextSize  	= Dialog.getNumber();
	TestMarkSize  	= Dialog.getCheckbox();
	DrawInXFrames  	= Dialog.getNumber();
	AddChronologicalData= 1;
	WriteNumbers	= 1;
	RetrieveBackuppedValues	= Dialog.getCheckbox();

ROISaveString = ExperimentName+"_Pos"+PosNumber+".roi.zip"; print("ROISaveString "+ROISaveString);

DateFolder = ExpDate+FileSeparator; 	
if(File.exists(DumpLocation + ResultDump + DateFolder)) 	{print("yep");}		else {print("ResultDump not found"); 	File.makeDirectory(DumpLocation + ResultDump + DateFolder);}	print("ResultDump exists ("+ResultDump+DateFolder+")");

/// 	end of DIALOG



if(EditImageTitle){
ImageTitleTemp = substring(ImageTitle, 0, lengthOf(ImageTitle)-4);	
Dialog.create(" "); Dialog.addMessage("OK, edit the name ... "); Dialog.addString("Experiment name ?", ImageTitleTemp, 60); Dialog.show();ExperimentName  = Dialog.getString();
selectWindow(ImageTitle); rename(ExperimentName);
ImageTitle = ExperimentName;
}


// test and maybe REDEFINE the MarkSize and TextSize ??
if(TestMarkSize){
	CreateWindowToTestMarkSize ();
	//  DIALOG - again
	Dialog.create(" ");	Dialog.addNumber("Mark size", MarkSize, 0 , 4 , ""); 	Dialog.addNumber("Text size", TextSize, 0 , 4 , ""); 	Dialog.show();	MarkSize  = Dialog.getNumber();	TextSize  = Dialog.getNumber();		
	selectWindow("Test Mark Size"); close();
}

WriteAwayParameters();
			
//  Draw Framenumbers in the top middle
if(WriteNumbers){DrawFrameNumbers(ImageTitle);}



/////////////////////////////////////////////////////////////////////////////////////////////////////////
NumberOfRetrievedROIs = 0;
if(RetrieveBackuppedValues){
	Path = DumpLocation + SettingsDump + BackupDump ;								
	
	NumberOfRetrievedROIs 	= RetrieveLastFromArray("TotalNumberOfROIs");						
	//  the output-data
	EventArray 		= Retrieve ("EventArray");
	FrameNumberArray 	= Retrieve ("FrameNumberArray");							
	FrameNumberStringArray 	= Retrieve ("FrameNumberStringArray");
	XCoordinateArray 	= Retrieve ("XCoordinateArray");
	YCoordinateArray 	= Retrieve ("YCoordinateArray");
	MitosisRemarkArray 	= Retrieve ("MitosisRemarkArray");
	// and the totals
	CountMitoses 		= RetrieveLastFromArray("CountMitoses");	
	CountApoptoses 		= RetrieveLastFromArray("CountApoptoses");						



	// restore those selections in the ROI manager
	setTool("point");
	for(i=0 ; i<NumberOfRetrievedROIs; i++){
		setSlice(parseFloat(FrameNumberArray[i]));
		makePoint(parseFloat(XCoordinateArray[i]), parseFloat(YCoordinateArray[i]));
		selectWindow("ROI Manager");	roiManager("Add"); roiManager("Select", i); 
			 if(indexOf(EventArray[i], "Mitosis") != -1) 		{EventinROIname="Mit "; }			 
			 if(indexOf(EventArray[i], "Apoptosis") != -1) 	{EventinROIname="Apo "; }			 
			 if(indexOf(EventArray[i], "Catastrophe") != -1) 	{EventinROIname="M.C."; }			 
		ROIName = "ROI#"+(i+1)+" ; "+EventinROIname+"; frame"+FrameNumberArray[i]+" ; (XY"+floor(XCoordinateArray[i])+","+floor(YCoordinateArray[i])+")";		roiManager("Rename", ROIName);
	}
	TotalNumberOfROIs = NumberOfRetrievedROIs;
	
	Array.print(EventArray);

}     //  vd if(RetrieveBackuppedValues)






//  THE LOOP  //  THE LOOP  //  THE LOOP  //  THE LOOP  //  THE LOOP  //  THE LOOP  //  THE LOOP
//  THE LOOP  //  THE LOOP  //  THE LOOP  //  THE LOOP  //  THE LOOP  //  THE LOOP  //  THE LOOP
ExtraString = ""; 


Continue=1;
while (Continue){
setTool("point"); run("Line Width...", "line=1");	print(""); print("LOOP STARTS");print("this will be event # : "+TotalNumberOfROIs+1); 


///  interrogate user 
	ShiftAtMarking=0;
	waitForUser("* MARK NEXT EVENT \n" + " \n" + "* study it   \n" + " \n " + ExtraString + "     (to finish --> select nothing)                          "); 
	if(isKeyDown("shift")){ShiftAtMarking=1; OldFill=EventOptionsFill ; EventOptionsFill = EventOptionsArray[1];}



SkipDataOutput 			= 0 ;
DiscardPreviousEvent 		= 0 ;   
DiscardPreviousEventNoSelection	= 0 ; 
PreviousEventDiscarded 		= 0 ; 
MovingMark			= 0 ;






// Store dimensions of the Selection
selectWindow(ImageTitle); getDimensions(xImage, yImage, dummy, NumberOfTimepoints, dummy); 	print("NumberOfTimepoints : "+NumberOfTimepoints);
Slice = getSliceNumber(); 									print("Slice number of the observed Event: "+Slice);
getSelectionBounds(x,y,dummy,dummy);

//  for in case the user forgot to click --> make sure Macro doesn't clog...
JumpBack=0;	
if(x==0 && y==0){
	Dialog.create("");		
	items = newArray("Oops... I clicked too fast", "All events marked, now FINISH !");	Dialog.addRadioButtonGroup("no selection...", items, 2, 1, "Oops... I clicked too fast");
 	if(TotalNumberOfROIs>0){
  	Dialog.setInsets(25, 20,0); 	Dialog.addCheckbox("Discard previous (i.e. Event_#"+TotalNumberOfROIs+" )", 0);}
		Dialog.show;
	ContinueString = Dialog.getRadioButton;	
		if(ContinueString=="Oops... I clicked too fast") 			{JumpBack=1; 	print("JUMP BACK !!!");}
		if(ContinueString=="All events marked, now FINISH !")			{Continue=0; 	print("Done with the Macro !!!");}
	//
	if(TotalNumberOfROIs>0){DiscardPreviousEventNoSelection  = Dialog.getCheckbox();	 }
				//
				if(DiscardPreviousEventNoSelection){
					waitForUser("DiscardPreviousEventNoSelection");
					selectWindow("ROI Manager"); roiManager("Select", TotalNumberOfROIs-1); run("Select None");	DrawStrikeThrough(ImageTitle, PreviousSlice, DrawInXFrames);		//  scrape through the already-drawn mark
					selectWindow("ROI Manager"); roiManager("Select", TotalNumberOfROIs-1); roiManager("Delete");	TotalNumberOfROIs = TotalNumberOfROIs-1 ;				//  delete ROI from ROI manager
					DiscardPreviousEventNoSelection = 0 ; PreviousEventDiscarded = 1 ; 
					
					JumpBack=0;

					waitForUser("* MARK NEXT EVENT \n" 	+ " \n"	+ "* study it   \n" + " \n " +"(to finish --> select nothing)                          ");
					Slice = getSliceNumber();  getSelectionBounds(x,y,dummy,dummy);
				}
}  // vd  if(x==0 && y==0)







if(JumpBack==0){
if(Continue){






//  CHECKBOX   SIMPLE 
//  CHECKBOX   SIMPLE 
print("");print("checkbox simple");print("");
RepeatCheckBox = 1; GoBack = 0 ;

	while (RepeatCheckBox){
		RepeatCheckBox = 0;
		if(GoBack){
			selectWindow(ImageTitle);	run("Select None");	setTool("point"); run("Line Width...", "line=1");
			if(TotalNumberOfROIs>0){roiManager("Select", TotalNumberOfROIs-1); run("Select None");}
			waitForUser("* MARK NEXT EVENT \n" 	+ " \n"	+ "* study it   \n" + " \n " +"(to finish --> select nothing)                          ");
			Slice = getSliceNumber();  getSelectionBounds(x,y,dummy,dummy);
		}
		ShiftDown=0;
		Dialog.create("");	
		Dialog.setInsets(-5, 0,0); 	Dialog.addCheckbox(" is this a great macro or not ?? ",1);
		Dialog.addRadioButtonGroup("What did you observe ??", EventOptionsArray, 3, 1, EventOptionsFill);	
		Dialog.setInsets(-5, 0,0); 	Dialog.addMessage(" ");
		Dialog.setInsets(-8, 20,0); 	Dialog.addString("Remark", "" , 30);
	  	Dialog.setInsets(11, 80,0); 	Dialog.addCheckbox("Oops, too quick ; go back         ", 0);
	  	if(TotalNumberOfROIs>0){
	  	Dialog.setInsets(11, 120,0); 	Dialog.addCheckbox("Discard previous (i.e. Event_#"+TotalNumberOfROIs+" )", 0);}
	  	Dialog.setInsets(11, 160,0); 	Dialog.addCheckbox("Finish Macro", 0);
			Dialog.show;	
																	if(isKeyDown("shift")){ShiftDown=1;}
		GreatMacro		= Dialog.getCheckbox();
		ObservedEvent 		= Dialog.getRadioButton;	print("Observed Event : " +ObservedEvent);			if(ShiftDown){EventOptionsFill = ObservedEvent;}
		MitosisRemark		= Dialog.getString();
		GoBack  		= Dialog.getCheckbox();		if(GoBack)		{RepeatCheckBox = 1;}		
	  	if(TotalNumberOfROIs>0){
		DiscardPreviousEvent  	= Dialog.getCheckbox();	 }
		FinishMacro  		= Dialog.getCheckbox();		
	
			if(ShiftAtMarking){
				EventOptionsFill=OldFill;
			}
			if(FinishMacro){
				Continue=0; 		// ofwel, dit wordt de laatste keer door de while-loop heen
				Dialog.create("");	Dialog.addCheckbox("include last event??", 1);	Dialog.show;	IncludeLast = Dialog.getCheckbox();	
				if(IncludeLast==0){SkipDataOutput = 1;}
			}
			//  discard previous event ?
			if(DiscardPreviousEvent){	
				GoBack = 1 ;	RepeatCheckBox = 1;	selectWindow("ROI Manager"); roiManager("Select", TotalNumberOfROIs-1); run("Select None");	DrawStrikeThrough(ImageTitle, PreviousSlice, DrawInXFrames);		//  scrape through the already-drawn mark
						selectWindow("ROI Manager"); roiManager("Select", TotalNumberOfROIs-1); roiManager("Delete");	TotalNumberOfROIs = TotalNumberOfROIs-1 ;				//  delete ROI from ROI manager
						DiscardPreviousEvent = 0 ; PreviousEventDiscarded = 1 ; 			
			}
			run("Select None"); 
		}





if(SkipDataOutput != 1){
	print("");print("draw mark");print("");
	////   DRAW  MARK    /////////   DRAW  MARK    /////////   DRAW  MARK    /////////   DRAW  MARK    /////
	////   DRAW  MARK    /////////   DRAW  MARK    /////////   DRAW  MARK    /////////   DRAW  MARK    /////

	// Works for both Simple and Extended  Analysis
	if(ObservedEvent=="Mitosis") 			{DrawColor = "green";}
	if(ObservedEvent=="Apoptosis") 		{DrawColor = "magenta";}
	if(ObservedEvent=="Mitotic Catastrophe") 	{DrawColor = "yellow";}
	run("Colors...", "foreground="+DrawColor);

		//  LEFT  ; first mark on the 'left side'
		if(DoubleImage){if(x>0.5*xImage){x = x - 0.5*xImage;}	}
		MakeMark(ImageTitle, MarkSize);
			// Add ROI to the ROI-Manager-list ; always the one in the 'left' image
			selectWindow("ROI Manager");	roiManager("Add");
			TotalNumberOfROIs = roiManager("count"); print("TotalNumberOfROIs : "+TotalNumberOfROIs);
		DrawMarkAndNumber  (ImageTitle, Slice, DrawInXFrames);

		//  RIGHT  ; then mark on the 'right side'
		if(DoubleImage){x = x + 0.5*xImage;
			MakeMark  (ImageTitle, MarkSize);
			DrawMarkAndNumber  (ImageTitle, Slice, DrawInXFrames);
			}

		// For ROI renaming, we pick the ´left´ one
		if(DoubleImage){x = x - 0.5*xImage;}  
		RoiRenaming (ImageTitle);
		selectWindow(ImageTitle); run("Select None");

}  // vd (SkipDataOutput != 1)


if(SkipDataOutput != 1){

	//  And Count integrated amounts of each event
	//  And Count integrated amounts of each event
	print("");print("count integrated amount of each event");print("");
	N = TotalNumberOfROIs;
		if(N == 1){CountMitoses=0;}			if(ObservedEvent=="Mitosis") 		{CountMitoses 	= CountMitoses	 + 1;}		if(PreviousEventDiscarded==1 && PreviousEvent=="Mitosis") 		{CountMitoses = CountMitoses     - 1;}		New = CountMitoses ; 	BackupArray ("CountMitoses");
		if(N == 1){CountApoptoses=0;}			if(ObservedEvent=="Apoptosis")		{CountApoptoses = CountApoptoses + 1;}		if(PreviousEventDiscarded==1 && PreviousEvent=="Apoptosis") 		{CountApoptoses = CountApoptoses - 1;}		New = CountApoptoses ; 	BackupArray ("CountApoptoses");
		// later (after the loop) --> put in a smart ARRAY-of-TOTALS

//  even de 'FrameNumberString' goed regelen ; daarmee ga ik chronomlogical sorting doen
FrameNumberString = toString(Slice); NumberOfZerosRequired = 4 - lengthOf(FrameNumberString);	Zeros = ""; for(z=0 ; z<NumberOfZerosRequired ; z++){Zeros = Zeros + "0"; }	
FrameNumberString = Zeros + FrameNumberString;	





///////////////    EVERY ROUND, PUT VALUES IN THE ARRAYS    /////////////////////////    EVERY ROUND, PUT VALUES IN THE ARRAYS    //////////
///////////////    EVERY ROUND, PUT VALUES IN THE ARRAYS    /////////////////////////    EVERY ROUND, PUT VALUES IN THE ARRAYS    //////////
///////////////    EVERY ROUND, PUT VALUES IN THE ARRAYS    /////////////////////////    EVERY ROUND, PUT VALUES IN THE ARRAYS    //////////
////  volgorde maakt hier nix uit ; gewoon kwestie van alle Arrays opvullen voor deze Event
print("TotalNumberOfROIs : "+TotalNumberOfROIs);	print("NumberOfRetrievedROIs : "+NumberOfRetrievedROIs);	print("");print("every round, put variables in the arrays");print("");

N = TotalNumberOfROIs;																															New = TotalNumberOfROIs ; BackupArray ("TotalNumberOfROIs");			
PED = PreviousEventDiscarded;

	if(N==1){EventArray		= newArray(0);}		New = ObservedEvent;			if(PED){EventArray = Array.trim(EventArray, N-1);}				EventArray =  Array.concat(EventArray,New);						BackupArray ("EventArray");				
	if(N==1){FrameNumberArray	= newArray(0);}		New = toString(Slice);			if(PED){FrameNumberArray = Array.trim(FrameNumberArray, N-1);}			FrameNumberArray =  Array.concat(FrameNumberArray,New);					BackupArray ("FrameNumberArray");
	//  for chronological sorting
	if(N==1){FrameNumberStringArray	= newArray(0);}		New = FrameNumberString;		if(PED){FrameNumberStringArray = Array.trim(FrameNumberStringArray, N-1);}	FrameNumberStringArray =  Array.concat(FrameNumberStringArray,New);			BackupArray ("FrameNumberStringArray");
	
	if(N==1){XCoordinateArray	= newArray(0);}		New = toString(x);			if(PED){XCoordinateArray = Array.trim(XCoordinateArray, N-1);}			XCoordinateArray =  Array.concat(XCoordinateArray,New);					BackupArray ("XCoordinateArray");
	if(N==1){YCoordinateArray	= newArray(0);}		New = toString(y);			if(PED){YCoordinateArray = Array.trim(YCoordinateArray, N-1);}			YCoordinateArray =  Array.concat(YCoordinateArray,New);					BackupArray ("YCoordinateArray");
	
	if(N==1){MitosisRemarkArray	= newArray(0);}		New = toString(MitosisRemark);		if(PED){MitosisRemarkArray = Array.trim(MitosisRemarkArray, N-1);}		MitosisRemarkArray =  Array.concat(MitosisRemarkArray,New);				BackupArray ("MitosisRemarkArray");
	

print("");print("save ROI list");print("");
//  Save the ROI list
 ROIarray = newArray(TotalNumberOfROIs);
 for(i=0; i<ROIarray.length; i++)
 	{ROIarray[i] = i;} 	// fill ROI-array with numbers 1 to TotalNumberOfROIs ; necessary for selection
selectWindow("ROI Manager"); run("Select All"); roiManager("Select", ROIarray);
roiManager("Save", DumpLocation +SettingsDump+  ROISaveString); 
//  Save the data obtained so far

//  make window ready for the next-go-round
roiManager("Deselect"); roiManager("Select", TotalNumberOfROIs-1); selectWindow(ImageTitle); run("Select None");

}  // vd (SkipDataOutput != 1)
}  //  van de Continue
}  //  van de JumpBack

PreviousSlice 	= Slice ;
PreviousX 	= x ;
PreviousY 	= y ;
PreviousEvent	= ObservedEvent ;

print("");print("END OF LOOP");print("");
}  //  van de WHILE (Continue)   line ~250











// now (after the loop) --> put in a smart ARRAY-of-TOTALS
// now (after the loop) --> put in a smart ARRAY-of-TOTALS
print("");print("after loop, put in ArrayOfTotals");print("");

ArrayOfTotals 		= newArray(1010);	for(j=0 ; j<ArrayOfTotals.length ; j++) 	{ArrayOfTotals[j] = Blank;}
ArrayTotalsHeader	= newArray(1010);	for(j=0 ; j<ArrayTotalsHeader.length ; j++) 	{ArrayTotalsHeader[j] = Blank;}
//
	a=1;	ArrayTotalsHeader[a] = "Total # Mitoses";			ArrayOfTotals[a] = CountMitoses;			print("CountMitoses : "+CountMitoses);		print("Total # Mitoses : "+ArrayTotalsHeader[a]);
	a=a+1;	ArrayTotalsHeader[a] = "Total # Apoptoses";			ArrayOfTotals[a] = CountApoptoses;			print("CountApoptoses : "+CountApoptoses);	print("Total # Apoptoses : "+ArrayTotalsHeader[a]);


//    NOW store in Strings
//    NOW store in Strings
	print("");print("STORE DATA IN STRINGS, for the excel");print("");
	//  Define The Array-Of-PrintStrings
	PrintStringArray = newArray(5+TotalNumberOfROIs);
	PrintStringArray[0] = "Experiment : "+ExperimentName;
	PrintStringArray[1] = "";

for(i=0 ; i<TotalNumberOfROIs ; i++){
	ArrayForHeaderString1 = newArray(1010); 	// first  of 2 lines in xls file
	ArrayForHeaderString2 = newArray(1010); 	// second of 2 lines in xls file 	
	ArrayForPrintString  = newArray(1010);
	RecognizeSpaces = "   ";  //  3 times spacebar ; after the remark-column
	
	///  a = column	(consecutive parameters
	///  i = row  	(consecutive events)  
	///  Position and EventNumber are always The First Two. The others, just put them in the order you like, and it will work
		a = 0;	if(i==0){ArrayForHeaderString1[a]="xxxx";		ArrayForHeaderString2[a]="xxxx";}		ArrayForPrintString[a] = FrameNumberStringArray[i];				
		a=a+1;	if(i==0){ArrayForHeaderString1[a]="Position";		ArrayForHeaderString2[a]="(organoid)";}		ArrayForPrintString[a] = toString(PosNumber);				
		a=a+1;	if(i==0){ArrayForHeaderString1[a]="Event-";		ArrayForHeaderString2[a]="number";}		ArrayForPrintString[a] = toString(i+1);	

		a=a+1;	if(i==0){ArrayForHeaderString1[a]="Observed";		ArrayForHeaderString2[a]="event";}		ArrayForPrintString[a] = EventArray[i];				
		a=a+1;	if(i==0){ArrayForHeaderString1[a]="Frame-";		ArrayForHeaderString2[a]="number";}		ArrayForPrintString[a] = toString(FrameNumberArray[i]);				
	
		a=a+1;	if(i==0){ArrayForHeaderString1[a]="X-Coor-";		ArrayForHeaderString2[a]="dinate";}		ArrayForPrintString[a] = toString(XCoordinateArray[i], 0);				
		a=a+1;	if(i==0){ArrayForHeaderString1[a]="Y-Coor-";		ArrayForHeaderString2[a]="dinate";}		ArrayForPrintString[a] = toString(YCoordinateArray[i], 0);				
		a=a+1;	if(i==0){ArrayForHeaderString1[a]="Remark...";		ArrayForHeaderString2[a]="Remark...";}		ArrayForPrintString[a] = MitosisRemarkArray[i];			

		a=a+1;	if(i==0){ArrayForHeaderString1[a]=RecognizeSpaces;	ArrayForHeaderString2[a]=RecognizeSpaces;}	ArrayForPrintString[a] = RecognizeSpaces;	
		a=a+1;	if(i==0){ArrayForHeaderString1[a]="THE";		ArrayForHeaderString2[a]="THE";}		ArrayForPrintString[a] = ArrayTotalsHeader [i];			
		a=a+1;	if(i==0){ArrayForHeaderString1[a]="TOTALS";		ArrayForHeaderString2[a]="TOTALS";}		ArrayForPrintString[a] = ArrayOfTotals [i];	
						
		a=a+1;	if(i==0){ArrayForHeaderString1[a]="";			ArrayForHeaderString2[a]="";}			ArrayForPrintString[a] = "";	
		a=a+1;	if(i==0){ArrayForHeaderString1[a]="";			ArrayForHeaderString2[a]="";}			ArrayForPrintString[a] = "";	
		a=a+1;	if(i==0){ArrayForHeaderString1[a]="";			ArrayForHeaderString2[a]="";}			ArrayForPrintString[a] = "";	


	NumberOfParameters = a+1; 
	ArrayForPrintString  = Array.trim(ArrayForPrintString,  NumberOfParameters);  //
	ArrayForHeaderString1 = Array.trim(ArrayForHeaderString1, NumberOfParameters);  //
	ArrayForHeaderString2 = Array.trim(ArrayForHeaderString2, NumberOfParameters);  //

		if(i+1 <= NumberOfRetrievedROIs){print("voor invullen van de NumberOfRetrievedROIs : NumberOfParameters (optelsom van de a'tjes) = "+NumberOfParameters);	Array.print(ArrayForPrintString); print("KOPIEER , i = "+i);	}
		else {print("voor het GEWONE invullen : NumberOfParameters (optelsom van de a'tjes) = "+NumberOfParameters);							Array.print(ArrayForPrintString); print("KOPIEER , i = "+i);	}


	// build the HeaderString and put in the PrintStringArray
	if(i==0){
		HeaderString1 = "";													if(PrintStringsToLog){print("******************* , i = "+i); print("HeaderString1 start : "+HeaderString1);}
		for(j=0 ; j<NumberOfParameters ; j++){HeaderString1 = HeaderString1 + Separator + ArrayForHeaderString1[j];		if(PrintStringsToLog){print("HeaderString1 for-loop "+HeaderString1);}	}
		PrintStringArray[2] = HeaderString1;
		//
		HeaderString2 = "";													if(PrintStringsToLog){print("HeaderString2 start : "+HeaderString2);}
		for(j=0 ; j<NumberOfParameters ; j++){HeaderString2 = HeaderString2 + Separator + ArrayForHeaderString2[j];		if(PrintStringsToLog){print("HeaderString2 for-loop "+HeaderString2);}	}
		PrintStringArray[3] = HeaderString2;		
		}
		PrintStringArray[4] 	= Blank;	
	// build the PrintString and put in the PrintStringArray
	PrintString = "";														if(PrintStringsToLog){print("PrintString start : "+PrintString);}
	for(j=0 ; j<NumberOfParameters ; j++){PrintString = PrintString + Separator + ArrayForPrintString[j];				if(PrintStringsToLog){print("PrintString for-loop "+PrintString);}		}
	PrintString = toString(PrintString);
	// now put the Printstring of this i in de ARRAY 
	FirstRow = 5 ;
	PrintStringArray[FirstRow + i] 	= PrintString;											if(PrintStringsToLog){print("PrintStringArray.length "+PrintStringArray.length);}
																	if(PrintStringsToLog){print(""); print("******************* , i = "+i);  print("PrintStringArray[FirstRow + i] : "); print(PrintStringArray[FirstRow + i]);}		
} //  van de i-loop
 



///  SORT CHRONOLOGICALLY 
///  SORT CHRONOLOGICALLY 
if(AddChronologicalData){
	print("");print("sort chronologically");print("");
	//  make a second block, by doubling the arrays so we can sort the data chronologically
	ArrayChronologicalPrintString = Array.slice(PrintStringArray, FirstRow, PrintStringArray.length);

	print(""); print("TotalNumberOfROIs : " + TotalNumberOfROIs);
	print(""); print("PrintStringArray.length : "+PrintStringArray.length); print("");
	for(k=0 ; k<PrintStringArray.length ; k++){print(k+" : "+PrintStringArray[k]);} print("");
	for(k=0 ; k<ArrayChronologicalPrintString.length ; k++){print(k+" : "+ArrayChronologicalPrintString[k]);} print("");
	
	
	
	Array.sort(ArrayChronologicalPrintString);																				print("just done sorting for ArrayChronologicalPrintString");for(k=0 ; k<ArrayChronologicalPrintString.length ; k++){print(k+" : "+ArrayChronologicalPrintString[k]);} print("");
 
ChopOffInitialFrameNumberString=1;
if(ChopOffInitialFrameNumberString){
	//   in de 'ArrayChronologicalPrintString' mogen de eerste Framenumbers er weer af
	for(f=0 ; f<ArrayChronologicalPrintString.length ; f++){	ArrayChronologicalPrintString[f] = substring(ArrayChronologicalPrintString[f], 7 , lengthOf(ArrayChronologicalPrintString[f]));	}	print("");print("ArrayChronologicalPrintString"); for(k=0 ; k<ArrayChronologicalPrintString.length ; k++){ print(k+" : "+ArrayChronologicalPrintString[k]);}
	//  ook in de oorspronkelijke 'ArrayForPrintString' mogen de eerste Framenumbers er weer af
	for(f=FirstRow ; f<PrintStringArray.length ; f++){
		PrintStringArray[f] = substring(PrintStringArray[f], 7 , lengthOf(PrintStringArray[f]));}	//  deze 7 is om de 'FramenumberString' die nodig was voor sorting, er weer af te halen
		PrintStringArray[2] = substring(PrintStringArray[2], 7 , lengthOf(PrintStringArray[2]));
		PrintStringArray[3] = substring(PrintStringArray[3], 7 , lengthOf(PrintStringArray[3]));													print("");print("PrintStringArray"); for(k=0 ; k<PrintStringArray.length ; k++){print(k+" : "+PrintStringArray[k]); }
	}

	//  first we chop off the totals, those are going to be shuffled wrongly on this side...
	// print(ArrayChronologicalPrintString.length);	print(PrintStringArray.length); 
		HeaderForChronoSorted = substring(PrintStringArray[2], 0 , indexOf(PrintStringArray[2] , RecognizeSpaces) );    
		PrintStringArray[2] =  PrintStringArray[2] + HeaderForChronoSorted;
		HeaderForChronoSorted = substring(PrintStringArray[3], 0 , indexOf(PrintStringArray[3] , RecognizeSpaces) );    
		PrintStringArray[3] =  PrintStringArray[3] + HeaderForChronoSorted;
		// now test for all lines, chop off last bit
		for(g=0 ; g<ArrayChronologicalPrintString.length  ; g++){
			IndexForChopOff = indexOf(ArrayChronologicalPrintString[g], RecognizeSpaces);
			if(IndexForChopOff != -1){ArrayChronologicalPrintString[g] = substring(ArrayChronologicalPrintString[g], 0 , IndexForChopOff);	}
		}

	// then, we add cellnumber changes ; for integrating temporal cell numbers :
	//  the Headers first
	PrintStringArray[2] =  PrintStringArray[2] + Separator + "Cell Number";
	PrintStringArray[3] =  PrintStringArray[3] + Separator + "Change";
	// then all events
	BeginChronoArray = newArray(ArrayChronologicalPrintString.length);
	for(f=0 ; f<ArrayChronologicalPrintString.length ; f++){
		BeginChronoArray[f] = substring(ArrayChronologicalPrintString[f], 0,30);
		CellNumberChange = 0 ;
		if(indexOf(BeginChronoArray[f], "Mitosis") != -1){
			CellNumberChange =  1;		ArrayChronologicalPrintString[f] = ArrayChronologicalPrintString[f] + Separator +  toString(CellNumberChange);} 
		if(indexOf(BeginChronoArray[f], "Mitotic Catastrophe") != -1)	{
			CellNumberChange = -1;		ArrayChronologicalPrintString[f] = ArrayChronologicalPrintString[f] + Separator +  toString(CellNumberChange);}
		if(indexOf(BeginChronoArray[f], "Apoptosis") != -1){
			CellNumberChange = -1;		ArrayChronologicalPrintString[f] = ArrayChronologicalPrintString[f] + Separator +  toString(CellNumberChange);}
	}
	
	// now concatenate them, so they will be in the same row in excel
		for(g=0 ; g<ArrayChronologicalPrintString.length  ; g++){
			PrintStringArray[g + FirstRow] =  PrintStringArray[g + FirstRow] + ArrayChronologicalPrintString[g];
		}
} //  vd if(AddChronologicalData)


else{	//  ALSO IF WE DON'T DO CHRONOLOGICAL SORTING !!
	for(f=FirstRow ; f<PrintStringArray.length ; f++){
		PrintStringArray[f] = substring(PrintStringArray[f], 7 , lengthOf(PrintStringArray[f]));}	
		PrintStringArray[2] = substring(PrintStringArray[2], 7 , lengthOf(PrintStringArray[2]));
		PrintStringArray[3] = substring(PrintStringArray[3], 7 , lengthOf(PrintStringArray[3]));									print("");print("PrintStringArray"); for(k=0 ; k<PrintStringArray.length ; k++){print(k+" : "+PrintStringArray[k]); }
}




print("");print("Save results and round up");print("");
//  SAVE RESULTS  and round up
	ScoreEvents_Output = PrintStringArray;
	Array.show(ScoreEvents_Output); selectWindow("ScoreEvents_Output"); setLocation(1, 1);

	// if(ChooseAnalysisType){AnalysisType="Simple+Extended";}
	PosString=""; if(PosNumber!=NaN){PosString = " Pos"+PosNumber;}
	NameResultsWindow = "ScoreEvents_Output "+ExperimentName + PosString + ".xls";
	IJ.renameResults(NameResultsWindow);	
		Dialog.create(" "); Dialog.addString("Save as ... ", NameResultsWindow, 80); 	Dialog.show();
		NameResultsWindow  = Dialog.getString(); 
	saveAs("Results", DumpLocation + ResultDump + DateFolder + NameResultsWindow);   
	selectWindow(NameResultsWindow); run("Close");
	// also save the Annotated Image series??
	selectWindow(ImageTitle); SaveName=getTitle;	
		if(endsWith(SaveName, ".avi")){SaveName = substring(SaveName, 0, lengthOf(SaveName)-4);}
	SaveName = SaveName+ "_ANALYZED"; 
	// ask user
		Dialog.create(" Save Avi ??"); 
		Dialog.addMessage("Want to SAVE the annotated avi-movie ??  "); 
		Dialog.addString("File name ", SaveName, 80); 			
		Dialog.setInsets(20, 20,0); Dialog.addRadioButtonGroup("Save the annotated movie  ", newArray("Don't save" , "Save to ScoreEvents Result-dump" , "Save As ..."), 3, 1, SaveAnnotatedMovie);	
			Dialog.show();
		SaveName			= Dialog.getString;
		SaveAnnotatedMovie 	= Dialog.getRadioButton;
	if(SaveAnnotatedMovie=="Save to ScoreEvents Result-dump"){
		selectWindow(ImageTitle);		run("AVI... ", "compression=JPEG frame=3 save=["+DumpLocation + ResultDump + DateFolder + SaveName+".avi]");		}	
	if(SaveAnnotatedMovie=="Save As ..."){
		selectWindow(ImageTitle);		run("AVI... ", "compression=JPEG frame=3");								}

	WriteAwayParameters();


	Line0 = "DONE !!!!  \n \n \n \n \n \n";
	Line1 = "Data are written away in xls format. Check D/ANALYSIS DUMP/ScoreEvents  \n";
	Line1b = "    ... and maybe you saved the avi's with the events marked in there, so you can always look it back   \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, from left to right: \n";
	Line7 = "   first some rows with raw data, in order as you clicked them \n";
	Line8 = "   then the TOTALS \n";
	Line9 = "   then the same raw data, but sorted in chronological order \n";
	Line10 = "   then (also chronologically) the +1's (for mitoses) and -1's (for apoptoses), which describe the organoid's evolution \n";
	
	print(""); waitForUser(Line0 + Line1 +Line1b + Line2 + Line3 + Line4 + Line5 + Line6 + Line7 + Line8 + Line9 + Line10 ); print("");

	exit("done !");













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

 function DoPrepare (){
 	print("\\Clear"); print("MACRO STARTS"); print("");
			while (isOpen("ScoreEvents_Output")){ selectWindow("ScoreEvents_Output"); run("Close");}	
	if(Mac==0){	while (isOpen("ScoreEvents_Output.xls")){ selectWindow("ScoreEvents_Output.xls"); run("Close");} 	}
			while (isOpen("Log")){ selectWindow("Log"); run("Close");}
 }

 function DrawFrameNumbers (Title){
 setBatchMode(true);
	getDimensions(xImage, yImage, dummy, NumberOfTimepoints, dummy);
	run("Colors...", "foreground=yellow background=black selection=yellow");	setFont("SansSerif", 48, " antialiased");
	for(i=0; i<NumberOfTimepoints ; i++){
		selectWindow(ImageTitle);
		setSlice(i+1); 
		FrameNumber = i+1;
		drawString(FrameNumber, (0.5*xImage-50), 60);
	}
	setSlice(1);
 setBatchMode(false);
 }

 
 function MakeMark (Title, MarkSize){
	selectWindow(ImageTitle);
 	if(ObservedEvent=="Mitosis")			{makeOval(x, y, MarkSize, MarkSize);}
	else 						{makeRectangle(x, y, MarkSize, MarkSize);}	
	if(ObservedEvent=="Mitotic Catastrophe")	{run("Rotate...", "angle=45");}
}

 function DrawMarkAndNumber (Title, Slice, DrawInXFrames){
	selectWindow(ImageTitle);
	DrawInFirstSlice = Slice-(floor(0.5*DrawInXFrames));
		//  these two are for in case we are close to the begin o the end of the movie
		if(DrawInFirstSlice<1) 					{DrawInFirstSlice = 1;}
		if(DrawInFirstSlice > NumberOfTimepoints-(DrawInXFrames-1)) 	{DrawInFirstSlice = NumberOfTimepoints-(DrawInXFrames-1);}
		// 

	for(i=0;i<DrawInXFrames;i++){
		// for Moving mark
		if(MovingMark){
			if(DrawInFirstSlice+i == Slice){print("NU  wordt de loop overgeslagen"+Slice); i = i+1; } 
			x = round(ArrayX[i]); y = round(ArrayY[i]);	MakeMark(ImageTitle, MarkSize);  	
		}
		setSlice(DrawInFirstSlice+i);	print("MOVING MARK slice : "+getSliceNumber);
		// black background
		run("Colors...", "foreground=black"); 		run("Line Width...", "line=5"); setFont("SansSerif", TextSize*1.15, "bold");
		run("Draw", "slice");
		drawString(TotalNumberOfROIs, x, y);
		// colored foreground
		run("Colors...", "foreground="+DrawColor); 	run("Line Width...", "line=2"); setFont("SansSerif", TextSize, " antialiased");
		run("Draw", "slice"); 
		drawString(TotalNumberOfROIs, x, y);
		}
	run("Line Width...", "line=1");
	setSlice(Slice); 	run("Select None");
	}

 function DrawStrikeThrough (Title, Slice, DrawInXFrames){
 	print("");print("DrawStrikeThrough");print("DrawStrikeThrough");
	if(DiscardPreviousEvent==1 ||  DiscardPreviousEventNoSelection==1){ x=PreviousX ; y=PreviousY; }
	
	selectWindow(ImageTitle);
	//  make strikethrough
	x1 = x;			x2 = x + MarkSize;
	y1 = y - 1.5*MarkSize;	y2 = y + 1.5*MarkSize;
	makeLine(x1, y1, x2, y2, 3);
	DrawInFirstSlice = Slice-(floor(0.5*DrawInXFrames));
		if(DrawInFirstSlice<1) 					{DrawInFirstSlice = 1;}
		if(DrawInFirstSlice > NumberOfTimepoints-(DrawInXFrames-1)) 	{DrawInFirstSlice = NumberOfTimepoints-(DrawInXFrames-1);}
	for(i=0;i<DrawInXFrames;i++){
		setSlice(DrawInFirstSlice+i);	
		run("Colors...", "foreground=red"); 		
		run("Fill", "slice");					
		}
	setSlice(Slice); 	run("Select None");
	}

 function RoiRenaming (Title){
selectWindow(Title);
roiManager("Select", TotalNumberOfROIs-1);
	 StringTimepoints = ""+NumberOfTimepoints; DigitsForTimepoints = lengthOf(StringTimepoints);  print("DigitsForTimepoints "+DigitsForTimepoints);
	 Zeros="";
	 if(DigitsForTimepoints==1){Zeros="";}
	 if(DigitsForTimepoints==2 && Slice>=10){Zeros="";}		if(DigitsForTimepoints==2 && Slice<10){Zeros="0";}
	 if(DigitsForTimepoints==3 && Slice>=100){Zeros="";}		if(DigitsForTimepoints==3 && Slice<100){Zeros="0";}	if(DigitsForTimepoints==3 && Slice<10){Zeros="00";}

	 if(ObservedEvent=="Mitosis")			{EventinROIname="Mit ";}
	 if(ObservedEvent=="Apoptosis")		{EventinROIname="Apo ";}
	 if(ObservedEvent=="Mitotic Catastrophe")	{EventinROIname="M.C.";}
	 xInteger = floor(x); yInteger = floor(y);
ROIName = "ROI#"+(TotalNumberOfROIs)+" ; "+EventinROIname+"; frame"+Zeros+Slice+" ; (XY"+xInteger+","+yInteger+")";
roiManager("Rename", ROIName);
}

 
 function printArray(a)
 {
      print("");
      for(i=0; i<a.length; i++)
          print(i+": "+a[i]);
  }


function FixSaveDirectories (){

	if(File.exists(DumpLocation)){print("yep");}
	else {	print("DumpLocation not found"); 	
	// try to generate it (works if computer has D-drive)
	File.makeDirectory(DumpLocation);}			
	if(File.exists(DumpLocation)){print("yep, just generated the folder DumpLocation");	print("DumpLocation exists ("+DumpLocation+")");}
	// dus , als het niet is gelukt, bijv geen D-drive
	else{	waitForUser("OK, first we need to create folders on your computer so we can store analysis output and settings \n" + " \n " + "WHERE ??");  print("DumpLocation not found"); 	
		ForDumpLocation = getDirectory("Where shall we create folders for analysis data ??");	print("ForDumpLocation (initially) : "+ForDumpLocation);		
			//  even schuine streepjes toevoegen.... gedoe zeg...
			NewString=""; FileSeparator = File.separator; 								print("FileSeparator : " + FileSeparator);
			for(i=0 ; i<lengthOf(ForDumpLocation) ; i++){
				Character = substring(ForDumpLocation, i, i+1);							print("Character = "+ Character);	
				if(Character!= FileSeparator)	{NewString = NewString + Character;				print("NewString = "+ NewString);}
				else				{NewString = NewString + FileSeparator+ FileSeparator;		print("NewString = "+ NewString);}	
			}
		ForDumpLocation = NewString;											print("ForDumpLocation (eventually) : "+ForDumpLocation);
		DumpLocation	= ForDumpLocation + "ANALYSIS DUMP"+FileSeparator;
		if(File.exists(DumpLocation)){ }
		else {	File.makeDirectory(DumpLocation);									print("DumpLocation exists ("+DumpLocation+")");
			File.makeDirectory(DumpLocation + ResultDump);								print("ResultDump exists ("+DumpLocation + ResultDump+")");
			File.makeDirectory(DumpLocation + SettingsDump);							print("SettingsDump exists ("+DumpLocation + SettingsDump+")");
			File.makeDirectory(DumpLocation + ResultDump + DateFolder);						print("Date Folder  exists ("+DumpLocation + ResultDump+DateFolder+")");
		}
	}
	// wherever is DumpLocation, generate these two inside that location
	if(File.exists(DumpLocation + ResultDump)) 			{print("yep");}		else {print("ResultDump not found"); 	File.makeDirectory(DumpLocation + ResultDump);}			print("ResultDump exists ("+ResultDump+")");

	if(File.exists(DumpLocation + SettingsDump)) 			{print("yep");}		else {print("SettingsDump not found"); 	File.makeDirectory(DumpLocation + SettingsDump);}		print("SettingsDump exists ("+SettingsDump+")");
	if(File.exists(DumpLocation + SettingsDump + BackupDump)) 	{print("yep");}		else {print("SettingsDump not found"); 	File.makeDirectory(DumpLocation + SettingsDump + BackupDump);}	print("SettingsDump exists ("+SettingsDump + BackupDump+")");
	if(File.exists(FateTrackSettingsDump)) 				{print("yep");}		else {exit("FateTrackSettingsDump bestaat niet \n n "+FateTrackSettingsDump);}				
}

function CreateWindowToTestMarkSize (){
	selectWindow(ImageTitle); setSlice(1);
	run("Duplicate...", "title=[Test Mark Size]"); selectWindow("Test Mark Size");
	DrawColor = "green";
	ArrayMarkSizes = newArray(8,10,12,14,16,20,25);
		DrawDistanceX = (getWidth / (ArrayMarkSizes.length+2));
		DrawDistanceY = 0.25*DrawDistanceX;
	run("Colors...", "foreground=green"); 	run("Line Width...", "line=2"); setFont("SansSerif", 18, " antialiased");
		drawString("Mark Sizes", DrawDistanceX, 1.5*DrawDistanceY);
		drawString("Text Sizes", DrawDistanceX, 5*DrawDistanceY);
	run("Colors...", "foreground=yellow"); 
	for(i=0 ; i <ArrayMarkSizes.length ; i++){
		x = DrawDistanceX*(i+1);	
		y = 2*DrawDistanceY;
			makeOval(x, y, ArrayMarkSizes[i], ArrayMarkSizes[i]);	run("Draw", "slice");
		y = 4*DrawDistanceY;	
			setFont("SansSerif", ArrayMarkSizes[i]*1.15, "bold");	drawString(ArrayMarkSizes[i], x, y);
	}
	run("Select None");
}

function WriteAwayParameters(){
newImage("ImageForParametersAndSettings(ScoreEvents)", "RGB black", 200, 100, 1);
setFont("SansSerif", 30, " antialiased");	run("Colors...", "foreground=red");	drawString("ScoreEvents", 15, getHeight-30);

  List.set("ExperimentName", ExperimentName);
  List.set("PosNumber", PosNumber);
  List.set("TimeInterval", TimeInterval);
  List.set("MarkSize", MarkSize);
  List.set("TextSize", TextSize);
  List.set("DrawInXFrames", DrawInXFrames);
  List.set("WriteNumbers", WriteNumbers);
  List.set("AddChronologicalData", AddChronologicalData);
  List.set("DoubleImage", DoubleImage);
  List.set("SaveAnnotatedMovie", SaveAnnotatedMovie);
  List.set("ExpDate", ExpDate);
  List.set("OrgLine", OrgLine);
  List.set("EditImageTitle", EditImageTitle);

	list = List.getList();
  	setMetadata("info", list);
	saveAs("Tiff", DumpLocation + SettingsDump + "ImageForParametersAndSettings(ScoreEvents).tif");
	List.clear;

  close();
}



///////////////////  the 3 functions for backupping of the data
function BackupArray (BackupName){

	Path = DumpLocation + SettingsDump + BackupDump ;
	if(N==1){BackupString = New;}
	else   {BackupString = File.openAsString(Path + BackupName+".txt");
		BackupString = BackupString + Separator + New;}
		File.saveString(BackupString, Path + BackupName+".txt");
}

function Retrieve (BackupName){
	print("********");print("begin vd Retrieve");print(BackupName);
	TempArray = newArray(NumberOfRetrievedROIs);	
	BackupString = File.openAsString(Path + BackupName+".txt");		LastIndex = lastIndexOf(BackupString, Separator);
	StartSearch=0;	Continue = 1;	k=0;	
	while (Continue){
		k=k+1;	X=indexOf(BackupString,Separator,StartSearch);	A=substring(BackupString,StartSearch,X); StartSearch=X+1;	
			TempArray[k-1]=A;  
			if(lengthOf(A) >1 ){
				if(k==1){	TempArray[k-1]= substring(A,0,lengthOf(A)-1);}
				if(k>1)  {	TempArray[k-1]= substring(A,1,lengthOf(A)-1);}
				}
		if(StartSearch>LastIndex){	
			k=k+1;		
			A=substring(BackupString,StartSearch,lengthOf(BackupString));	
			TempArray[k-1]=A; 	
			if(lengthOf(A) >1 ){
				if(k==1){	TempArray[k-1]= substring(A,0,lengthOf(A)-1);}
				if(k>1)  {	TempArray[k-1]= substring(A,1,lengthOf(A)-1);}
				}
			Continue=0;}
			print("TempArray[k-1] : "+TempArray[k-1]);
		}
	return TempArray ;
}

function RetrieveLastFromArray (BackupName){
	BackupString = File.openAsString(Path + BackupName + ".txt");	
	LastIndex = lastIndexOf(BackupString, Separator); 	
		if(LastIndex == -1){LastIndex=-2;}	// in absence of separator... -2 because later it's +2
	LastFill = substring(BackupString,LastIndex+2,lengthOf(BackupString));
	LastFill = parseFloat(LastFill);		
		if(isNaN(LastFill)){print(""); waitForUser("Oops................"); print(""); }
	return LastFill ;
}

function SetAtZoom(Title){
	wait(WaitTimeOrderWindows);
	selectWindow(Title); 	run("Select None");	setLocation(1,1); 	run("View 100%");
	setBatchMode(true);				
		for(j=0;j<nTimes;j++){run(Z);}		
		run("Set... ", "zoom="+ZoomFactor);
	setBatchMode(false);
	// now test and , if wrong, correct !
	selectWindow(Title);
	getLocationAndSize(dummy, dummy, WidthA, dummy);	WidthB = getWidth*0.01*ZoomFactor;
	Margin=0.98;
	if(WidthA < Margin*WidthB){
		run("Out [-]");									
	}
}

function PopUp(Title, OriginalZoom, Percentage){
	setBatchMode(true);
	selectWindow(Title); run("Select None"); setLocation(1,1); 
		ZoomFactor = (Percentage/100)*OriginalZoom;
	Zooms = newArray(16.7, 25,33.3, 50,75,100,150,200,300,400,600,800,1200,1600);  i=0;  while(ZoomFactor>Zooms[i]){i=i+1;}			
	Z="";nTimes=0;
	if(Zooms[i]<100){Z="Out [-]"; nTimes = 5-i;}	
	if(Zooms[i]>100){Z="In [+]";  nTimes = i-5;}
	
	setBatchMode(false);						

	SetAtZoom(Title);
	setLocation((XLocationMin + 0.5*XLocationStep) , (YLocationMin + YWindowFraction*(YLocationMax-YLocationMin))); 
}
