//These macros were written by Steve Rothery
//FILM - Facility for Imaging in Light Microscopy, Imperial College London
//http://www3.imperial.ac.uk/imagingfacility/

///////////////////////////////////////////////1


macro "Live Measurements image Action Tool - C000 T0508L T6508i T8508v Te508e T1h08I T5h08n Tah08f Teh08o" 
{

//setTool("line");
run("Clear Results");
Xt="";
Yt="";
mt="";
if (nImages<1){
	exit("No Open Images");
}


run("Text Window...", "name=[Live Measurements] width=50 height=7 monospaced");
setLocation(0, 0);

a=isOpen("Live Measurements");

while (a==true) {
wait(250);
fn=getTitle();
bd=bitDepth();
getVoxelSize(px, py, pz, unit);


ln=getValue("Length");
an=getValue("Angle");
ar=getValue("Area");
mn=getValue("Mean");
mx=getValue("Max");



Plot.create("Intensity Information", Xt, Yt);
Plot.setFrameSize(600, 350);

Plot.setOptions("addvspace=10");
Plot.setFontSize(12, "bold")
Plot.setLimitsToFit();
Plot.setColor("blue", "blue");
Plot.addText("Line Length: "+ln+" "+unit, 0, 0);
//Plot.addText("Angle: "+an, 0.3, 0);
Plot.addText("Area: "+ar+" "+unit, 0.35, 0);
Plot.addText("Mean: "+mn, 0.65, 0);
Plot.addText("Max: "+mx, 0.85, 0);

Plot.setColor("red", "red");

if (selectionType<3){
	getHistogram(values, counts, 256);
	mt="Histogram of intensities";
	Xt="Intensity";
	Yt="Frequency";
Plot.add("bar", values, counts);

}
if (selectionType==3 || selectionType==5 || selectionType==7){
	mt="Line profile";
	Xt="Length ("+unit+")";
	Yt="Intensity";
	prof=getProfile();
	dist=Array.getSequence(prof.length);
	for (el=0;el<prof.length;el++){
		dist[el]=dist[el]*px;
	
	}
Plot.add("line", dist, prof);
}
Plot.update();


a=isOpen("Live Measurements");
if(a==true){
print("[Live Measurements]", "\\Update: Close This Window to Exit \n Image: "+fn+" \n Area: "+ar+" "+unit+ " \n Mean Intensity: "+mn+ "\n Line length: "+ln+" "+unit+" \n Line Angle: "+an+" degrees");
}

if (nImages<1){
	selectWindow("Live Measurements");
	run("Close");
	exit();
}
} while(a==1);
}


//////////////////////////////////////////////2


macro "Multi Line Measure Action Tool - C000  T3g09u T8g09m  C0aa F01h5 C000 R01h5 D03D23D43D63D83Da3Dc3De3Dg3 D02D22D42D62D82Da2Dc2De2Dg2 "
{
run("Set Measurements...", "area mean min centroid feret's display redirect=None decimal=3");

getVoxelSize(px, py, pz, units);
fn=getTitle();

setTool("line");

Overlay.clear;


Dialog.create("Options");
  Dialog.addMessage("ROI options: \n");
  LineColour = newArray("Red", "Green", "Blue", "Magenta", "Yellow", "Cyan", "Orange", "Black", "White" );
  clear=newArray("Yes","No");
//    Dialog.addChoice("Clear Results Table ?", clear, "No");
    Dialog.addChoice("Clear ROI's ?", clear, "Yes");
    Dialog.addMessage("Line options: \n");
    Dialog.addChoice("Colour ?", LineColour, "Green");
    Dialog.addNumber("Line Thickness ?", 1);
    Dialog.addNumber("No. of decimal places ?", 2);
    Dialog.addMessage("Angle options: \n");
    Dialog.addChoice("Display angle ?", clear, "No");
    Dialog.addNumber("No. of decimal places ?", 2);
    Dialog.addMessage("Text options: \n");
    fontface = newArray("Ariel","SansSerif", "Serif", "Times New Roman", "Courier New");
    Dialog.addChoice("Font ?", fontface, "Ariel");    
    fontstyle = newArray("None","Bold", "Italic", "Bold-Italic");
    Dialog.addChoice("Style ?", fontstyle, "None");
    Dialog.addNumber("Font Size (point) ?", 12);
Dialog.show;

//clearRes=Dialog.getChoice();
clearRoi=Dialog.getChoice();
LinCol=Dialog.getChoice();
LineWidth=Dialog.getNumber();
Lenplaces=Dialog.getNumber();
Showangle=Dialog.getChoice();
Anplaces=Dialog.getNumber();
fontface=Dialog.getChoice()
fontstyle=Dialog.getChoice()
fontsize=Dialog.getNumber();

setFont(fontface, fontsize, fontstyle);

if (Lenplaces<1){
	Lenplaces=Lenplaces-1;
}

if (Anplaces<1){
	Anplaces=Anplaces-1;
}


//if (clearRes=="Yes"){
//run("Clear Results");; 
//}

if (clearRoi=="Yes"){
roiManager("Reset"); 
}

run("Line Width...", "line="+LineWidth);

Cols="foreground="+LinCol + " background=black selection="+LinCol;
run("Colors...",Cols );

setJustification("center");

roiManager("Show All with labels");
title = "Get info";
msg = "draw lines and add to manager(t)\n then select OK to continue";
waitForUser(title, msg);

n=roiManager("Count");

	for (i=0;i<n;i++){
		roiManager("Select", i);
		roiManager("Rename", "Line "+i +1);
getLine(x1, y1, x2, y2, lineWidth);

dist=sqrt( ((x1-x2)*(x1-x2))  +  ((y1-y2)*(y1-y2)) );

op=x1-x2;
ad=y1-y2;
an=atan2(ad, op);
an=180-(an*180/PI);

if (an>270){
	an=an-360;
}
else if (an>90){
	an=an-180;
}

andec=indexOf(an, ".");
an=substring(an, 0, andec+Anplaces+1);


Overlay.addSelection;
dist=dist *px;


lendec=indexOf(dist, ".");
dist=substring(dist, 0, lendec+Lenplaces+1);

gr=" " + dist + " " + units;
if (Showangle=="Yes"){
	gr=gr  + "  " + an + " degrees";
}


Overlay.drawString(gr, x1, y1, an);
run("Measure");
Overlay.add;
	}
roiManager("Deselect");
roiManager("Show All");
IJ.renameResults("Results",fn+" - Data");
}





///////////////////////////////////////////////3


macro " Colour & Rename ROI's Action Tool - C000 T1h08R T8h08O Tgh08I Cg00 T18081 T68082 Tb8083"
{
//start
n=roiManager("count");
if(n==0){
	exit("No ROI's")
	};
roiManager("select", 0);
getLine(x1, y1, x2, y2, lineWidth);
if (lineWidth<1){
	lineWidth=1;
}
colours = newArray("#4dff0000","#4d00ff00", "#4d0000ff","#4dff00ff","#4d00ffff","#4dffff00","#4dffc800","#4dffffff","#4d000000");
//get info
Dialog.create("Select Colour and Range");
items = newArray("red","green","blue","magenta","cyan","yellow","orange","black","white");
Dialog.addChoice("Colour", items, "green");
opt = newArray("Yes","No");
Dialog.addChoice("Line Semi-Transparent ?", opt, "Yes")
Dialog.addNumber("Line width", lineWidth); 
Dialog.addNumber("Range from", 1);
Dialog.addNumber("to", n);
Dialog.show();

col=Dialog.getChoice();
transparent=Dialog.getChoice();
lnwdth=Dialog.getNumber();
s=Dialog.getNumber();
n=Dialog.getNumber();
s=s-1;
pre=getString("ROI Name", "Line");
run("Line Width...", "line="+lnwdth);


colour=col;
//get transparent colour 

if (transparent=="Yes"){
for (c=0;c<9;c++){
	if (col==items[c]){
	colour=colours[c];
}
}
}
//main routine
for (i=s; i<n; i++)
{
roiManager("select", i);
name=pre + " " + (i+1);
roiManager("Rename", name);
roiManager("Set Color", colour);
roiManager("Set Line Width", lnwdth);

}
roiManager("Deselect");
roiManager("Show all with labels");
}



/////////////////////////////////////////4


macro "Sequentially <Analyse Particles, Summary table only> from ROI list (v1) Action Tool - C000 T1g10R T8g10O Tgg10I C000 L02g2 D01D21D41D61D81Da1Dc1De1Dg1" 
//produces a summary table for all ROI's in the list
{
run("Set Measurements...", "area mean min centroid bounding area_fraction display redirect=None decimal=3");
fn=getTitle();
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
getVoxelSize(px, py, pz, unit);
mx=ImageWidth*ImageHeight;

if (ImageChannels>1 || bitDepth()==24){
waitForUser("Info", "Image must be grayscale or single channel \n Duplicate, flatten or split channels \n then select image to analyse");
fn=getTitle();
}


n=roiManager("count");
if (n>0){
keep=getBoolean("Keep existing ROI's?");
if (keep==false){
	roiManager("Reset");
}
}

roiManager("Show all");

//get ROI's
waitForUser("Draw", "Draw ROI's and add to ROI manager \n \nthen click OK to contine ");

run("Threshold...");

title = "Get info";
msg = "Now threshold image then click OK ";
waitForUser(title, msg);



run("Select None");
n=roiManager("count");
if(n==0){
	exit("There are no ROI's - please add ROI's and run macro again")
	};
roiManager("Remove Channel Info");

Dialog.create("Select Size Range ");
Dialog.addNumber("Range from", 0, 0, 15,"pixels");
Dialog.addNumber("to", mx, 0, 15, "pixels");
Dialog.show();

L=Dialog.getNumber();
H=Dialog.getNumber();



//run summary for ROI's
for (roi=0; roi<n; roi++){
selectWindow(fn);
roiManager("select", roi);
name=Roi.getName;
rename(fn + " "+name);
run("Analyze Particles...", " size=L-H summarize");
rename(fn);
}


}

//////////////////////////////////////////5

macro "Move, Sclae or Align multiple ROI's Action Tool - C000 T1h08R T8h08O Tgh08I L0565 L0523 L0527 C00g V6044 Cg00 Vd064 C0g0 V9544" {
fn=getTitle();
n=roiManager("count");
run("Clear Results");

ms=newArray("Move","Scale","Align");
Dialog.create("Options");
Dialog.addRadioButtonGroup("Move, Scale or Align ROI's", ms, 1, 2, ms[0]);
Dialog.addNumber("If Scaling - Scale Factor",1);
Dialog.show();

opt=Dialog.getRadioButton();
sf=Dialog.getNumber();

//move rois
if (opt=="Move"){
waitForUser("","Select Key Roi (Alt+Click)  \n \n then press OK");
curr=roiManager("index");
roiManager("Select", curr);
Roi.getBounds(x1, y1, width, height)
waitForUser("","Move Key ROI to new position \n \n then press OK");
roiManager("update");
roiManager("Select", curr);
Roi.getBounds(x2, y2, width, height)

Xm=x2-x1;
Ym=y2-y1;

for (roi=0;roi<n;roi++){
if (roi!=curr){
	roiManager("Select", roi);
	roiManager("translate", Xm, Ym);
}
}
roiManager("Deselect");
run("Select None");
}

//scale rois
if (opt=="Scale"){

for (roi=0;roi<n;roi++){
	roiManager("select", roi);
	run("Scale... ", "x=sf y=sf");
	roiManager("update");
}
roiManager("deselect");
run("Select None");
}

//align rois
if (opt=="Align"){
run("Clear Results");
for (roi=1;roi<=n;roi++){
	roiManager("select", roi-1);
	roiManager("rename", roi);
}
roiManager("deselect");

RoiList=Array.getSequence(n);
roitotal=n;

Dialog.create("Options");
	Dialog.addRadioButtonGroup("Horizontal Alignment:" , newArray("None","Left","Right"), 1, 4, "None");
	Dialog.addRadioButtonGroup("Vertical Alignment" , newArray("None","Top","Bottom"), 1, 4, "None");
	Dialog.addRadioButtonGroup("ROI's:" , newArray("all","selection"), 1, 2, "all");
Dialog.show();

Hpos=Dialog.getRadioButton();
Vpos=Dialog.getRadioButton();
moveRoi=Dialog.getRadioButton();

//selection rois
if (moveRoi=="selection"){
waitForUser("","Select Rois");
roiManager("measure");
roitotal=nResults;
if (roitotal<2){
	exit("Select at least 2 ROI's");
}
//Array.resample(RoiList,roitotal);
RoiList=newArray(roitotal);
for (res=0;res<roitotal;res++){
RoiList[res]=parseInt(substring(getResultLabel(res), indexOf(getResultLabel(res), ":")+1, lengthOf(getResultLabel(res))))-1;
}
}


roiManager("deselect");

//move  routine	
Lpos=newArray(roitotal);
Rpos=newArray(roitotal);	
Tpos=newArray(roitotal);
Bpos=newArray(roitotal);
//get roi positions
for (roi=0;roi<roitotal;roi++){
	roiManager("select", RoiList[roi]);
Roi.getContainedPoints(xpoints, ypoints);
Array.getStatistics(xpoints, min, max, mean, stdDev);
Lpos[roi]=min;
Rpos[roi]=max;
Array.getStatistics(ypoints, min, max, mean, stdDev);
Tpos[roi]=min;
Bpos[roi]=max;
}
Array.getStatistics(Lpos, Lmin, max, mean, stdDev);
Array.getStatistics(Rpos, min, Rmax, mean, stdDev);
Array.getStatistics(Tpos, Tmin, max, mean, stdDev);
Array.getStatistics(Bpos, min, Bmax, mean, stdDev);

//Array.show(RoiList,Lpos,Rpos,Tpos,Bpos);


//alignment routine
transX=0;
transY=0;
for (roi=0;roi<roitotal;roi++){
	roiManager("select", RoiList[roi]);
if (Hpos=="Left"){
	transX=Lmin-Lpos[roi];
}
if (Vpos=="Top"){
	transY=Tmin-Tpos[roi];
}
if (Hpos=="Right"){
	transX=Rmax-Rpos[roi];
}
if (Vpos=="Bottom"){
	transY=Bmax-Bpos[roi];
}
roiManager("translate", transX, transY);
}
roiManager("deselect");
run("Select None");
}


}



//////////////////////////////////////6


macro "Sequentially Analyse Particles, saves results & summary for each ROI(v1) Action Tool - C000 T1h08R T8h08O Tgh08I C00g V2046 Cg00 V9064 C0g0 V7444" 
//produces 2 saved files for each ROI (results and Summay table) and an overall summary table
{
a=nImages; 
if(a>0){};
else {
	 exit("No Image open")
};

getDimensions(width, height, channels, slices, frames);
mx=width*height;

//close windows
if (isOpen("Summary")) { 
	selectWindow("Summary"); 
       run("Close"); 
}

 if (isOpen("Results")) { 
	selectWindow("Results"); 
       run("Close"); 
}

roiManager("Show all");

//add ROI's
title = "Get info";
msg = "Image must be grayscale or single channel \n >> Draw ROI's and add to ROI manager \n\n >> then click OK to contine ";
waitForUser(title, msg);

run("Threshold...");

title = "Get info";
msg = "Now threshold image then click OK ";
waitForUser(title, msg);

n=roiManager("count");
if(n==0){
	exit("No ROI's")
	};

//get output info
output = getDirectory("Location for results");

fl=getTitle();

fln=getString("Results output filename:", fl);
selectWindow(fl);
rename(fln);

Dialog.create("Select Size Range ");
Dialog.addNumber("Range from", 0, 0, 15,"pixels");
Dialog.addNumber("to", mx, 0, 15, "pixels");
Dialog.show();

L=Dialog.getNumber();
H=Dialog.getNumber();

//measure ROI's
for (i=0; i<n; i++){
roiManager("select", i);
a=i+1;
roiManager("Rename",  a);

b=fln + " ROI " + a;
rename(b);

run("Analyze Particles...", " size=L-H display clear");

//test to see if ROI has measurements and save if so
if (isOpen("Results")) { 

c="Results of " + b;
out = output + c + ".csv";

IJ.renameResults(c);

selectWindow(c);
saveAs("Results ", out);
run("Close"); 
}
}

//run summary and save
for (i=0; i<n; i++){
roiManager("select", i);
a=i+1;

b=fln + " ROI " + a;
rename(b);

run("Analyze Particles...", " size=L-H summarize");
}
//save total summary
out = output + "Summary of " + fln + ".xls";
saveAs("Text", out);
selectWindow("Summary of " + fln + ".xls"); 
    run("Close");

rename(fl);
}


///////////////////////////////////////////////7

macro "Split up Image into segments Action Tool - C000 R00ff L07f7 L707f" 
{
//initialise
fn=getTitle();
roiManager("UseNames", "true");
run("Labels...", "color=white font=12 show use draw");
run("Colors...", "foreground=white background=black selection=white");
roiManager("Reset");
getDimensions(width, height, channels, slices, frames);
getVoxelSize(px, py, pz, units);

a=width/3*px;
b=height/3*px;


//dialog
Dialog.create("Get Crop Dimensions");
	Dialog.addMessage("Enter number of colums and rows");
	Dialog.addNumber("Input number of Columns", 2);
	Dialog.addNumber("Input number of Rows", 2);
	Dialog.addMessage("or");
	Dialog.addCheckbox("Use specific dimensions", false);
	Dialog.addMessage("   Enter distances in................."+units);
	Dialog.addNumber("Input width of Crops", a);
	Dialog.addNumber("Input height of Crops", b);
	Dialog.addMessage("Output");
	Dialog.addCheckbox("Save and close Croped images to a directory", false);
Dialog.show(); 
	
//response - set variables

cols=Dialog.getNumber();
rows=Dialog.getNumber();
size=Dialog.getCheckbox();
cropx=Dialog.getNumber();
cropy=Dialog.getNumber();
SaveCrop=Dialog.getCheckbox();

if (SaveCrop==true){
	//select location where images/results are to be stored
output = getDirectory("Select output location for cropped images");
}

cropWidth=width/cols;
cropHeight=height/rows;


//by size
if (size==true){
cropWidth=cropx/px;
cropHeight=cropy/py;
cols=width/cropWidth;
rows=height/cropHeight;
}


crop=1;

//main routine  
for (row=0;row<rows;row++){

for (col=0;col<cols;col++){

Xpos=col+col*(cropWidth-1);
Ypos=row+row*(cropHeight-1);
selectWindow(fn);
run("Specify...", "width=cropWidth height=cropHeight x=Xpos y=Ypos");
roiManager("Add");
run("Duplicate...", "duplicate");
rename("Crop "+crop+" "+fn);

roiManager("select",crop-1);
roiManager("rename", "Crop "+crop);

if (SaveCrop==true){
	//select location where images/results are to be stored
out = output + "Crop "+crop+" "+fn;
saveAs("Tiff",out);
close();
}

crop=crop+1;

}
}
//finish up

selectWindow(fn);
 
roiManager("Show All with labels");
roiManager("UseNames", "false");
}

///////////////////////////////////////////8

macro "Create a Grid Action Tool - C000 R00ff L03f3 L06f6 L09f9 L0cfc L303f L606f L909f Lc0cf" 
{
//initialise
fn=getTitle();
roiManager("UseNames", "true");
run("Labels...", "color=white font=12 show use draw");
run("Colors...", "foreground=white background=black selection=white");
roiManager("Reset");
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
getVoxelSize(px, py, pz, units);

a=ImageWidth/3*px;
b=ImageHeight/3*px;


//dialog
Dialog.create("Get Region Dimensions");
	Dialog.addMessage("Enter number of colums and rows");
	Dialog.addNumber("Input number of Columns", 2);
	Dialog.addNumber("Input number of Rows", 2);
	Dialog.addMessage("or");
	Dialog.addCheckbox("Use specific dimensions", false);
	Dialog.addMessage("   Enter distances in................."+units);
	Dialog.addNumber("Input width of Region", a);
	Dialog.addNumber("Input height of Region", b);
	pos=newArray("Starting Top-Left (all of Image)","Cross at Centre (full regions only)","Region at Centre (full regions only)");
	Dialog.addRadioButtonGroup("Positioning of grid if specifying", pos, 3, 1, pos[0])

	
Dialog.show(); 
	
//response - set variables
cols=Dialog.getNumber();
rows=Dialog.getNumber();
size=Dialog.getCheckbox();
RegionX=Dialog.getNumber();
RegionY=Dialog.getNumber();
location=Dialog.getRadioButton();

RegionWidth=ImageWidth/cols;
RegionHeight=ImageHeight/rows;




//by size
offsetX=0;
offsetY=0;

if (size==true){
//full image crop
RegionWidth=RegionX/px;
RegionHeight=RegionY/py;
cols=ImageWidth/RegionWidth;
rows=ImageHeight/RegionHeight;

//cross at centre only full regions
if (location=="Cross at Centre (full regions only)"){
	cols=floor(cols);
	rows=floor(rows);
	offsetX=(ImageWidth/2)-(RegionWidth*(floor(cols/2)));
	offsetY=(ImageHeight/2)-(RegionHeight*(floor(rows/2)));
if ((cols*RegionWidth)+offsetX>ImageWidth){
	cols=cols-1;
}
if ((rows*RegionHeight)+offsetY>ImageHeight){
	rows=rows-1;
}	
}

// square at centre only full region
if (location=="Region at Centre (full regions only)"){	
	cols=floor(cols);
	rows=floor(rows);
	a=floor((ImageWidth/2-RegionWidth/2)/(RegionWidth));
	offsetX=(ImageWidth/2-RegionWidth/2)-RegionWidth*floor((ImageWidth/2-RegionWidth/2)/(RegionWidth));
	offsetY=(ImageHeight/2-RegionHeight/2)-RegionHeight*floor((ImageHeight/2-RegionHeight/2)/(RegionHeight));
if ((cols*RegionWidth)+offsetX>ImageWidth){
	cols=cols-1;
}
if ((rows*RegionHeight)+offsetY>ImageHeight){
	rows=rows-1;
}
}
}


Region=1;

//main routine  
for (row=0;row<rows;row++){
for (col=0;col<cols;col++){
Xpos=col+offsetX+col*(RegionWidth-1);
Ypos=row+offsetY+row*(RegionHeight-1);
selectWindow(fn);
run("Specify...", "width=RegionWidth height=RegionHeight x=Xpos y=Ypos");
roiManager("Add");
roiManager("select",Region-1);
roiManager("rename", "Region "+Region);
Region=Region+1;
}
}
//finish up
selectWindow(fn);
roiManager("Show All with labels");
roiManager("UseNames", "false");

}

////////////////////////////////////////////////9

macro "Create Weibel Grid Action Tool -  C000  L0030 L70a0 Le0h0 L0b3b L7bab Lebhb  L3666 La6d6 Lg6h6 L3h6h Lahdh Lghhh"
{

//initialise
fn=getTitle();
roiManager("reset");
run("Clear Results");
run("Select None");
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
getVoxelSize(px, py, pz, unit);

if (isOpen("Grid Summary")==true){
	selectWindow("Grid Summary");
	run("Close");
}


//set size and offset
Dialog.create("Options");
Dialog.addNumber("Grid Size ("+unit+")" , 200);
Dialog.addNumber("Grid offset X ("+unit+")", 50);
Dialog.addNumber("Grid offset Y ("+unit+")", 50);
Dialog.show();

ln=Dialog.getNumber(); //length of line in units
Xoff=Dialog.getNumber()/px;//top left offset in units
Yoff=Dialog.getNumber()/px;//top left offset in units

lw=ln/px;
lh=sqrt(lw*lw-(lw/2*lw/2));

//draw region
waitForUser("Draw limiting region if required \n then press OK");
if (selectionType==-1){
	makeRectangle(0, 0, ImageWidth, ImageHeight);
}
roiManager("add");

//get grid limit
getSelectionBounds(X1, Y1, regionwidth, regionheight);

Xoff=Xoff+X1;
Yoff=Yoff+Y1;
Xpts=round(regionwidth/(lw/2))+2;
Ypts=round(regionheight/(lw/2))+2;

roiManager("Show None");

setBatchMode("hide");

//create grid
for (set=0;set<Ypts;set++){
for (roi=0;roi<Xpts;roi++){
roiManager("select", 0);
if (selectionContains(Xoff+(2*lw*roi),Yoff+(2*lh*set)) && selectionContains(Xoff+(2*lw*roi)+lw,Yoff+(2*lh*set))){	
makeLine(Xoff+(2*lw*roi),Yoff+(2*lh*set),Xoff+(2*lw*roi)+lw,Yoff+(2*lh*set));
roiManager("add");
}
}
for (roi=0;roi<Xpts;roi++){
roiManager("select", 0);
if (selectionContains(Xoff+(2*lw*roi)+(lw/2),Yoff+(2*lh*set)+lh) && selectionContains(Xoff+(2*lw*roi)+lw+(lw/2),Yoff+(2*lh*set)+lh)){	
makeLine(Xoff+(2*lw*roi)+(lw/2),Yoff+(2*lh*set)+lh,Xoff+(2*lw*roi)+lw+(lw/2),Yoff+(2*lh*set)+lh);
roiManager("add");
}	
}
}

n=roiManager("count");
roiManager("select", 0);
roiManager("rename", "region");
Reg_area=getValue("Area");
for (roi=1;roi<n;roi++){
	roiManager("select", roi);
	roiManager("rename", "Line "+roi);
}

setBatchMode("exit and display");

roiManager("UseNames", "true");
roiManager("Show All with labels");


run("Text Window...", "name=[Grid Summary] width=65 height=3 monospaced");
setLocation(0, 0);
print("[Grid Summary]", "\\Update: Region Area = "+Reg_area+" sq "+unit+"\n Line Length = "+ln+" "+unit+"\n Number of Lines = "+n-1);

}







/////////////////////////////////////////////10

macro "Multi crop an image (v2) Action Tool - C000 R1055 R1755 R9055 R9755 R1e55 R9e55 " {

//initialise and get info
{
a=nImages; 
if(a>0){};
else {
	 exit("No Image open")
};

fl=getTitle();
getDimensions(width, height, channels, slices, frames);
w=width;
h=height;
c=channels;
z=slices;
f=frames;

//defaults
xt=200;
yt=200;
xs=250;
ys=250;
xn=8;
yn=8;

roiManager("reset");
roiManager("Show all");

Dialog.create("Select");
  Dialog.addMessage("Select method:");
  todo = newArray("Known size ROI - Point select", "Select ROI size - Point select", 
  "Known size ROI - Array Select - Known spacing", "Select ROI size - Array Select - Select spacing" );
  Dialog.addRadioButtonGroup("What do you want to do?", todo, 4, 2, "Known size ROI - Point select");
Dialog.show;
  
op = Dialog.getRadioButton(); 

// option 1
if (op == "Known size ROI - Point select" )
{
Dialog.create("Roi size:");
  Dialog.addMessage("Enter X and Y size for ROI");
  Dialog.addNumber("X dimension ", xt, 0, 1," pixels" );
  Dialog.addNumber("Y dimension ", yt, 0, 1," pixels" );
Dialog.show;
  
xt = Dialog.getNumber(); 
yt = Dialog.getNumber(); 

setTool("point");
title = "Get info";
msg = "Now mark centre of ROI's and add them to ROI manager by pressing t\n \nthen select OK to continue";
waitForUser(title, msg);
d=getImageID();
n=roiManager("count");
if(n==0){
	exit("No ROI's")
	};
process();
}

//option 2
else if (op == "Select ROI size - Point select")
{
setTool("rectangle");
title = "Get info";
msg = "Draw ROI at required size\n \nthen select OK to continue";
waitForUser(title, msg);
Roi.getBounds(x, y, width, height)
xt=width;
yt=height;

setTool("point");
title = "Get info";
msg = "Now mark centre of ROI's and add them to ROI manager by pressing t\n \nthen select OK to continue";
waitForUser(title, msg);
d=getImageID();
n=roiManager("count");
if(n==0){
	exit("No ROI's")
	};
process();
}

//option 3
else if (op == "Known size ROI - Array Select - Known spacing")
{
Dialog.create("Roi size and spacing:");
  Dialog.addMessage("Enter X and Y size and spacing for ROI");
  Dialog.addNumber("X dimension ", xt, 0, 1," pixels" );
  Dialog.addNumber("Y dimension ", yt, 0, 1," pixels" );
  Dialog.addNumber("x Spacing ", xs, 0, 1," pixels" );
  Dialog.addNumber("Y spacing ", ys, 0, 1," pixels" );
  Dialog.addMessage("Array size:");
  Dialog.addNumber("Number of images in X ", xn, 0, 1,"" );
  Dialog.addNumber("Number of images in Y ", yn, 0, 1,"" );
Dialog.show;
  
xt = Dialog.getNumber(); 
yt = Dialog.getNumber(); 
xs = Dialog.getNumber(); 
ys = Dialog.getNumber(); 
xn = Dialog.getNumber(); 
yn = Dialog.getNumber();

setTool("point");
title = "Get info";
msg = "Now mark centre of top right ROI and add to ROI manager by pressing t\n \nthen select OK to continue";
waitForUser(title, msg);
Roi.getBounds(x, y, width, height);

b=y;
for (i=1; i<=yn; i++){
for (j=0; j<xn; j++){ 
a=x+j*xs;
Roi.move(a, b);
roiManager("Add");
}
b=y+i*ys;
}
d=getImageID();
n=roiManager("count");
process();
}

//option 4
else if (op == "Select ROI size - Array Select - Select spacing")
{
//get size
setTool("rectangle");
title = "Get info";
msg = "Draw ROI at required size\n \nthen select OK to continue";
waitForUser(title, msg);
Roi.getBounds(x, y, width, height)
xt=width;
yt=height;

//x spacing
setTool("line");
title = "Get info";
msg = "Now draw line in x for spacing \n \nthen select OK to continue";
waitForUser(title, msg);
Roi.getBounds(x, y, width, height);
xs=width;

//y spacing
setTool("line");
title = "Get info";
msg = "Now draw line in y for spacing\n \nthen select OK to continue";
waitForUser(title, msg);
Roi.getBounds(x, y, width, height);
ys=height;

//get array
Dialog.create("Roi size and spacing:");
  Dialog.addMessage("Array size:");
  Dialog.addNumber("Number of images in X ", xn, 0, 1,"" );
  Dialog.addNumber("Number of images in Y ", yn, 0, 1,"" );
Dialog.show;

xn = Dialog.getNumber(); 
yn = Dialog.getNumber();

//get start
setTool("point");
title = "Get info";
msg = "Now mark centre of top left ROI\n \nthen select OK to continue";
waitForUser(title, msg);
Roi.getBounds(x, y, width, height);

b=y;
for (i=1; i<=yn; i++){
for (j=0; j<xn; j++){ 
a=x+j*xs;
Roi.move(a, b);
roiManager("Add");
}
b=y+i*ys;
}
d=getImageID();
n=roiManager("count");
process();
}


//output
function process()
{
Dialog.create("Output");
  Dialog.addMessage("Output method:");
  outputoption = newArray("Save original and split channels to directory", "Save to directory", "Create Stack of images");
  Dialog.addRadioButtonGroup("What do you want to do?", outputoption, 3, 1, "Save original and split channels to directory");
Dialog.show;
  
outpt = Dialog.getRadioButton(); 

if (outpt == "Save original and split channels to directory")
{
output = getDirectory("Location for extracted images");
fln=getString("Filename:", fl);
CropSaveSplit(c,xt,yt);
}
else if (outpt == "Save to directory")
{
output = getDirectory("Location for extracted images");
fln=getString("Filename:", fl);
CropSave(c,xt,yt);
}
else if (outpt == "Create Stack of images")
{
CropStack(c,xt,yt);
}
}

//save individuals
function CropSaveSplit(c,xt,yt)
{

for (i=0; i<n; i++)
{

selectImage(d);
roiManager("select", i);
a=i+1;
roiManager("Rename",  a);
selectImage(d);

Roi.getBounds(x, y, width, height);
x=x-(xt/2);
y=y-(yt/2) ;
makeRectangle(x, y, xt, yt);

b=fln + " ROI " + a;
out = output + b;
run("Duplicate...", "title=[temp] duplicate channels=1-c");
saveAs("Tiff", out);
run("Split Channels");

for (g=1; g<=c; g++){
Chan="C" + g + "-" + b + ".tif";	
out = output + Chan;
selectWindow(Chan);
saveAs("Tiff", out);
close();
}
}
}

function CropSave(c,xt,yt)
{

for (i=0; i<n; i++)
{

selectImage(d);
roiManager("select", i);
a=i+1;
roiManager("Rename",  a);
selectImage(d);

Roi.getBounds(x, y, width, height);
x=x-(xt/2);
y=y-(yt/2) ;
makeRectangle(x, y, xt, yt);

b=fln + " ROI " + a;
out = output + b;
run("Duplicate...", "title=[temp] duplicate channels=1-c");
saveAs("Tiff", out);
close();
}
}
}

//create stack
function CropStack(c,xt,yt)
{
selectImage(d);

getVoxelSize(width, height, depth, unit);
units=unit;
px=width;
pz=depth;

roiManager("select", 0);
Roi.getBounds(x, y, width, height)
x=x-(xt/2);
y=y-(yt/2) ;
makeRectangle(x, y, xt, yt);
run("Duplicate...", "title=[total.czi] duplicate channels=1-c");

for (i=1; i<n; i++){
selectImage(d);
roiManager("select", i);

selectImage(d);

Roi.getBounds(x, y, width, height)
x=x-(xt/2);
y=y-yt/2;
makeRectangle(x, y, xt, yt);

	run("Duplicate...", "title=[new.czi] duplicate channels=1-c");
	run("Concatenate...", "  title=[total.czi] image1=[total.czi] image2=[new.czi]");
}
newscale="distance=1 known=" + px + " pixel=1 unit=" + units;
run("Set Scale...", newscale);
}

}





/////////////////////////////////11


macro "Measure change in rotation Action Tool - C000 L18e1 L18ef Cg00 P76887b C00g P91e1a5 Pbbefaf"
{

//setup
roiManager("Reset");
roiManager("Show All with labels");
setTool("arrow");
run("Arrow Tool...", "width=2 size=8 color=Yellow style=Notched");

//get frame info
t=Stack.getFrameInterval();
Stack.getUnits(X, Y, Z, Time, Value);
fn=getTitle();

//add arrows and measure
title = "Add ROI's";
msg = "Add lines to roi Manager(t)\n \n then select OK to continue";
waitForUser(title, msg);

n=roiManager("Count");
if (n==0){
	exit("no ROI's");
}
run("Clear Results");
roiManager("Measure");


//calculate angles
AngleMeasures=newArray(n);
AngleChange=newArray(n-1);
AngleAccumulative=newArray(n-1);
Fr=newArray(n-1);
//measure angle
for (i=0;i<n;i++){
	AngleMeasures[i]=getResult("Angle", i);
	if (AngleMeasures[i]<0){
		AngleMeasures[i]=AngleMeasures[i]+360;
	}
}

//calculate change in angle
for (k=0;k<n-1;k++){
	Fr[k]=t*(k+1);
	AngleChange[k]=AngleMeasures[k]-AngleMeasures[k+1];
	if (AngleChange[k]>180){
		AngleChange[k]=AngleChange[k]-360;
	}
	if (AngleChange[k]<-180){
		AngleChange[k]=AngleChange[k]+360;
	}
acc=AngleChange[k];
if (acc<0){
	acc=acc*-1;
}
//calculate accumulative angle
AngleAccumulative[k]=acc;
if (k>0){
	AngleAccumulative[k]=AngleAccumulative[k-1]+acc;
}

}
//tidy up
run("Clear Results");
selectWindow("Results");
run("Close");

//print results
for (rot=0;rot<n-1;rot++){
	 setResult("Angle anti-clockwise from Horizontal", rot, AngleMeasures[rot]);
	 setResult("Time ("+Time+")", rot+1, Fr[rot]);
     setResult("Change of Angle (-ve anti-clockwise)", rot+1, AngleChange[rot]);
     setResult("Accumulative Angle Change", rot+1, AngleAccumulative[rot]);
}
setResult("Angle anti-clockwise from Horizontal", rot, AngleMeasures[n-1]);

//plot results
if (t!=0){
Array.getStatistics(Fr, min, max, mean, stdDev);
tmin=min;
tmax=max;
Array.getStatistics(AngleAccumulative, min, max, mean, stdDev);
//accmin=min;
accmax=max;
Array.getStatistics(AngleChange, min, max, mean, stdDev);
accmin=min;
//accmax=max;

        Plot.create("Accumulation Plot", "Time (" + Time + ")", "Angle");
        Plot.setLimits(tmin, tmax, accmin, accmax);
//        Plot.setFrameSize(500, 300);
        Plot.setLineWidth(2);
        Plot.setColor("Red");     
        Plot.add("line",Fr, AngleAccumulative);
        Plot.addText("Accumulative", 0.1, 0);
        Plot.setColor("Blue");     
        Plot.add("line",Fr, AngleChange);        
        Plot.addText("Angle Change", 0.3, 0);
        
Plot.show();
}

setTool("line");
IJ.renameResults("Results",fn+" - Angle Data");
}



//*****************************************************12

macro "Radial measures Action Tool -  C0g0 H3373a1f4g6eeaf4h3e3c2b4800  C000 G3373a1f4g6eeaf4h3e3c2b4800 L8g82 L38g8 L33dd L3dd3 "
{
//imitialize
fn=getTitle();
getVoxelSize(px, py, pz, unit);
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
roiManager("Reset");
run("Clear Results");
setTool("rectangle");
run("Select None");
run("Set Measurements...", "area mean min centroid perimeter feret's display redirect=None decimal=3");
run("Point Tool...", "type=Crosshair color=White size=Medium label");

//get options
Dialog.create("Options");
	opt=newArray("Yes", "No");
	Dialog.addChoice("Do you want to crop the image: ", opt, "No");
	Dialog.addChoice("Do you want to scale the image: ", opt, "No");
	Dialog.addNumber("If scaling use factor:", 3);
	obj=newArray("Drawing","Threshold");
	Dialog.addChoice("Create cell shape by ", obj, "Drawing");
	ctr=newArray("Marking", "Cell Auto", "Threshold");
	Dialog.addChoice("Create centre point by ", ctr, "Marking");
Dialog.show();

//get responses
crp=Dialog.getChoice();
scl=Dialog.getChoice();
sc=Dialog.getNumber() ;
addcell=Dialog.getChoice();
addcentre=Dialog.getChoice();

	
//crop
if (crp=="Yes"){
title = "Crop";
msg = "draw crop region\n then select OK to continue";
waitForUser(title, msg);
run("Crop");
}


//scale
if (scl=="Yes"){
new="x="+sc+" y="+sc+" z=1.0  interpolation=Bilinear average create";
run("Scale...",new );
}
getVoxelSize(px, py, pz, unit);
setTool("freehand");


///ADD CELL ******************************************************************************

//by drawing 
if (addcell=="Drawing"){
waitForUser("Cell shape", "Draw cell shape\n then select OK to continue");
roiManager("Add");
roiManager("Select", 0);
roiManager("Rename", "Cell Area");
Roi.getCoordinates(xpoints, ypoints);
}

//by threshold 
if (addcell=="Threshold"){
if (bitDepth()==24 || is("composite")==true){
Stack.setDisplayMode("color");
}
do {
	roiManager("Reset");
waitForUser("Cell shape", "Select channel to create cell shape by threshold (draw roi to exclude outside)\n then select OK to continue");
run("Analyze Particles...", "size=25.00-Infinity show=Nothing add");
if (roiManager("Count")!=1){
	print("more than 1 object is selected - try again");
}
} while (roiManager("Count")!=1);

roiManager("Select", 0);
roiManager("Rename", "Cell Area");
Roi.getCoordinates(xpoints, ypoints);
}

//get line length and centre
roiManager("Select", 0);
roiManager("measure");
length=floor(getResult("Feret", 0)/px);
centreX=floor(getResult("X", 0)/px);
centreY=floor(getResult("Y", 0)/py);
selectWindow("Results");
run("Close");



//ADD CENTRE **************************************************************

//by marking
if (addcentre=="Marking"){
setTool("point");
run("Select None");
waitForUser("Cell centre", "Mark centre point of cell\n then select OK to continue");
roiManager("Add");
roiManager("Select", 1);
roiManager("Rename", "Cell centre");
Roi.getCoordinates(centrepointX, centrepointY);
roiManager("Show All");
}


//by cell auto
if (addcentre=="Cell Auto"){
makePoint(centreX, centreY);
roiManager("Add");
roiManager("Select", 1);
roiManager("Rename", "Cell centre");
Roi.getCoordinates(centrepointX, centrepointY);
}



//by threshold
if (addcentre=="Threshold"){
if (bitDepth()==24 || is("composite")==true){
Stack.setDisplayMode("color");
}
do {
waitForUser("Cell centre", "Select channel for centre point and threshold\n then select OK to continue");
run("Analyze Particles...", "size=25.00-Infinity show=Nothing add");
roin=roiManager("Count");
if (roin!=2){
	print("more than 1 centre is selected");
	for (rn=roin;rn>1;rn--){
		roiManager("select",rn-1);
		roiManager("Delete");
	}
}
} while (roiManager("Count")!=2);

roiManager("Select", 1);
roiManager("measure");
centreX=floor(getResult("X", 0)/px);
centreY=floor(getResult("Y", 0)/py);
selectWindow("Results");
run("Close");
roiManager("Select", 1);
roiManager("delete");
makePoint(centreX, centreY);
roiManager("Add");
roiManager("Select", 1);
roiManager("Rename", "Cell centre");
Roi.getCoordinates(centrepointX, centrepointY);
}

//****************************


//set constants
n=getNumber("Angle change of lines from centre (degrees)", 15);
angstep=n;
angnum=360/angstep;
xcoord=newArray(length);
ycoord=newArray(length);



//create line
for (ln=0;ln<length;ln++){
	xcoord[ln]=ln+centrepointX[0];
	ycoord[ln]=centrepointY[0];
}

makeSelection("freehand", xcoord, ycoord);
roiManager("Add");


//////////////////main routine
for (ang=0;ang<angnum;ang++){
	
roiManager("Select", 0);
//checks if in roi
for (k=0;k<length;k++){
yes=selectionContains(xcoord[k], ycoord[k]);
if (yes==true){
	x2=xcoord[k];
	y2=ycoord[k];
}
}
//Draws line
makeLine(centrepointX[0], centrepointY[0], x2, y2);
roiManager("Add");
roiManager("Select", ang+3);
roiManager("Rename", "line "+ang+1);

roiManager("Select", 2);
run("Rotate...", "  angle="+(angstep));
roiManager("Update");
getSelectionCoordinates(xcoord, ycoord);


xt=centrepointX[0]-xcoord[0];
yt=centrepointY[0]-ycoord[0];

roiManager("Select", 2);
roiManager("translate", xt, yt);
roiManager("Update");
getSelectionCoordinates(xcoord, ycoord);

}

//finish up
if (ImageChannels>1){
	Stack.setDisplayMode("composite");
}
roiManager("Select", 2);
roiManager("Delete");
roiManager("measure");
roiManager("Show All");
setTool("rectangle");
IJ.renameResults("Results",fn+" - Data");
}



////////////////////////////////////////13

macro "Draw Max/Min Ferets Action Tool - C0g0 H3373a1f4g6eeaf4h3e3c2b4800 C000 G3373a1f4g6eeaf4h3e3c2b4800 Cg00 L3gd2 L33dd" 
{

//Draws the min feret at right angles to the feret at the centre of the roi
//initialise
run("Set Measurements...", "area mean min centroid feret's display redirect=None decimal=3");
getVoxelSize(px, py, pz, unit);
fn=getTitle();

// option to keep original rois
Dialog.create("Options");
Dialog.addMessage("!! Please Note !! \n - Generate ROI's before running this macros");
Dialog.addCheckbox("Display Maximum Feret", true);
Dialog.addCheckbox("Display Minimum Feret", true);
Dialog.addCheckbox("Keep Original ROI's", true);
Dialog.show();

display_feret=Dialog.getCheckbox();
display_minferet=Dialog.getCheckbox();
Keep=Dialog.getCheckbox();


n=roiManager("Count");

if (n<1){
exit("no ROI's");
}

//create Arrays
angle=newArray(n);
Feret_length=newArray(n);
minFeret_width=newArray(n);
ROI=newArray(n);


//generate results table
run("Clear Results");
roiManager("Deselect");
roiManager("Measure");


//routine to generate Ferets
for (roi=0;roi<n;roi++){
dir=1;

roiManager("select", roi);
roiManager("rename", "ROI "+roi+1);
ROI[roi]="ROI "+roi+1;

//get data from result table
Feret_x1=getResult("FeretX",roi);
Feret_y1=getResult("FeretY",roi);
angle[roi]=getResult("FeretAngle",roi);
Feret_length[roi]=getResult("Feret",roi);
minFeret_width[roi]=getResult("MinFeret",roi);

//check direction
if (angle[roi]>90){
	dir=-1;
}
//convert to radians and calculate x and y end position
an=angle[roi]*0.0174533;

//make feret an add to roimanager
if (display_feret==true){
Feret_x2=cos(an)*Feret_length[roi]/px;
Feret_y2=sin(an)*Feret_length[roi]/px;
makeLine(Feret_x1, Feret_y1, (Feret_x1+(Feret_x2*dir)),(Feret_y1-(Feret_y2*dir)));
roiManager("Add");
}

//make minferet an add to roimanager
if (display_minferet==true){
shiftX=(Feret_length[roi]-minFeret_width[roi])/2;
shiftdir=1;
if (angle[roi]<90){
	shiftdir=-1;
}
shiftY=shiftX*shiftdir;
minFeret_x1=Feret_x1;
minFeret_y1=Feret_y1;
minFeret_x2=(cos(an)*minFeret_width[roi]/px);
minFeret_y2=(sin(an)*minFeret_width[roi]/px);
makeLine(minFeret_x1+shiftX, minFeret_y1+shiftY, (minFeret_x1+shiftX+(minFeret_x2*dir)),(minFeret_y1+shiftY-(minFeret_y2*dir)));
run("Rotate...", "angle=90");
roiManager("Add");
}
}

//remove original rois
if (Keep!=true){
	all=Array.getSequence(n);
	roiManager("Select",all);
	roiManager("Delete");
}

//rename results
IJ.renameResults("Results",fn+" - Feret Data");
roiManager("show all without labels");

//display arrays
Array.show(fn+" Feret Data",ROI,angle,Feret_length,minFeret_width);
}


////////////////////////////////////////////////////////////////////////14

macro "% Cell Confluency (Brightfield) Action Tool - C999 F00hh C6g6 H836477597c6dbeaac8a30 C000 R00hh" 
{
Dialog.create("Info");
	Dialog.addMessage("Instructions:");
	Dialog.addMessage("When prompted set the Variance Radius value to select the best cell area");
	Dialog.addMessage("i.e.- Try values between 2 and 8 pixels using the preview option to test the result");
Dialog.show()

run("Set Measurements...", "area mean min area_fraction limit display redirect=None decimal=2");
fn=getTitle();
roiManager("reset");

run("Duplicate...", "title=["+fn+" cell area]");

//process to find scratch
//***************************************************
run("8-bit");
run("Variance...", "");
//***************************************************

setAutoThreshold("Default dark");
//run("Threshold...");
run("Measure");
run("Create Selection");
roiManager("Add");
roiManager("Set Fill Color", "#4d00ff00");
close();
selectWindow(fn);
roiManager("Show All without labels");

}


/////////////////////////////////////////////////////////////////////////15

macro "Scratch/Wound Assay Action Tool - C6g6 F00hh C888 H806477597c6hbhaac8a00 C000 R00hh" 
{

//initialise
roiManager("reset");
run("Colors...", "foreground=White background=black selection=Green");

cols=newArray("White","Black","Red","Green","Blue","Magenta","Cyan","Yellow");
run("Clear Results");
TotalArea=0;
curr=0;

//image info
fn=getTitle();
getDimensions(ImageWidth, ImageHeight, ImageChannels, imageSlices, ImageFrames);
bd=bitDepth();
if (bd==24 || ImageChannels>1){
run("8-bit");
}

P1=ImageWidth/50;
P2=ImageHeight/25;
Th=ImageHeight/50;
getVoxelSize(px, py, pz, unit);

//options
Dialog.create("Overlay options");
	Dialog.addMessage("Mask Options");
	Dialog.addNumber("Minimum area to include (Sq "+unit+"):",5000);
	Dialog.addCheckbox("Exlcude cells inside scratch region", true);
	Dialog.addMessage("Instructions");
	Dialog.addMessage("When prompted set the Variance Radius to select the best area");
	Dialog.addMessage("- Try values between 4 to 7 pixels using the preview option to see the result");
	Dialog.addMessage("Overlay Options");
	Dialog.addChoice("Colour of the Overlay", cols, "White");
	Dialog.addNumber("Line thickness:",2);
	Dialog.addCheckbox("Print measured areaa on the overlay", true);
Dialog.show(); 

//responses
MinSize=Dialog.getNumber();
FillHoles=Dialog.getCheckbox();
Overlay_colour=Dialog.getChoice();
Line_thick=Dialog.getNumber(); 
ann=Dialog.getCheckbox();
run("Colors...", "foreground="+Overlay_colour+" background=black selection=Green");
run("Line Width...", "line="+Line_thick);

//create copies
run("Duplicate...", "title=[Overlay of "+fn+"]");
run("Duplicate...", "title=scratch");

//process to find scratch
//***************************************************
run("8-bit");
run("Variance...", "");
//***************************************************

//threshold and create mask
setAutoThreshold("Default");
run("Threshold...");
waitForUser("Set threshold", "set threshold\n and select OK to continue");
setOption("BlackBackground", true);
run("Convert to Mask");

//remove cells in scratch region
if (FillHoles==true){
	run("Fill Holes");
}

//create rois and mask
setAutoThreshold("Default dark");
run("Analyze Particles...", "size="+MinSize+"-Infinity show=Masks add"); // set minimum size
selectWindow("scratch");
close();

//test to see if rois exist
n=roiManager("Count");
if (n==0){
	makeRectangle(1, 1, 1, 1);
	roiManager("Add");
}
n=roiManager("Count");

// create overlay roi
selectWindow("Mask of scratch");
run("Create Selection");
roiManager("add");

//measure and rename rois 
selectWindow("Mask of scratch");
setAutoThreshold("Default");	
for (roi=0;roi<n;roi++){
rename(fn+" Scratch Region "+roi+1);
roiManager("Select",roi);
Roi.setStrokeWidth(2);
roiManager("Set Color", "green");
roiManager("rename","Scratch Region "+roi+1);
run("Analyze Particles...", "size=0-Infinity show=Nothing summarize");
}
selectWindow(fn+" Scratch Region "+roi);
close();

//get total area
Table.rename("Summary", fn+" Measurements");
TotalArea=0;
for (roi=0;roi<n;roi++){
tempArea=Table.get("Total Area", roi);
TotalArea=TotalArea+tempArea;
}


//create overlay
selectWindow("Overlay of "+fn);
run("RGB Color");
roiManager("select", n);
roiManager("draw");
roiManager("select", n);
roiManager("delete");
if (ann==true){
annotate="Total Area = "+toString(TotalArea)+" Sq "+unit;
setFont("SansSerif", Th);
drawString(annotate, P1, P2, "black");
//makeText(annotate, P1, P2);
//roiManager("add & draw");
setFont("SansSerif", 12);
}
roiManager("Show None");
run("Colors...", "foreground=White background=black selection=Green");
run("Line Width...", "line=1");

}




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






