//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 "Change Channels LUT's Action Tool - Cccc F00hh C000 T0809L T6809U Td809T Cg00 T0g09R C0g0 T6g09G C00g Tdg09B" 
{

bit=bitDepth();

if (bit==24){
run("Make Composite");
}

getDimensions(width, height, channels, slices, frames);


Dialog.create("Change Channel Look-up Tables")
  Dialog.addMessage("Select Colour for each channel");
Colour = newArray("Red", "Green", "Blue", "Cyan", "Magenta", "Yellow", "Grays", "Light Blue", "HiLo", "16 colors", "Spectrum","lifetime");
for (i=1; i<=channels; i++) {
Ch="Channel " + i;
Dialog.addRadioButtonGroup(Ch, Colour, 2, 1, Colour[i-1]);
}
Dialog.show(); 


for (j=1; j<=channels; j++){
	if (channels>1){
	Stack.setChannel(j);
	}
newcol = Dialog.getRadioButton();
run(newcol);
}
}

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

macro "Multi Channel Intensity Line Profile Plots(v2) Action Tool - C0g0 L1h43 L43hd C00g L1d6e L6eh4 Cg00 L1649 L49h8 Cg00 L1649 L49h8 C000 T3408l T6408i T9408n Tf408e L000h L0hhh"
{
//plots an intensity profile of a multi channel image
//this version has auto LUT and plot size

run("Clear Results");

if (bitDepth()==24){
run("Make Composite");
}

setTool("line");

getDimensions(width, height, channels, slices, frames);
fn=getTitle();
getVoxelSize(px, py, pz, units);


bit=bitDepth();
yscalelim=pow(2, bit)-1;


//menu
Dialog.create("Plot size");
  Dialog.addMessage("Select Plot options: \n - if the colours appear wrong, you may need to re-set the LUT's\n - use the Change channel LUT's macro");
  range = newArray(" Set own limits ", " Full intensity range ", " Limit to upper signal "," Limit to signal range ");
  Dialog.addRadioButtonGroup("Select intensity range (y-axis)", range, 1, 4, " Limit to signal range ");
  Dialog.addNumber("Low intensity value ", 0, 0, 6," " );
  Dialog.addNumber("High intensity value ", yscalelim, 0, 6," " );
  Dialog.addMessage("Enter dimensions of plot window");
  Dialog.addNumber("X dimension ", 650, 0, 4," pixels" );
  Dialog.addNumber("Y dimension ", 350, 0, 4," pixels" );
  Dialog.addMessage("Set line width");
  Dialog.addNumber("Line width ", 1, 0, 4," pixels" );  
Dialog.show;

rangelimits = Dialog.getRadioButton();
lowy = Dialog.getNumber(); 
highy = Dialog.getNumber(); 
plotsizex = Dialog.getNumber(); 
plotsizey = Dialog.getNumber();
plotlinewidth = Dialog.getNumber();  


//draw line and get data
title = "Draw Profile";
msg = "Draw line \n \n then select OK to continue";
waitForUser(title, msg);

exist=selectionType();
if (exist==-1){
	exit("No selection - re-run macro");
}

Channel=getProfile();
xscalelen=lengthOf(Channel);


//get y range
highlevel=0;
lowlevel=yscalelim;
for (i=1;i<=channels;i++){
if (channels>1){
Stack.setChannel(i);
}
Channel=getProfile();
Array.getStatistics(Channel, lowtemp, hightemp, mean, stdDev);

if (hightemp>highlevel){
	highlevel=hightemp;
}
if (lowtemp<lowlevel){
	lowlevel=lowtemp;
}
}
extend=(highlevel-lowlevel)*0.025;
highlevel=highlevel + extend;
lowlevel=lowlevel - extend;


//get x range
	Distance=newArray(xscalelen);
for (g=0;g<xscalelen;g++){
	Distance[g]=g*px;
setResult("Distance (" + units +")", g, Distance[g]);
}


//y range selection
if (rangelimits==" Full intensity range "){
	ymax=yscalelim;
	ymin=0;
}
if (rangelimits==" Set own limits "){
	ymax=highy;
	ymin=lowy;
}
if (rangelimits==" Limit to upper signal "){
	ymax=highlevel;
	ymin=0;
}
if (rangelimits==" Limit to signal range "){
	ymin=lowlevel;
	ymax=highlevel;
}


//main plot and results
        Plot.create(fn+" - Multi-Channel Intensity Plot", "Distance (" + units + ")", "Intensity");
        Plot.setLimits(0, xscalelen*px, ymin, ymax);
        Plot.setFrameSize(plotsizex, plotsizey);
        Plot.setLineWidth(plotlinewidth);
for (i=0;i<channels;i++){
if (channels>1){
Stack.setChannel(i+1);
}
col=lookup();
Channel=getProfile();
name="Channel " + i+1;
for (row=0; row<lengthOf(Channel); row++)
{
setResult(name, row, Channel[row]);
}
		Plot.setColor(col);     
        Plot.add("line",Distance, Channel);
        Plot.addText("Channel " + i+1, i*0.1, 0);
}
Plot.show();

IJ.renameResults("Results",fn+" - Intensity Data");

//colour lookup

function lookup(){
getLut(reds, greens, blues);
Array.getStatistics(reds, min, max, mean, stdDev);
re=max;
RED=toHex(re);
if (re<17){
RED=RED+"0";	
}
Array.getStatistics(greens, min, max, mean, stdDev);
gr=max;
GREEN=toHex(gr);
if (gr<17){
GREEN=GREEN+"0";	
}
Array.getStatistics(blues, min, max, mean, stdDev);
bl=max;
BLUE=toHex(bl);
if (bl<17){
BLUE=BLUE+"0";	
}
col="#"+RED+GREEN+BLUE;
if (col=="#ffffff"){
col="Black";
}
return col;
}
}

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


macro "Multiple line Intensity Profile Plot Action Tool - C0g0 L1h43 L43hd C00g L1d6e L6eh4 Cg00 L1649 L49h8 Cg00 L1649 L49h8 C000 T3408l T6408i T9408n Tf408e L000h L0hhh C000 T3h07R T9h07O Thh07I"
{

//constants
colours = newArray("#4dff0000","#4d00ff00", "#4d0000ff","#4dff00ff","#4d00ffff","#4dffff00","#4dffc800","#4dffffff","#4d000000");
setTool("line");
lineWidth=1;
n=roiManager("count");


//get image info
fn=getTitle();
if (bitDepth()==24){
run("Make Composite");
}

getDimensions(width, height, channels, slices, frames);
getVoxelSize(px, py, pz, units);

if (slices>1 || frames>1){
	exit("This macro does not work on a Z or time series");
}



//get info
Dialog.create("Select Colour and Range");
	opt = newArray("Yes","No");
	if (n>0){
		Dialog.addChoice("Do you want to keep existing ROI's", opt, "Yes")
	}
	items = newArray("red","green","blue","magenta","cyan","yellow","orange","black","white");
	Dialog.addChoice("Colour", items, "green");

	Dialog.addChoice("Line Semi-Transparent ?", opt, "Yes")
	Dialog.addNumber("Line width", lineWidth);
	Dialog.addString("ROI Name", "Line", 12) 
Dialog.show();

if (n>0){
answer=Dialog.getChoice();
if (answer=="No"){
roiManager("Reset");	
}
}

col=Dialog.getChoice();
transparent=Dialog.getChoice();
lnwdth=Dialog.getNumber();
pre=Dialog.getString() ;

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];
}
}
}

//draw line and get data
title = "Draw Profile";
msg = "Draw lines and add to ROI manager (t) \n \n then select OK to continue";
waitForUser(title, msg);

n=roiManager("count");
if(n==0){
	exit("No ROI's")
	};
roiManager("deselect");
roiManager("Remove Channel Info");
roiManager("Remove Slice Info");
roiManager("Remove Frame Info");



//main routine
for (i=0; i<n; i++)
{
roiManager("select", i);
name=pre + " " + (i+1);
roiManager("Rename", name);
roiManager("Set Color", colour);
roiManager("Set Line Width", lnwdth);

}
roiManager("Deselect");



//start of analysis

//plots an intensity profile of a multi channel image
//this version has auto LUT and plot size

run("Clear Results");

bit=bitDepth();
yscalelim=pow(2, bit)-1;

//menu
Dialog.create("Plot size");
  Dialog.addMessage("Select Plot options: \n - if the colours appear wrong, you may need to re-set the LUT's\n - use the Change channel LUT's macro");
  range = newArray(" Set own limits ", " Full intensity range ", " Limit to upper signal "," Limit to signal range ");
  Dialog.addRadioButtonGroup("Select intensity range (y-axis)", range, 1, 4, " Limit to signal range ");
  Dialog.addNumber("Low intensity value ", 0, 0, 6," " );
  Dialog.addNumber("High intensity value ", yscalelim, 0, 6," " );
  Dialog.addMessage("Enter dimensions of plot window");
  Dialog.addNumber("X dimension ", 650, 0, 4," pixels" );
  Dialog.addNumber("Y dimension ", 350, 0, 4," pixels" );
  Dialog.addMessage("Set line width");
  Dialog.addNumber("Line width ", 1, 0, 4," pixels" );
  op = newArray("Yes","No"); 
  Dialog.addChoice("Autosave Results ?", op, "No");
  Dialog.addChoice("Close all images automatically ?", op, "No");
Dialog.show;

rangelimits = Dialog.getRadioButton();
lowy = Dialog.getNumber(); 
highy = Dialog.getNumber(); 
plotsizex = Dialog.getNumber(); 
plotsizey = Dialog.getNumber();
plotlinewidth = Dialog.getNumber();  
sv=Dialog.getChoice();
clearall=Dialog.getChoice();

if (sv=="Yes"){
	output = getDirectory("Location for results");
}


for (R=0;R<n;R++){
selectWindow(fn);
roiManager("select", R);

Channel=getProfile();
xscalelen=lengthOf(Channel);


//get y range
highlevel=0;
lowlevel=yscalelim;
for (i=1;i<=channels;i++){
if (channels>1){
Stack.setChannel(i);
}
Channel=getProfile();
Array.getStatistics(Channel, lowtemp, hightemp, mean, stdDev);

if (hightemp>highlevel){
	highlevel=hightemp;
}
if (lowtemp<lowlevel){
	lowlevel=lowtemp;
}
}
extend=(highlevel-lowlevel)*0.025;
highlevel=highlevel + extend;
lowlevel=lowlevel - extend;


//get x range
	Distance=newArray(xscalelen);
for (g=0;g<xscalelen;g++){
	Distance[g]=g*px;
setResult("Distance (" + units +")", g, Distance[g]);
}


//y range selection
if (rangelimits==" Full intensity range "){
	ymax=yscalelim;
	ymin=0;
}
if (rangelimits==" Set own limits "){
	ymax=highy;
	ymin=lowy;
}
if (rangelimits==" Limit to upper signal "){
	ymax=highlevel;
	ymin=0;
}
if (rangelimits==" Limit to signal range "){
	ymin=lowlevel;
	ymax=highlevel;
}


//main plot and results
        Plot.create(fn+ " Intensity Plot Line "+R+1, "Distance (" + units + ")", "Intensity");
        Plot.setLimits(0, xscalelen*px, ymin, ymax);
        Plot.setFrameSize(plotsizex, plotsizey);
        Plot.setLineWidth(plotlinewidth);
for (i=0;i<channels;i++){
if (channels>1){
Stack.setChannel(i+1);
}
col=lookup();
Channel=getProfile();
chname="Channel " + i+1 +" Line "+R+1;
for (row=0; row<lengthOf(Channel); row++)
{
setResult(chname, row, Channel[row]);
}
		Plot.setColor(col);     
        Plot.add("line",Distance, Channel);
        Plot.addText("Channel " + i+1, i*0.1, 0);
}
Plot.show();
if (sv=="Yes"){
out = output + fn + " Intensity Plot Line "+R+1;
saveAs("Jpeg", out);
}
}
IJ.renameResults("Results for "+fn);
if (sv=="Yes"){
out = output + fn + " results.xls";
saveAs("Results", out);

}
selectWindow(fn);
run("Stack to RGB");
roiManager("Show all with labels");
run("Flatten");
rename(fn+" overlay");
if (sv=="Yes"){
out = output + fn + " overlay";
saveAs("Jpeg", out);
roiManager("deselect");
roiManager("Save", output+fn+".zip");

if (clearall=="Yes" && sv=="Yes"){
selectWindow(fn + " results.xls");
run("Close");
run("Close All");
}
}


//colour lookuproiManager("Show all with labels");
function lookup(){
getLut(reds, greens, blues);
Array.getStatistics(reds, min, max, mean, stdDev);
re=max;
RED=toHex(re);
if (re<17){
RED=RED+"0";	
}
Array.getStatistics(greens, min, max, mean, stdDev);
gr=max;
GREEN=toHex(gr);
if (gr<17){
GREEN=GREEN+"0";	
}
Array.getStatistics(blues, min, max, mean, stdDev);
bl=max;
BLUE=toHex(bl);
if (bl<17){
BLUE=BLUE+"0";	
}
col="#"+RED+GREEN+BLUE;
if (col=="#ffffff"){
col="Black";
}
return col;
}
}


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

macro "Multi Channel Intensity Line Profile Plots for Z stacks Action Tool - C0g0 L1h43 L43hd C00g L1d6e L6eh4 Cg00 L1649 L49h8 Cg00 L1649 L49h8 C4dd F58aa C000 T3408l T6408i T9408n Tf408e L000h L0hhh T7h10Z"
{
//plots an intensity profile of a multi channel image
//this version has auto LUT and plot size

run("Clear Results");

if (bitDepth()==24){
run("Make Composite");
}

setTool("line");

getDimensions(width, height, channels, slices, frames);
fn=getTitle();

zfirst=1;
zlast=slices;


getVoxelSize(px, py, pz, units);


bit=bitDepth();
yscalelim=pow(2, bit)-1;

Stack.getPosition(channel, zcurr, frame);


//menu
Dialog.create("Plot size");
  Dialog.addMessage("Select Plot options: \n - if the colours appear wrong, you may need to re-set the LUT's\n - use the Change channel LUT's macro");
  range = newArray(" Set own limits ", " Full intensity range ", " Limit to upper signal "," Limit to signal range ");
  Dialog.addRadioButtonGroup("Select intensity range (y-axis)", range, 1, 4, " Limit to signal range ");
  Dialog.addNumber("Low intensity value ", 0, 0, 6," " );
  Dialog.addNumber("High intensity value ", yscalelim, 0, 6," " );
  Dialog.addMessage("Enter dimensions of plot window");
  Dialog.addNumber("X dimension ", 650, 0, 4," pixels" );
  Dialog.addNumber("Y dimension ", 350, 0, 4," pixels" );
  Dialog.addMessage("Set line width");
  Dialog.addNumber("Line width ", 1, 0, 4," pixels" );
  Dialog.addMessage("For Z Stacks - select the Z Range \n");
  Dialog.addNumber("First Z Slice ", zfirst, 0, 5, "" ); 
  Dialog.addNumber("Last Z Slice ", zlast, 0, 5, "");
  Dialog.addCheckbox("Just Current Slice Z="+zcurr, 0);  
Dialog.show;

rangelimits = Dialog.getRadioButton();
lowy = Dialog.getNumber(); 
highy = Dialog.getNumber(); 
plotsizex = Dialog.getNumber(); 
plotsizey = Dialog.getNumber();
plotlinewidth = Dialog.getNumber();  
zfirst = Dialog.getNumber();
zlast = Dialog.getNumber();
SingleZ= Dialog.getCheckbox();

if (zlast>slices || zlast<zfirst || zfirst<1){
	exit("Z out of Range");
}


//draw line and get data
title = "Draw Profile";
msg = "Draw line \n \n then select OK to continue";
waitForUser(title, msg);

exist=selectionType();
if (exist==-1){
	exit("No selection - re-run macro");
}


setBatchMode(true);
if (SingleZ==1){
	zfirst=zcurr;
	zlast=zcurr;
	setBatchMode(false);
}

Channel=getProfile();
xscalelen=lengthOf(Channel);

//get y range
highlevel=0;
lowlevel=yscalelim;


for (zslice=zfirst;zslice<=zlast;zslice++){
Stack.setSlice(zslice); 

for (i=1;i<=channels;i++){
if (channels>1){
Stack.setChannel(i);
}


Channel=getProfile();
Array.getStatistics(Channel, lowtemp, hightemp, mean, stdDev);

if (hightemp>highlevel){
	highlevel=hightemp;
}
if (lowtemp<lowlevel){
	lowlevel=lowtemp;
}
}
}
extend=(highlevel-lowlevel)*0.025;
highlevel=highlevel + extend;
lowlevel=lowlevel - extend;


//get x range
	Distance=newArray(xscalelen);
for (g=0;g<xscalelen;g++){
	Distance[g]=g*px;
setResult("Distance (" + units +")", g, Distance[g]);
}


//y range selection
if (rangelimits==" Full intensity range "){
	ymax=yscalelim;
	ymin=0;
}
if (rangelimits==" Set own limits "){
	ymax=highy;
	ymin=lowy;
}
if (rangelimits==" Limit to upper signal "){
	ymax=highlevel;
	ymin=0;
}
if (rangelimits==" Limit to signal range "){
	ymin=lowlevel;
	ymax=highlevel;
}


//main plot and results



for (zslice=zfirst;zslice<=zlast;zslice++){ 
    selectImage(fn);
	Stack.setSlice(zslice);      
        
        Plot.create("Multi-Channel Intensity Plot", "Distance (" + units + ")", "Intensity");
        Plot.setLimits(0, xscalelen*px, ymin, ymax);
        Plot.setFrameSize(plotsizex, plotsizey);
        Plot.setLineWidth(plotlinewidth);
for (i=0;i<channels;i++){
if (channels>1){
Stack.setChannel(i+1);
}
col=lookupColour();
Channel=getProfile();
name="Channel " + i+1 + " Z="+ zslice;
for (row=0; row<lengthOf(Channel); row++)
{
setResult(name, row, Channel[row]);
}
		Plot.setColor(col);     
        Plot.add("line",Distance, Channel);
        Plot.addText("Channel " + i+1, i*0.1, 0);
        Plot.setFontSize(12);
        Plot.setColor("Black"); 
        Plot.addText("slice (" + zslice + ") Z=" + zslice*pz +" "+ units , 0.75, 0.07);
        Plot.setFontSize(12);
}
Plot.show();
rename("Plot of " + fn + " Z=" + zslice);
}

if (zlast-zfirst>1){
join=" title=["+fn+" - Multichannel Plots] ";
n=1;
for (zslice=zfirst;zslice<=zlast;zslice++){
	join=join + " image"+n+"=[Plot of "+fn+" Z="+zslice+"]";
	n=n+1;
}

run("Concatenate...", join);

plot=1;
for (zslice=zfirst;zslice<=zlast;zslice++){
	Stack.setSlice(plot);
    setMetadata("Label", " Z Slice "+zslice+" ");
    plot=plot+1;
}
setBatchMode(false);

Stack.setSlice(1);
}


IJ.renameResults("Results",fn+" - Intensity Data");
//lookup colour

function lookupColour(){
getLut(reds, greens, blues);
Array.getStatistics(reds, min, max, mean, stdDev);
re=max;
RED=toHex(re);
if (re<17){
RED=RED+"0";	
}
Array.getStatistics(greens, min, max, mean, stdDev);
gr=max;
GREEN=toHex(gr);
if (gr<17){
GREEN=GREEN+"0";	
}
Array.getStatistics(blues, min, max, mean, stdDev);
bl=max;
BLUE=toHex(bl);
if (bl<17){
BLUE=BLUE+"0";	
}
col="#"+RED+GREEN+BLUE;
if (col=="#ffffff"){
col="Black";
}
return col;
}
}

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


macro "Intensity Time Plots (multi channel) Action Tool - C0g0 L1h43 L43hd C00g L1d6e L6eh4 Cg00 L1649 L49h8 C000 T3408t T6408i T9408m Tg408e L000h L0hhh"
{

run("Clear Results");

// intensity plot over time 
//get file info
getDimensions(width, height, channels, slices, frames);
fn=getTitle();

if (frames==1 && slices==1){
	exit("This is not a time series");
}

if (frames>1 && slices>1){
	exit("This macro does not work on a Z stack time series");
}

if (frames==1 && slices!=1){
con=getBoolean("Image has only 1 frame, but " + slices + " slicess, do you want to convert slices to frames");
if (con==1){
run("Stack to Hyperstack...", "order=xyczt(default) channels=1 slices=" + frames + " frames=" + slices + " display=Color");	
getDimensions(width, height, channels, slices, frames);

Stack.setTUnit("frame");
}
}


setTool("oval");

//get bit depth
bit=bitDepth();
yscalelim=pow(2, bit)-1;

// create array
ChannelData=newArray(frames*channels);


//get plot details
Dialog.create("Plot size");
  Dialog.addMessage("Select Plot options: \n - if the colours appear wrong, you may need to re-set the LUT's\n - use the Change channel LUT's macro");
  range = newArray(" Set own limits ", " Full intensity range ", " Limit to upper signal "," Limit to signal range ");
  Dialog.addRadioButtonGroup("Select intensity range (y-axis)", range, 1, 4, " Limit to signal range ");
  Dialog.addNumber("Low intensity value ", 0, 0, 6," " );
  Dialog.addNumber("High intensity value ", yscalelim, 0, 6," " );
  Dialog.addMessage("Enter dimensions of plot window");
  Dialog.addNumber("X dimension ", 650, 0, 4," pixels" );
  Dialog.addNumber("Y dimension ", 350, 0, 4," pixels" );
  Dialog.addMessage("Set line width");
  Dialog.addNumber("Line width ", 1, 0, 4," pixels" );  
Dialog.show;

rangelimits = Dialog.getRadioButton();
lowy = Dialog.getNumber(); 
highy = Dialog.getNumber(); 
plotsizex = Dialog.getNumber(); 
plotsizey = Dialog.getNumber();
plotlinewidth = Dialog.getNumber();  
ymin=0;


//draw roi and measure
title = "Draw Profile";
msg = "Draw Roi\n \n then select OK to continue";
waitForUser(title, msg);
roiManager("Reset");
roiManager("Add");
roiManager("Multi Measure");

for (i=0;i<frames*channels;i++){	
  ChannelData[i]=getResult("Mean1", i);
} 

selectWindow("Results");
run("Close");



//get y range
Array.getStatistics(ChannelData, lowlevel, highlevel, mean, stdDev);


extend=(highlevel-lowlevel)*0.025;
highlevel=highlevel + extend;
lowlevel=lowlevel - extend;


//get x range
Frame_Interval=newArray(frames);
Fr=Stack.getFrameInterval();
if (Fr==0){
	Fr=1;
}
Stack.getUnits(X, Y, Z, Time, Value);
for (fi=1;fi<frames;fi++){
Frame_Interval[fi]=fi * Fr;
} 
Array.getStatistics(Frame_Interval, min, xscalelen, mean, stdDev);

for (t=0;t<frames;t++){
      setResult("Frame Interval (" + Time + ")", t, Frame_Interval[t]);
}


//y range selection
if (rangelimits==" Full intensity range "){
	ymax=yscalelim;
	ymin=0;
}
if (rangelimits==" Set own limits "){
	ymax=highy;
	ymin=lowy;
}
if (rangelimits==" Limit to upper signal "){
	ymax=highlevel;
	ymin=0;
}
if (rangelimits==" Limit to signal range "){
	ymin=lowlevel;
	ymax=highlevel;
}


//main plot and results
Channel=newArray(frames);

        Plot.create(fn+" - Time Intensity Plot", "Time (" + Time + ")", "Intensity");
        Plot.setLimits(0, xscalelen, ymin, ymax);
        Plot.setFrameSize(plotsizex, plotsizey);
        Plot.setLineWidth(plotlinewidth);

for (k=0;k<channels;k++){
if (channels>1){
Stack.setChannel(k+1);
}

for (j=0;j<frames;j++){
	  Channel[j]=ChannelData[j*channels+(k)];	
      name="Channel " + k+1;
      setResult(name, j, Channel[j]);
}
col=lookup();
		Plot.setColor(col);     
        Plot.add("line",Frame_Interval, Channel);
        Plot.addText("Channel " + k+1, k*0.1, 0);
}
Plot.show();

IJ.renameResults("Results",fn+" - Intensity Data");

// select colour

function lookup(){
getLut(reds, greens, blues);
Array.getStatistics(reds, min, max, mean, stdDev);
re=max;
RED=toHex(re);
if (re<17){
RED=RED+"0";	
}
Array.getStatistics(greens, min, max, mean, stdDev);
gr=max;
GREEN=toHex(gr);
if (gr<17){
GREEN=GREEN+"0";	
}
Array.getStatistics(blues, min, max, mean, stdDev);
bl=max;
BLUE=toHex(bl);
if (bl<17){
BLUE=BLUE+"0";	
}
col="#"+RED+GREEN+BLUE;
if (col=="#ffffff"){
col="Black";
}
return col;
}
}

}

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

macro "Multi Roi (max 15) Intensity Time Plots (single channel) Action Tool - C0g0 L1h43 L43hd C00g L1d6e L6eh4 Cg00 L1649 L49h8 C000 T3508R T9508O Tf508I L000h L0hhh"
{
//constants
run("Set Measurements...", "area mean min centroid display redirect=None decimal=3");
requires("1.52a");
run("Clear Results");
setTool("oval");
n=roiManager("Count");
roiManager("Show All with labels");

//get file info
fn=getTitle();
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
getVoxelSize(px, py, pz, unit);


if (ImageFrames==1 && ImageSlices==1){
	exit("This is not a time series");
}
if (ImageFrames==1 && ImageSlices!=1){
con=getBoolean("Image has only 1 frame, but " + ImageSlices + " slicess, do you want to convert slices to frames");
if (con==1){
run("Stack to Hyperstack...", "order=xyczt(default) channels=1 slices=" + ImageFrames + " frames=" + ImageSlices + " display=Color");	
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);

Stack.setTUnit("frame");
}
}

//get bit depth
bit=bitDepth();
yscalelim=pow(2, bit)-1;

range = newArray(" Set own limits ", " Full intensity range ", " Limit to upper signal "," Limit to signal range ");


//get plot details
Dialog.create("Plot Details");
	opt = newArray("Yes","No");
	if (n>0){
		Dialog.addChoice("Do you want to keep existing ROI's", opt, "Yes")
	}
    Dialog.setInsets(0, 20, -10);
	Dialog.addMessage("Data Output Options:");
    Dialog.setInsets(20, 220, -35);
    Dialog.addCheckbox("Calculate maxima", false);
    Dialog.setInsets(0, 380, -10);
    Dialog.addRadioButtonGroup("Option: Include/Exclude Edges", newArray("Include","Exclude"), 1, 2, "Exclude");
	Dialog.addMessage("Plot Options:");
    Dialog.setInsets(20, 20, -30);
    Dialog.addRadioButtonGroup("Select intensity range (y-axis)", range, 1, 4, " Limit to signal range ");
    Dialog.addNumber("Low intensity value ", 0, 0, 6," pixels" );
    Dialog.addNumber("High intensity value ", yscalelim, 0, 6," pixels" );
    Dialog.addMessage("Enter dimensions of plot window");
    Dialog.addNumber("X dimension ", 650, 0, 4," pixels" );
    Dialog.addNumber("Y dimension ", 350, 0, 4," pixels" );
    Dialog.addMessage("Set line width");
    Dialog.addNumber("Line width ", 1, 0, 4," pixels" );  
Dialog.show;

if (n>0){
answer=Dialog.getChoice();
if (answer=="No"){
roiManager("Reset");	
}
}

Cal_Max=Dialog.getCheckbox();
edge=-1;
inc=Dialog.getRadioButton();

if (inc=="Include"){
	edge=0;
}
rangelimits = Dialog.getRadioButton();
lowy = Dialog.getNumber(); 
highy = Dialog.getNumber(); 
plotsizex = Dialog.getNumber(); 
plotsizey = Dialog.getNumber();
plotlinewidth = Dialog.getNumber();  
ymin=0;


//draw rois
waitForUser("Add ROI's", "Add ROI's to ROI Manager (Press t)\n \n then select OK to continue");

// create arrays
// create arrays
n=roiManager("count");

if (n<1){
exit("No ROI's have been added");	
}


roiManager("deselect");
roiManager("Remove Channel Info");
roiManager("Remove Slice Info");
roiManager("Remove Frame Info");
RoiData=newArray(ImageFrames*n);
RoiPlot=newArray(ImageFrames);
colours=newArray("red","green","blue","magenta","cyan","#FFFF22","#008833","#FF5500","#000000", "#660066", "#9966FF","#000033", "#330000", "#339966", "#33CC99");



//reame and colour and roi's
for (i=0;i<n;i++){
roiManager("select", i);
name="ROI " + i+1;
roiManager("Rename", name);
roiManager("Set Color", colours[i]);
}
roiManager("Deselect");
roiManager("Multi Measure");


for (roi=0;roi<n;roi++){
for (j=0;j<ImageFrames;j++){	
  RoiData[j+(ImageFrames*roi)]=getResult("Mean(ROI "+roi+1+")", j);
} 
}

selectWindow("Results");
run("Close");

//get y range
Array.getStatistics(RoiData, lowlevel, highlevel, mean, stdDev);


extend=(highlevel-lowlevel)*0.025;
highlevel=highlevel + extend;
lowlevel=lowlevel - extend;


//get x range
Frame_Interval=newArray(ImageFrames);
Fr=Stack.getFrameInterval();
if (Fr==0){
	Fr=1;
}
Stack.getUnits(X, Y, Z, time_unit, Value);
for (fi=1;fi<ImageFrames;fi++){
Frame_Interval[fi]=fi * Fr;
} 
Array.getStatistics(Frame_Interval, min, xscalelen, mean, stdDev);


//y range selection
if (rangelimits==" Full intensity range "){
	ymax=yscalelim;
	ymin=0;
}
if (rangelimits==" Set own limits "){
	ymax=highy;
	ymin=lowy;
}
if (rangelimits==" Limit to upper signal "){
	ymax=highlevel;
	ymin=0;
}
if (rangelimits==" Limit to signal range "){
	ymin=lowlevel;
	ymax=highlevel;
}


//main plot and results
Channel=newArray(ImageFrames);
Table.create("Data");
Table.setLocationAndSize(100,600 ,600, 300);

for (t=0;t<ImageFrames;t++){
      Table.set("Frame Interval (" + time_unit + ")", t, Frame_Interval[t]);
}

        Plot.create(fn+" - Time Intensity Plot", "Time (" + time_unit + ")", "Intensity");
        Plot.setLimits(0, xscalelen, ymin, ymax);
        Plot.setFrameSize(plotsizex, plotsizey);
        Plot.setLineWidth(plotlinewidth);

for (m=0;m<n;m++){
for (p=0;p<ImageFrames;p++){
	  RoiPlot[p]=RoiData[p+(ImageFrames*m)];	
      name="Roi " + m+1;
      Table.set(name, p, RoiPlot[p]);
}
		Plot.setColor(colours[m]);     
        Plot.add("line",Frame_Interval, RoiPlot);
        Plot.addText("ROI " + m+1, m*0.1, 0);
}

Plot.show();

Table.rename("Data",fn+" - Intensity Data");


//get maxima
if (Cal_Max==true){
Array.getStatistics(RoiData, RoiData_min, RoiData_max, RoiData_mean, RoiData_stdDev);
Tolerance=(RoiData_max-RoiData_min)/5;
Tolerance=getNumber("input Tolerance (range = "+RoiData_min+"-"+RoiData_max+").  20% of this value is: ",Tolerance);

Table.create(fn+" Peak Maxima for ROI's");
Table.setLocationAndSize(100,200 , 300, 400);
for (roi=0;roi<n;roi++){
max_data=Array.slice(RoiData,ImageFrames*roi,ImageFrames+ImageFrames*roi);
// find maima and minima
Max_Time=Array.findMaxima(max_data, Tolerance, edge);
Max_Time=Array.sort(Max_Time);
for (max_value=0;max_value<Max_Time.length;max_value++){
	Max_Time[max_value]=Max_Time[max_value]*Fr;
}
//MinTime=Array.findMinima(RoiData, Tolerance);
Table.setColumn("Max Peak Roi "+roi+1+"("+time_unit+")", Max_Time);	
}

Table.create(fn+" ROI Location");
Table.setLocationAndSize(400,200 , 300, 200);
selectWindow(fn);
for (roi=0;roi<n;roi++){
roiManager("select", roi);
Table.set("ROI", roi , roi+1);
Table.set("X ("+unit+")", roi , getValue("X"));
Table.set("Y ("+unit+")", roi , getValue("Y"));
}
}
run("Select None");

//finish up
selectWindow(fn);
roiManager("Show All with labels");


}

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

macro "Intensity Time Plots (multi channel/multi ROI) Action Tool - C0g0 L1h43 L43hd C00g L1d6e L6eh4 Cg00 L1649 L49h8 C000 T3408t T6408i T9408m Tg408e T3h08R Tah08O Tgh08I L000h L0hhh"
{
//init
fn=getTitle();
run("Clear Results");
n=roiManager("Count");
roiManager("Deselect");
setTool("oval");

// intensity plot over time 
//get file info
getDimensions(width, height, channels, slices, frames);

//check if time series
if (frames==1 && slices==1){
	exit("This is not a time series");
}
if (frames>1 && slices>1){
	exit("This macro does not work on a Z stack time series");
}
if (frames==1 && slices!=1){
con=getBoolean("Image has only 1 frame, but " + slices + " slicess, do you want to convert slices to frames");
if (con==1){
run("Stack to Hyperstack...", "order=xyczt(default) channels=1 slices=" + frames + " frames=" + slices + " display=Color");	
getDimensions(width, height, channels, slices, frames);

Stack.setTUnit("frame");
}
}


//get bit depth
bit=bitDepth();
yscalelim=pow(2, bit)-1;

// create array
//ChannelData=newArray(frames*channels*n);


//get plot details
Dialog.create("Plot size");
	opt = newArray("Yes","No");
	if (n>0){
	Dialog.addChoice("Do you want to keep existing ROI's", opt, "Yes")
	}
	Dialog.addMessage("Select Plot options: \n - if the colours appear wrong, you may need to re-set the LUT's\n - use the Change channel LUT's macro");
	range = newArray(" Set own limits ", " Full intensity range ", " Limit to upper signal "," Limit to signal range ");
	Dialog.addRadioButtonGroup("Select intensity range (y-axis)", range, 1, 4, " Limit to signal range ");
	Dialog.addNumber("Low intensity value ", 0, 0, 6," " );
	Dialog.addNumber("High intensity value ", yscalelim, 0, 6," " );
	Dialog.addMessage("Enter dimensions of plot window");
	Dialog.addNumber("X dimension ", 650, 0, 4," pixels" );
	Dialog.addNumber("Y dimension ", 350, 0, 4," pixels" );
	Dialog.addMessage("Set line width");
	Dialog.addNumber("Line width ", 1, 0, 4," pixels" );  
Dialog.show;

if (n>0){
answer=Dialog.getChoice();
if (answer=="No"){
roiManager("Reset");	
}
}

rangelimits = Dialog.getRadioButton();
lowy = Dialog.getNumber(); 
highy = Dialog.getNumber(); 
plotsizex = Dialog.getNumber(); 
plotsizey = Dialog.getNumber();
plotlinewidth = Dialog.getNumber();  
ymin=0;


//draw roi's
title = "Draw Rois";
msg = "Add ROI's - draw and press [t] \n \n then select OK to continue";
waitForUser(title, msg);
roiManager("deselect");
roiManager("Remove Channel Info");
roiManager("Remove Slice Info");
roiManager("Remove Frame Info");
n=roiManager("Count");
data=frames*channels;
ChannelData=newArray();

for (roi=0;roi<n;roi++){
	roiManager("select", roi);
	roiManager("rename", "ROI "+roi+1);
}


//get data
selectWindow(fn);
roiManager("deselect");
roiManager("Multi Measure");
for (roi=0;roi<n;roi++){
roi_data=Table.getColumn("Mean(ROI "+roi+1+")");
ChannelData=Array.concat(ChannelData,roi_data);
}
selectWindow("Results");
run("Close");


//get y range
Array.getStatistics(ChannelData, lowlevel, highlevel, mean, stdDev);
extend=(highlevel-lowlevel)*0.025;
highlevel=highlevel + extend;
lowlevel=lowlevel - extend;


//get x range
Frame_Interval=newArray(frames);
Fr=Stack.getFrameInterval();
if (Fr==0){
	Fr=1;
}

Stack.getUnits(X, Y, Z, Time, Value);
for (fi=1;fi<frames;fi++){
Frame_Interval[fi]=fi * Fr;
} 

Array.getStatistics(Frame_Interval, min, xscalelen, mean, stdDev);


//print data
for (t=0;t<frames;t++){
      setResult("Frame Interval (" + Time + ")", t, Frame_Interval[t]);
}

for (roi=0;roi<n;roi++){
for (row=0;row<frames;row++){
	for (ch=0;ch<channels;ch++){
	setResult("Roi "+roi+1+" Ch "+ch+1+" Intensity", row, ChannelData[ch+(channels*row)+(data*roi)]);
}
}
}


//y range selection
if (rangelimits==" Full intensity range "){
	ymax=yscalelim;
	ymin=0;
}
if (rangelimits==" Set own limits "){
	ymax=highy;
	ymin=lowy;
}
if (rangelimits==" Limit to upper signal "){
	ymax=highlevel;
	ymin=0;
}
if (rangelimits==" Limit to signal range "){
	ymin=lowlevel;
	ymax=highlevel;
}



//plot routine

for (roi=0;roi<n;roi++){
selectWindow(fn);
roiManager("Select",roi);

Channel=newArray(frames);
       Plot.create("Roi "+roi+1, "Time (" + Time + ")", "Intensity");
       Plot.setLimits(0, xscalelen, ymin, ymax);
       Plot.setFrameSize(plotsizex, plotsizey);
       Plot.setLineWidth(plotlinewidth);

for (k=0;k<channels;k++){
if (channels>1){
Stack.setChannel(k+1);
}

for (j=0;j<frames;j++){
//key line
	Channel[j]=getResult("Roi "+roi+1+" Ch "+k+1+" Intensity", j);
}  

col=lookup();
		Plot.setColor(col);     
        Plot.add("line",Frame_Interval, Channel);
        Plot.addText("Channel " + k+1, k*0.1, 0);
}
        Plot.setFontSize(16);
        Plot.setColor("Black"); 
        Plot.addText("Roi "+roi+1, 0.92, 0.09);
        Plot.setFontSize(12);
Plot.show();

} 

if (n>1){
//join plots
join=" title=["+fn+" - Intensiy Plots] ";

for (pl=1;pl<=n;pl++){
    join=join + " image"+pl+"=[Roi "+pl+"]";
}	

run("Concatenate...", join);

}
IJ.renameResults("Results",fn+" - Intensity Data");

// select colour
function lookup(){
getLut(reds, greens, blues);
Array.getStatistics(reds, min, max, mean, stdDev);
re=max;
RED=toHex(re);
if (re<17){
RED=RED+"0";	
}
Array.getStatistics(greens, min, max, mean, stdDev);
gr=max;
GREEN=toHex(gr);
if (gr<17){
GREEN=GREEN+"0";	
}
Array.getStatistics(blues, min, max, mean, stdDev);
bl=max;
BLUE=toHex(bl);
if (bl<17){
BLUE=BLUE+"0";	
}
col="#"+RED+GREEN+BLUE;
if (col=="#ffffff"){
col="Black";
}
return col;
}
}

}

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

macro "Multi Channel Intensity Line Profile for Time Series Action Tool - C0g0 L1h43 L43hd C00g L1d6e L6eh4 Cg00 L1649 L49h8 Cg00 L1649 L49h8 C000 T3308l T6308i T9308n Tf308e T3g08t T6g08i T8g08m Tgg08e L000h L0hhh"
{
//plots an intensity line profile of a multi channel image time series
//this version has auto LUT and plot size

run("Clear Results");

if (bitDepth()==24){
run("Make Composite");
}

setTool("line");

getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
fn=getTitle();
Chans=newArray(ImageChannels);
getVoxelSize(px, py, pz, units);
bit=bitDepth();
yscalelim=pow(2, bit)-1;
Stack.getUnits(X, Y, Z, Time, Value);
Frame_Interval=newArray(ImageFrames);
FrIn=Stack.getFrameInterval();
for (fi=1;fi<ImageFrames;fi++){
Frame_Interval[fi]=fi * FrIn;
} 

if (ImageSlices>1){
	exit("This macro does not work on a Z Stack image");
}

getVoxelSize(px, py, pz, units);
bit=bitDepth();
yscalelim=pow(2, bit)-1;


//menu
Dialog.create("Plot size");
  Dialog.addMessage("Select Plot options: \n - if the colours appear wrong, you may need to re-set the LUT's\n - use the Change channel LUT's macro");
  range = newArray(" Set own limits ", " Full intensity range ", " Limit to upper signal "," Limit to signal range ");
  Dialog.addRadioButtonGroup("Select intensity range (y-axis)", range, 1, 4, " Limit to signal range ");
  Dialog.addNumber("Low intensity value ", 0, 0, 6," " );
  Dialog.addNumber("High intensity value ", yscalelim, 0, 6," " );
  Dialog.addMessage("Enter dimensions of plot window");
  Dialog.addNumber("X dimension ", 650, 0, 4," pixels" );
  Dialog.addNumber("Y dimension ", 350, 0, 4," pixels" );
  Dialog.addMessage("Set line width");
  Dialog.addNumber("Line width ", 1, 0, 4," pixels" ); 
Dialog.show;

rangelimits = Dialog.getRadioButton();
lowy = Dialog.getNumber(); 
highy = Dialog.getNumber(); 
plotsizex = Dialog.getNumber(); 
plotsizey = Dialog.getNumber();
plotlinewidth = Dialog.getNumber();  


setBatchMode(true);

//draw line and get data
title = "Draw Line Profile";
msg = "Draw line \n \n then select OK to continue";
waitForUser(title, msg);


exist=selectionType();
if (exist==-1){
	exit("No selection - re-run macro");
}


//get y range
highlevel=0;
lowlevel=yscalelim;

for (Im=1;Im<=ImageFrames;Im++){
Stack.setFrame(Im);
for (ch=1;ch<=ImageChannels;ch++){
		Stack.setChannel(ch);	
	Channel=getProfile();
	Array.getStatistics(Channel, lowtemp, hightemp, mean, stdDev);
if (hightemp>highlevel){
	highlevel=hightemp;
}
if (lowtemp<lowlevel){
	lowlevel=lowtemp;
}
}
}


extend=(highlevel-lowlevel)*0.025;
highlevel=highlevel + extend;
lowlevel=lowlevel - extend;

xscalelen=lengthOf(Channel);


//get x range
Distance=newArray(xscalelen);
for (g=0;g<xscalelen;g++){
	Distance[g]=g*px;
	setResult("Distance (" + units +")", g, Distance[g]);
}


//y range selection
if (rangelimits==" Full intensity range "){
	ymax=yscalelim;
	ymin=0;
}
if (rangelimits==" Set own limits "){
	ymax=highy;
	ymin=lowy;
}
if (rangelimits==" Limit to upper signal "){
	ymax=highlevel;
	ymin=0;
}
if (rangelimits==" Limit to signal range "){
	ymin=lowlevel;
	ymax=highlevel;
}


//main plot and results
for (fr=1;fr<=ImageFrames;fr++){
//    selectImage(fn);
//	Stack.setFrame(fr); 
//	Channel=getProfile();            
        Plot.create("Intensity Plot", "Distance (" + units + ")", "Intensity");
        Plot.setLimits(0, xscalelen*px, ymin, ymax);
        Plot.setFrameSize(plotsizex, plotsizey);
        Plot.setLineWidth(plotlinewidth);


for (ch=1;ch<=ImageChannels;ch++){	
	selectImage(fn);
	Stack.setFrame(fr); 
	Stack.setChannel(ch);	
	Channel=getProfile();
	col=lookupColour();
	
	name="Chan: "+ch+" time pt="+ fr+ " (" +Frame_Interval[fr-1]+" "+Time+")";
for (row=0; row<lengthOf(Channel); row++){
setResult(name, row, Channel[row]);
}
		Plot.setColor(col);     
        Plot.add("line",Distance, Channel);
        Plot.setFontSize(12);
        Plot.setColor("Black"); 
        Plot.addText("frame (" + fr + ") T=" + Frame_Interval[fr-1] +" "+ Time , 0.75, 0.07);	
}
   

Plot.show();
rename("Plot of " + fn + " T=" + fr);
}



//join images
if (ImageFrames>1){
join=" title=["+fn+" - Series Time Plots] ";
n=1;
for (Im=1;Im<=ImageFrames;Im++){
	join=join + " image"+n+"=[Plot of " + fn + " T=" + Im +"]";
	n=n+1;
}

run("Concatenate...", join);

plot=1;
for (Im=1;Im<=ImageFrames;Im++){
	Stack.setSlice(plot);
    setMetadata("Label", " Time Point "+Im);
    plot=plot+1;
}


Stack.setSlice(1);
}
setBatchMode(false);

IJ.renameResults("Results",fn+" - Intensity Data");


//lookup colour
function lookupColour(){
getLut(reds, greens, blues);
Array.getStatistics(reds, min, max, mean, stdDev);
re=max;
RED=toHex(re);
if (re<17){
RED=RED+"0";	
}
Array.getStatistics(greens, min, max, mean, stdDev);
gr=max;
GREEN=toHex(gr);
if (gr<17){
GREEN=GREEN+"0";	
}
Array.getStatistics(blues, min, max, mean, stdDev);
bl=max;
BLUE=toHex(bl);
if (bl<17){
BLUE=BLUE+"0";	
}
col="#"+RED+GREEN+BLUE;
if (col=="#ffffff"){
col="Black";
}
return col;
}
}



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



macro "Max, Mean Min Intensity Time Plots (one channel) Action Tool - C0g0 L1h43 L43hd C0aa L1d6e L6eh4 Ca0a L1649 L49h8 C000 T3508m Ta508a Tf508x T3g08m Tcg08i Tfg08n L000h L0hhh"
{

run("Clear Results");

// intensity plot over time for upto 3 channels
//get file info

fn=getTitle();

getDimensions(width, height, channels, slices, frames);


if (frames==1 && slices==1){
	exit("This is not a time series");
}
if (frames==1 && slices!=1){
con=getBoolean("Image has only 1 frame, but " + slices + " slicess, do you want to convert slices to frames");
if (con==1){
run("Stack to Hyperstack...", "order=xyczt(default) channels=1 slices=" + frames + " frames=" + slices + " display=Color");	

getDimensions(width, height, channels, slices, frames);

Stack.setTUnit("frame");
}
}


setTool("oval");

//get bit depth
bit=bitDepth();
yscalelim=pow(2, bit)-1;

// create array
ChannelMean=newArray(frames);
ChannelMax=newArray(frames);
ChannelMin=newArray(frames);


//get plot details
Dialog.create("Plot size");
  Dialog.addMessage("Select Plot options: \n ");
  range = newArray(" Set own limits ", " Full intensity range ", " Limit to upper signal "," Limit to signal range ");
  Dialog.addRadioButtonGroup("Select intensity range (y-axis)", range, 1, 4, " Limit to signal range ");
  Dialog.addNumber("Low intensity value ", 0, 0, 6," " );
  Dialog.addNumber("High intensity value ", yscalelim, 0, 6," " );
  Dialog.addMessage("Enter dimensions of plot window");
  Dialog.addNumber("X dimension ", 650, 0, 4," pixels" );
  Dialog.addNumber("Y dimension ", 350, 0, 4," pixels" );
  Dialog.addMessage("Set line width");
  Dialog.addNumber("Line width ", 1, 0, 4," pixels" );  
Dialog.show;

rangelimits = Dialog.getRadioButton();
lowy = Dialog.getNumber(); 
highy = Dialog.getNumber(); 
plotsizex = Dialog.getNumber(); 
plotsizey = Dialog.getNumber();
plotlinewidth = Dialog.getNumber();  
ymin=0;


//draw roi and measure
title = "Draw Profile";
msg = "Draw Roi\n \n then select OK to continue";
waitForUser(title, msg);
roiManager("Reset");
roiManager("Add");
roiManager("Multi Measure");

for (i=0;i<frames;i++){	
  ChannelMean[i]=getResult("Mean1", i);
  ChannelMax[i]=getResult("Max1", i);
  ChannelMin[i]=getResult("Min1", i);
  
} 

selectWindow("Results");
run("Close");



//get y range
Array.getStatistics(ChannelMax, min, highlevel, mean, stdDev);

Array.getStatistics(ChannelMin, lowlevel, max, mean, stdDev);


extend=(highlevel-lowlevel)*0.025;
highlevel=highlevel + extend;
lowlevel=lowlevel - extend;


//get x range
Frame_Interval=newArray(frames);
Fr=Stack.getFrameInterval();
if (Fr==0){
	Fr=1;
}
Stack.getUnits(X, Y, Z, Time, Value);
for (fi=1;fi<frames;fi++){
Frame_Interval[fi]=fi * Fr;
} 
Array.getStatistics(Frame_Interval, min, xscalelen, mean, stdDev);

for (t=0;t<frames;t++){
      setResult("Frame Interval (" + Time + ")", t, Frame_Interval[t]);
}


//y range selection
if (rangelimits==" Full intensity range "){
	ymax=yscalelim;
	ymin=0;
}
if (rangelimits==" Set own limits "){
	ymax=highy;
	ymin=lowy;
}
if (rangelimits==" Limit to upper signal "){
	ymax=highlevel;
	ymin=0;
}
if (rangelimits==" Limit to signal range "){
	ymin=lowlevel;
	ymax=highlevel;
}


//main plot and results
Channel=newArray(frames);

        Plot.create(fn+" - Time Intensity Plot", "Time (" + Time + ")", "Intensity");
        Plot.setLimits(0, xscalelen, ymin, ymax);
        Plot.setFrameSize(plotsizex, plotsizey);
        Plot.setLineWidth(plotlinewidth);


for (j=0;j<frames;j++){	
      Mean="Mean Intensity";
	  CMax="Max Intensity";
      CMin="Min Intensity";
      setResult(Mean, j, ChannelMean[j]);
      setResult(CMax, j, ChannelMax[j]);
      setResult(CMin, j, ChannelMin[j]);
      
}
		Plot.setColor("Red");     
        Plot.add("line",Frame_Interval, ChannelMean);
        Plot.addText("Mean ", 0.1, 0);
 		Plot.setColor("Green");     
        Plot.add("line",Frame_Interval, ChannelMax);       
        Plot.addText("Max ", 0.2, 0);
		Plot.setColor("Blue");     
        Plot.add("line",Frame_Interval, ChannelMin);   
        Plot.addText("Min ", 0.3, 0);
Plot.show();

IJ.renameResults("Results",fn+" - Intensity Data");
}



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

macro "Measure Nuclear and Cytoplasmic Intensities Action Tool -  C0g0 H3373a1f4g6eeaf4h3e3c2b4800  C000 G3373a1f4g6eeaf4h3e3c2b4800  Cg00 V6675"
{
fn=getTitle();
//get bit depth and channel info

getDimensions(width, height, channels, slices, frames);

if (bitDepth()==24){
	run("Make Composite");
	getDimensions(width, height, channels, slices, frames);
}


ch=newArray(channels);
chAnalyse=newArray(channels);
bit=bitDepth();


//get channel options
Dialog.create("Select Fluorophes")
Dye = newArray("none", "Dapi", "488", "546", "594", "647" );
analyse = newArray("Yes", "No");
for (i=1; i<=channels; i++) {
Dialog.addMessage("Select fluorophes for channel " + i);
Dialog.addChoice("Channel " + i, Dye, "none");
Dialog.addString("Antibody name (optional): ", "");
Dialog.addRadioButtonGroup("Analyse " + "Channel " + i + " ?" , analyse, 1, 1, "No");
  Dialog.addMessage("");
}
Dialog.addRadioButtonGroup("Close all images when finished ?"  , analyse, 1, 1, "No");
Dialog.show(); 




for (j=0; j<channels; j++){
ch[j] = Dialog.getChoice();
ant=Dialog.getString();
chAnalyse[j]= Dialog.getRadioButton();

if (ch[j]=="Dapi" && chAnalyse[j]=="Yes"){
	exit("This macro won't analyse the Dapi channel"); 
}
if (ant!=""){
    	ch[j]=ant;
}	
if (ch[j]=="Dapi"){
	Dchan="C"+j+1;
}

}

Clse=Dialog.getRadioButton();


//start routine
rename("temp");
run("Split Channels");

   
//creat dapi masks
selectWindow(Dchan + "-temp");
run("Grays");
run("Threshold...");
title = "Get info";
msg = "set Dapi threshold to define nucleii\n then select OK to continue";
waitForUser(title, msg);
run("Convert to Mask");

if (bit!=8){	
run("16-bit");
imageCalculator("Multiply", Dchan + "-temp", Dchan + "-temp");
}

selectWindow(Dchan + "-temp");
run("Duplicate...", " ");
rename(Dchan + "-invert");
run("Invert");
  
//start analysing channels
for (an=0;an<channels;an++){

if (chAnalyse[an]=="Yes"){
	Ichan="C"+an+1;
if (ch[an]=="none"){
	ch[an]=Ichan;
}

imageCalculator("Subtract create", Ichan + "-temp" ,Dchan + "-temp");
rename("Average Cytoplasmic Intensity of " + ch[an] + " - " + fn);


//nuclear measures
imageCalculator("Subtract create", Ichan + "-temp" ,Dchan + "-invert");
rename("Average Nuclear Intensity of " + ch[an] + " - " + fn);
run("Grays");
run("Threshold...");
title = "Get info";
msg = "set threshold for nuclear component of " + ch[an] + "\n then select OK to continue";
waitForUser(title, msg);
run("Analyze Particles...", " show=Nothing summarize");

//cytoplasmic measures  
selectWindow("Average Cytoplasmic Intensity of " + ch[an] + " - " + fn);
run("Grays");
run("Threshold...");
title = "Get info";
msg = "set threshold for cytoplasmic component  of " + ch[an] + "\n then select OK to continue";
waitForUser(title, msg);
run("Analyze Particles...", "  show=Nothing summarize");

}
}

IJ.renameResults("Summary",fn+" - Intensity Data");

//clean up
selectWindow(Dchan + "-invert");
close();
for (cl=0;cl<channels;cl++){
selectWindow("C"+ (cl+1) + "-temp");
close();
}
if (Clse=="yes"){
	run("Close All");
}
}

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

macro "Lambda Plot multi ROI's (max 15)  Action Tool - C00g L51dd L865d C000 L000h L0hhh"
{
//initialise

wavelength=newArray(350, 355, 360, 365, 370, 375, 380, 385, 390, 395, 400, 405, 410, 415, 420, 425, 430, 435, 440, 445, 
450, 455, 460, 465, 470, 475, 480, 485, 490, 495, 500, 505, 510, 515, 520, 525, 530, 535, 540, 545, 
550, 555, 560, 565, 570, 575, 580, 585, 590, 595, 600, 605, 610, 615, 620, 625, 630, 635, 640, 645, 
650, 655, 660, 665, 670, 675, 680, 685, 690, 695, 700, 705, 710, 715, 720, 725, 730, 735, 740, 745, 750); 
SpectrumRed=newArray(0, 0, 0, 0, 0, 0, 1, 42, 71, 92, 105, 113, 116, 114, 107, 86, 62, 37, 5, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 29, 52, 73, 92, 110, 128, 145, 
162, 178, 194, 209, 224, 239, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 243, 231, 217, 204, 190, 176, 162, 147, 133, 120); 
SpectrumGreen=newArray(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 37, 
68, 96, 120, 144, 168, 190, 212, 233, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 
255, 255, 255, 255, 255, 255, 255, 241, 224, 208, 191, 174, 157, 139, 120, 101, 81, 59, 35, 14, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); 
SpectrumBlue=newArray(0, 0, 0, 0, 0, 0, 1, 45, 81, 114, 144, 172, 200, 227, 253, 255, 255, 255, 255, 255, 
255, 255, 255, 255, 255, 255, 255, 255, 255, 207, 152, 89, 10, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); 


run("Clear Results");
setTool("oval");
n=roiManager("Count");
type="Lambda Emission";

//get file info
fn=getTitle();
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);

//check data
if (ImageChannels==1 && ImageSlices==1&& ImageFrames==1){
	exit("This is not a lambda series");
}

steps=1;
if (ImageFrames==1 && ImageSlices==1){
	steps=ImageChannels;
}
if (ImageChannels==1 && ImageFrames==1){
	steps=ImageSlices;
	run("Stack to Hyperstack...", "order=xyczt(default) channels="+steps+" slices=1 frames=1 display=Grayscale");
}
if (ImageChannels==1 && ImageSlices==1){
	steps=ImageFrames;
	run("Stack to Hyperstack...", "order=xyczt(default) channels="+steps+" slices=1 frames=1 display=Grayscale");
}
if (ImageChannels*ImageSlices*ImageFrames>steps){
	exit("This is not a lambda series");
}
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);

//get bit depth
bit=bitDepth();
yscalelim=pow(2, bit)-1;


//get plot details
Dialog.create("Plot size");
	opt = newArray("Yes","No");
	if (n>0){
		Dialog.addChoice("Do you want to keep existing ROI's", opt, "Yes")
	}
	Dialog.addMessage("Main Options");
  Dialog.setInsets(0, 250, 0);
  Dialog.addCheckbox("Create a Gallery View", false);
    Dialog.setInsets(0, 250, 0); 
  Dialog.addCheckbox("Add Wavelength Colour LUT to images", false);
      Dialog.setInsets(0, 250, 0);  
  Dialog.addCheckbox("Create a Maximum Projection", false); 
      Dialog.setInsets(0, 250, 0); 
  Dialog.addCheckbox("Create a Plot and Data", true); 
    Dialog.addMessage("Plot options");  
  range = newArray(" Set own limits ", " Full intensity range ", " Limit to upper signal "," Limit to signal range ");
  Dialog.addRadioButtonGroup("Select intensity range (y-axis)", range, 1, 4, " Limit to signal range ");
  Dialog.addNumber("Low intensity value ", 0, 0, 6," " );
  Dialog.addNumber("High intensity value ", yscalelim, 0, 6," " );
  Dialog.addMessage("Enter dimensions of plot window");
  Dialog.addNumber("X dimension ", 650, 0, 4," pixels" );
  Dialog.addNumber("Y dimension ", 350, 0, 4," pixels" );
  Dialog.addMessage("Set line width");
  Dialog.addNumber("Line width ", 2, 0, 4," pixels" ); 

Dialog.show;

if (n>0){
answer=Dialog.getChoice();
if (answer=="No"){
roiManager("Reset");	
}
}

//get responses
CreateGall=Dialog.getCheckbox(); 
wavelengthLUT=Dialog.getCheckbox(); 
CreateProj=Dialog.getCheckbox();
CreatePlot=Dialog.getCheckbox();
rangelimits = Dialog.getRadioButton();
lowy = Dialog.getNumber(); 
highy = Dialog.getNumber(); 
plotsizex = Dialog.getNumber(); 
plotsizey = Dialog.getNumber();
plotlinewidth = Dialog.getNumber(); 

ymin=0;

//draw rois
//roiManager("Reset");

waitForUser("Add ROI's", "Add ROI's to ROI Manager (t) \n \n or do nothing to select whole image  \n \n then select OK to continue");


// create arrays
n=roiManager("count");
if (n<1){
run("Specify...", "width=ImageWidth height=ImageHeight x=0 y=0");
roiManager("add");
n=roiManager("count");
}


RoiData=newArray(steps*n);
RoiPlot=newArray(steps);
colours=newArray("red","green","blue","magenta","cyan","#FFFF22","#008833","#FF5500","#000000", "#660066", "#9966FF","#000033", "#330000", "#339966", "#33CC99");


//reame and colour and roi's
for (i=0;i<n;i++){
roiManager("select", i);
name="ROI " + i+1;
roiManager("Rename", name);
roiManager("Set Color", colours[i]);
roiManager("Remove Channel Info");
}
roiManager("Deselect");
roiManager("Multi Measure");


for (roi=0;roi<n;roi++){
for (j=0;j<steps;j++){	
  RoiData[j+(steps*roi)]=getResult("Mean(ROI "+roi+1+")", j);
} 
}

selectWindow("Results");
run("Close");

//get y range
Array.getStatistics(RoiData, lowlevel, highlevel, mean, stdDev);


extend=(highlevel-lowlevel)*0.025;
highlevel=highlevel + extend;
lowlevel=lowlevel - extend;

//****************************************************************
//get x range
meta=getMetadata("Info");
Frame_Interval=newArray(steps);

// for Zeiss
zeiss=indexOf(meta, "AIMApplication");
if (zeiss>1){
for (l=1;l<=steps;l++){
txt=l;
if (l<10){
txt="0"+l;
}
li=indexOf(meta, "EmissionWavelength #"+txt);
Frame_Interval[l-1]=parseInt(substring(meta, li+25, li+28));
}
bw=(Frame_Interval[steps-1]-Frame_Interval[0])/steps;
step=bw;
}


//for Leica Lambda
leica1=indexOf(meta, "HardwareSetting|ScannerSettingRecord|SystemType");
if (leica1>1){
Dialog.create("Title");
Dialog.addRadioButtonGroup("Scan Type", newArray("Emission","Excitation"), 1, 2, "Emission");
Dialog.show();

tp=Dialog.getRadioButton();

if (tp=="Emission"){
   stl=indexOf(meta, "HardwareSetting|ScannerSettingRecord|dblLambdaBeginLeft_0 #1 = ");
   str=indexOf(meta, "HardwareSetting|ScannerSettingRecord|dblLambdaBeginRight_0 #1 = ");
   edl=indexOf(meta, "HardwareSetting|ScannerSettingRecord|dblLambdaEndLeft_0 #1 = ");
   edr=indexOf(meta, "HardwareSetting|ScannerSettingRecord|dblLambdaEndRight_0 #1 = ");
   startl=parseInt(substring(meta, stl+63, stl+66));
   startr=parseInt(substring(meta, str+64, str+67));
   endl=parseInt(substring(meta, edl+61, edl+64));
   endr=parseInt(substring(meta, edr+62, edr+65));
   midstart=startl+((startl-startr)/2);
   midend=endl+((endl-endr)/2);
   bw=startr-startl;
   step=((midend-midstart)/steps);
for (fi=0;fi<steps;fi++){
Frame_Interval[fi]=round(step + midstart+(fi * step));
}
}else 

//for Leica Delta
if (tp=="Excitation"){
   st=indexOf(meta, "HardwareSetting|ScannerSettingRecord|nLambdaExcitationBegin #1");
   ed=indexOf(meta, "HardwareSetting|ScannerSettingRecord|nLambdaExcitationEnd #1");
   start=parseInt(substring(meta, st+65, st+68))/2;
   end=parseInt(substring(meta, ed+63, ed+66))/2;
   step=(start-end)/(ImageChannels-1)/2;
  
for (fi=0;fi<steps;fi++){
Frame_Interval[fi]=start + step*fi;
}
type="Lambda Excitation";
}
}


leica2=indexOf(meta, "LambdaDefinition");
if (leica2>1){
   stl=indexOf(meta, "LambdaDetectionBegin = ");
   str=indexOf(meta, "LambdaDetectionFirstEnd = ");
   edl=indexOf(meta, "LambdaDetectionLastBegin = ");
   edr=indexOf(meta, "LambdaDetectionEnd = ");
   startl=parseInt(substring(meta, stl+23, stl+26));
   startr=parseInt(substring(meta, str+26, str+29));
   endl=parseInt(substring(meta, edl+27, edl+30));
   endr=parseInt(substring(meta, edr+21, edr+24));
   midstart=startl+((startl-startr)/2);
   midend=endl+((endl-endr)/2);
   bw=startr-startl;
   step=((midend-midstart)/steps);
for (fi=0;fi<steps;fi++){
Frame_Interval[fi]=round(step + midstart+(fi * step));
}
}



//own settings
if (zeiss<1 && leica1<1 && leica2<1) {
Dialog.create("User imput");
  Dialog.addMessage("Enter Lambda information");
  Dialog.addNumber("Start wavelength ", 400, 0, 6," nm" );
  Dialog.addNumber("End wavelength ", 750, 0, 6," nm" );
  Dialog.addNumber("Bandwidth ", 10, 0, 4," nm" );
  Dialog.addNumber("Step-size ", 10, 0, 4," nm" );
Dialog.show;

startl = Dialog.getNumber(); 
endr = Dialog.getNumber(); 
bw = Dialog.getNumber(); 
step = Dialog.getNumber();

for (fi=0;fi<steps;fi++){
Frame_Interval[fi]=(bw/2) + startl+(fi * step);
} 	
}


//////////create plot and data
if (CreatePlot==true){
for (t=0;t<steps;t++){
      setResult("Wavelength (nm)", t, Frame_Interval[t]);
}

//y range selection
if (rangelimits==" Full intensity range "){
	ymax=yscalelim;
	ymin=0;
}
if (rangelimits==" Set own limits "){
	ymax=highy;
	ymin=lowy;
}
if (rangelimits==" Limit to upper signal "){
	ymax=highlevel;
	ymin=0;
}
if (rangelimits==" Limit to signal range "){
	ymin=lowlevel;
	ymax=highlevel;
}

//main plot and results
        Plot.create(fn+" - "+type+" Scan Intensity Plot", "Wavelength (nm) ", "Intensity");
        Plot.setLimits(Frame_Interval[0], Frame_Interval[steps-1], ymin, ymax);
        Plot.setFrameSize(plotsizex, plotsizey);
        Plot.setLineWidth(plotlinewidth);

for (m=0;m<n;m++){
for (p=0;p<steps;p++){
	  RoiPlot[p]=RoiData[p+(steps*m)];	
      name="Roi " + m+1;
      setResult(name, p, RoiPlot[p]);
}
		Plot.setColor(colours[m]);     
        Plot.add("line",Frame_Interval, RoiPlot);
        Plot.addText("ROI " + m+1, m*0.1, 0);
}

Plot.show();
IJ.renameResults("Results",fn+" - "+type+" Intensity Data");
}
////////////end plot

selectWindow(fn);
roiManager("Show All with labels");
//selectWindow(fn+" - Lambda Scan Intensity Plot");


///////////create colour image
if (wavelengthLUT==true){
//Colour lambda stack
selectWindow(fn);
run("Stack to Hyperstack...", "order=xyczt(default) channels=ImageChannels slices=ImageSlices frames=ImageFrames display=Color");
for (im=0;im<steps;im++){
	Stack.setChannel(im+1);
wl=round(Frame_Interval[im]);
if (wl<350){
	wl=350;
}
if (wl>750){
	wl=750;
}

ref=(wl-350)/5;
redmax=SpectrumRed[ref];
greenmax=SpectrumGreen[ref];
bluemax=SpectrumBlue[ref];

red=newArray(256);
green=newArray(256);
blue=newArray(256);

for (i=0;i<256;i++){
	red[i]=floor(i*(redmax+1)/256);
	green[i]=floor(i*(greenmax+1)/256);
	blue[i]=floor(i*(bluemax+1)/256);
}
setLut(red, green, blue);
}
}
///////////end colour


//create projection
if (CreateProj==true){
selectWindow(fn);
run("RGB Color");
rename("temprgb");
run("Z Project...", "projection=[Max Intensity]");
rename(fn+" - "+type+" Projection");
roiManager("Show All");
selectWindow("temprgb");
close();
}
/////////end projection


///////////craete gallery
if (CreateGall==true){
setColor("white");


//get format
rows=1;
if ((ImageChannels)/5>1){
rows=floor((ImageChannels)/5)+1;
}
cols=floor((ImageChannels)/rows);
if (cols*rows<ImageChannels){
cols=cols+1;
}

//get output info
Dialog.create("Select Output Options");
  Dialog.addMessage("There are "+steps+" Images");
  Dialog.addNumber("Number of Columns",cols );
  Dialog.addNumber("Number of Rows", rows);
  Dialog.addNumber("Border Width", 3);
  Dialog.addNumber("Label size", floor(25*ImageWidth/250));
  Dialog.addNumber("Scale factor", 0.5);
Dialog.show;

cols=Dialog.getNumber();
rows=Dialog.getNumber();
Bord=Dialog.getNumber();
fnt=Dialog.getNumber();
scaleF=Dialog.getNumber();
setFont("Arial", fnt,"antiliased");

selectWindow(fn);
roiManager("Show None");
run("Select None");
run("Duplicate...", "title=gall_temp duplicate");
run("RGB Color");
rename("gall");
run("Properties...", "channels=1 slices=ImageChannels frames=1");

//getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
	selectWindow("gall");
for (image=1;image<=ImageChannels;image++){
	Stack.setSlice(image);
	setMetadata("Label", Frame_Interval[image-1]+" nm");
	drawString(Frame_Interval[image-1]+" nm", 15, 15+fnt);
}

run("Make Montage...", "columns=cols rows=rows scale=scaleF border=Bord");
rename(fn+" - "+type+" Gallery");
selectWindow("gall");
close();
if (isOpen("gall_temp")==true){
	selectWindow("gall_temp");
	close();
}
}
///////////end gallery

}



///////////////////////////////////////////12

macro "Maxima and Minima of line profile Action Tool - C000 L1h43 L436d L6d81 L81aa Laac3 Lc3ef Lefg6 L000h L0hhh Cg00 Tf509L"
{
//initialise
fn=getTitle();
run("Clear Results");
setTool("line");
getDimensions(width, height, channels, slices, frames);
getVoxelSize(px, py, pz, units);

//draw line
title = "Draw Profile";
msg = "Draw line \n \n then select OK to continue";
waitForUser(title, msg);

exist=selectionType();
if (exist==-1){
	exit("No selection - re-run macro");
}

//get profile data 	
profile=getProfile;

xcoord=newArray(profile.length);

for (i=0;i<profile.length;i++){
xcoord[i]=i*px;
}

Array.getStatistics(profile, min, max, mean, stdDev);
Tolerance=(max-min)/5;
Tolerance=getNumber("input Tolerance (range = "+min+"-"+max+").  20% of this value is: ",Tolerance);

// find maima and minima
MaxDist= Array.findMaxima(profile, Tolerance);
MinDist= Array.findMinima(profile, Tolerance);

//sort on distance
Array.sort(MaxDist);
Array.sort(MinDist);

//get intensity data and print results
MaxIntensity=newArray(MaxDist.length);
MinIntensity=newArray(MinDist.length);
MaxDiff=newArray(MaxDist.length);
MinDiff=newArray(MinDist.length);
	
for(minpoint=0;minpoint<MinDist.length;minpoint++){
	MinIntensity[minpoint]=profile[MinDist[minpoint]]; 
	MinDist[minpoint]=MinDist[minpoint]*px;
	setResult("Minima Distance (" + units +")", minpoint, MinDist[minpoint]);
	setResult("Minima Intensity", minpoint, MinIntensity[minpoint]);
if (minpoint>0 && minpoint<MinDist.length){
	MinDiff[minpoint-1]=MinDist[minpoint]-MinDist[minpoint-1];
	setResult("Minima Difference (" + units +")", minpoint, MinDiff[minpoint-1]);
}	
}

for(maxpoint=0;maxpoint<MaxDist.length;maxpoint++){
	MaxIntensity[maxpoint]=profile[MaxDist[maxpoint]];
	MaxDist[maxpoint]=MaxDist[maxpoint]*px;
	setResult("Maxima Distance (" + units +")", maxpoint, MaxDist[maxpoint]);
	setResult("Maxima Intensity", maxpoint, MaxIntensity[maxpoint]);
if (maxpoint>0 && maxpoint<MaxDist.length){
	MaxDiff[maxpoint-1]=MaxDist[maxpoint]-MaxDist[maxpoint-1];
	setResult("Maxima Difference (" + units +")", maxpoint, MaxDiff[maxpoint-1]);
}
}


//crete plot
Plot.create(fn+" - Plot of Maxima/Minima", "Distance ("+units+")", "Intensity",xcoord, profile);
	Plot.setColor("Red");
	Plot.add("circles", MinDist, MinIntensity);
		Plot.setColor("Green");
	Plot.add("circles", MaxDist, MaxIntensity);
		Plot.setColor("Black");
Plot.show;


IJ.renameResults("Results",fn+" - Maxima & Minima Data");
//Array.show(MinDist,MinIntensity,MaxDist,MaxIntensity);
}



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


macro "Maxima and Minima of time plot Action Tool - C000 L1h43 L436d L6d81 L81aa Laac3 Lc3ef Lefg6 L000h L0hhh Cg00 Tf509T"
{

win=getList("image.titles");
plwin="";
for (i=0;i<win.length;i++){
	selectWindow(win[i]);
if (getInfo("window.type")=="plot"){
plwin=win[i];
}
}

if (plwin==""){
	exit("You will need to create a time plot before running this macro\n using Time Series Analyser or Intenity Time plot macro");
}

	
run("Clear Results");

//get calibration
title = "Get info";
msg = "select original image to get calibration \n select ok when done";
waitForUser(title, msg);
fn=getTitle();
Stack.getUnits(X, Y, Z, Time, Value);
//tm=Stack.getFrameInterval();

//get plot data
title = "Get info";
msg = "select plot \n select ok when done";
waitForUser(title, msg);
//selectWindow(plwin);

Plot.getValues(xpoints, ypoints);
Array.getStatistics(ypoints, min, max, mean, stdDev);
Tolerance=(max-min)/5;
Tolerance=getNumber("input Tolerance (range = "+min+"-"+max+").  20% of this value is: ",Tolerance);

// find maima and minima
MaxTime=Array.findMaxima(ypoints, Tolerance);
MinTime=Array.findMinima(ypoints, Tolerance);

// sort on time
Array.sort(MaxTime);
Array.sort(MinTime);

//get intensity data and print results
MaxIntensity=newArray(MaxTime.length);
MinIntensity=newArray(MinTime.length);
MaxDiff=newArray(MaxTime.length);
MinDiff=newArray(MinTime.length);

for (minpoint=0;minpoint<MinTime.length;minpoint++){ 
	for (i=0;i<xpoints.length;i++){
	if (i==MinTime[minpoint]){
		MinIntensity[minpoint]=ypoints[i];
		MinTime[minpoint]=xpoints[i];
		setResult("Minima Time ("+Time+")", minpoint, MinTime[minpoint]);
		setResult("Minima Intensity", minpoint, MinIntensity[minpoint]);
	if (minpoint>0 && minpoint<MinTime.length){
		MinDiff[minpoint-1]=MinTime[minpoint]-MinTime[minpoint-1];
		setResult("Minima Difference (" +Time+")", minpoint, MinDiff[minpoint-1]);
}
		}
}
}
for (maxpoint=0;maxpoint<MaxTime.length;maxpoint++){
	for (i=0;i<xpoints.length;i++){ 	
	if (i==MaxTime[maxpoint]){
		MaxIntensity[maxpoint]=ypoints[i];
		MaxTime[maxpoint]=xpoints[i];
		setResult("Maxima Time ("+Time+")", maxpoint, MaxTime[maxpoint]);
		setResult("Maxima Intensity", maxpoint, MaxIntensity[maxpoint]);
	if (maxpoint>0 && maxpoint<MaxTime.length){
		MaxDiff[maxpoint-1]=MaxTime[maxpoint]-MaxTime[maxpoint-1];
		setResult("Maxima Difference (" +Time+")", maxpoint, MaxDiff[maxpoint-1]);
}
	}

}
}


//crete plot
Plot.create(fn+" - Plot of Maxima/Minima",  "Time ("+Time+")","Intensity", xpoints, ypoints);
	Plot.setColor("Red");
	Plot.add("circles", MinTime, MinIntensity);
		Plot.setColor("Green");
	Plot.add("circles", MaxTime, MaxIntensity);
		Plot.setColor("Black");
Plot.show();

IJ.renameResults("Results", fn+" - Maxima & Minima Data");
//Array.show(MaxTime,MaxIntensity,MinTime,MinIntensity);
}



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

macro " Select Channel Intensity Time Plots (display frame by frame) Action Tool - C0g0 L1h43 L43hd C00g L1d6e L6eh4 Cg00 L1649 L49h8 C000 T0408f T3408r T6408a T8408m Tg408e L000h L0hhh"
{

run("Clear Results");
setTool("oval");

// intensity plot over time mulit channels
//get file info
fn=getTitle();
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);

//check for time series
if (ImageFrames==1 && ImageSlices==1){
	exit("This is not a time series");
}
if (ImageFrames==1 && ImageSlices!=1){
con=getBoolean("Image has only 1 frame, but " + ImageSlices + " slicess, do you want to convert slices to frames");
if (con==1){
run("Stack to Hyperstack...", "order=xyczt(default) channels=1 slices=" + ImageFrames + " frames=" + ImageSlices + " display=Color");	
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);

Stack.setTUnit("frame");
}
}
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
plotheight=floor(ImageHeight/5*4);
plotwidth=floor(plotheight/2*3);

run("Select None");
run("Duplicate...", "title=temp duplicate");

//get bit depth
bit=bitDepth();
yscalelim=pow(2, bit)-1;

//select channels, colour 
Chans=newArray(ImageChannels);

Dialog.create("Title")
  Dialog.addMessage("Analyse Channels");
  analyseChannel = newArray("Yes", "No");
  for (Channel=1; Channel<=ImageChannels; Channel++) {
  Ch="Channel " + Channel;
  Dialog.addRadioButtonGroup(Ch, analyseChannel, 1, 1, "Yes");
  }
Dialog.show(); 
chansYes=0;
for (Channel=1;Channel<=ImageChannels;Channel++){
Chans[Channel-1] = Dialog.getRadioButton();
    if (Chans[Channel-1]=="yes"){
	chansYes=chansYes+1;
}
}

if (chansYes==0){
	exit("no channel selected");
}
// create array
ChannelData=newArray(ImageFrames*ImageChannels);



//get plot details
Dialog.create("Output Options");
  Dialog.addMessage("Select Plot options: \n - if the colours appear wrong, you may need to re-set the LUT's\n - use the Change channel LUT's macro");
  range = newArray(" Set own limits ", " Full intensity range ", " Limit to upper signal "," Limit to signal range ");
  Dialog.addRadioButtonGroup("Select intensity range (y-axis)", range, 1, 4, " Limit to signal range ");
  Dialog.addNumber("Low intensity value ", 0, 0, 6," " );
  Dialog.addNumber("High intensity value ", yscalelim, 0, 6," " );
  Dialog.addMessage("Enter dimensions of plot window");
  Dialog.addNumber("X dimension ", plotwidth, 0, 4," pixels" );
  Dialog.addNumber("Y dimension ", plotheight, 0, 4," pixels" );
  Dialog.addMessage("Additional options");
  Dialog.setInsets(-6, 200, 20);
  Dialog.addCheckbox("Edit axis titles, tick marks and grids", false);
   Dialog.addNumber("Plot line width ", 2, 0, 4," pixels" );
  option = newArray("yes","No");
  Dialog.addChoice("Invert graph", option, "No");
  position = newArray("Below", "Right", "No"); 
  Dialog.addChoice("Attach graph to image", position, "No");

  for (i=1; i<=ImageChannels; i++) {
  Dialog.addMessage("Select fluorophes for channel " + i);
  Dialog.addString("Channel " + i + " name: ", "Channel " + i);
  }

Dialog.show;

rangelimits = Dialog.getRadioButton();
lowy = Dialog.getNumber(); 
highy = Dialog.getNumber(); 
plotsizex = Dialog.getNumber(); 
plotsizey = Dialog.getNumber();
change_plot=Dialog.getCheckbox();
plotlinewidth = Dialog.getNumber(); 
Inv= Dialog.getChoice();
Attach= Dialog.getChoice();
titletext=newArray(ImageChannels);
for (title=0; title<ImageChannels; title++){
titletext[title] = Dialog.getString();
} 
ymin=0;




//draw roi and measure

waitForUser("Draw ROI", "Draw Roi or do nothing for whole image\n \n then select OK to continue");

getSelectionBounds(selx, sely, selwidth, selheight);
if (selx==0){
	makeRectangle(0, 0, ImageWidth-1, ImageHeight-1);
}
roiManager("Reset");
roiManager("Add");
roiManager("Select",0);
roiManager("Remove Frame Info");
roiManager("Multi Measure");

for (Data=0;Data<ImageFrames*ImageChannels;Data++){
  ChannelData[Data]=getResult("Mean1", Data);
}

selectWindow("Results");
run("Close");


//get y range
highlevel=0;
lowlevel=yscalelim;
a=0;
for (ChannelLevel=0;ChannelLevel<ImageChannels;ChannelLevel++){
if (Chans[ChannelLevel]=="Yes"){

for (range=ChannelLevel;range<(ImageFrames*ImageChannels);range+=ImageChannels){
	temprange=ChannelData[range];

	if 	(temprange>highlevel){
		highlevel=temprange;
	}
	if 	(temprange<lowlevel){
		lowlevel=temprange;
	}
}
}
}

extend=(highlevel-lowlevel)*0.025;
highlevel=highlevel + extend;
lowlevel=lowlevel - extend;


//get x range
Frame_Interval=newArray(ImageFrames);
Fr=Stack.getFrameInterval();
if (Fr==0){
	Fr=1;
}
Stack.getUnits(X, Y, Z, Time, Value);
for (fi=1;fi<ImageFrames;fi++){
Frame_Interval[fi]=fi * Fr;
} 
Array.getStatistics(Frame_Interval, min, xscalelen, mean, stdDev);

for (t=0;t<ImageFrames;t++){
      setResult("Frame Interval (" + Time + ")", t, Frame_Interval[t]);
}


//y range selection
if (rangelimits==" Full intensity range "){
	ymax=yscalelim;
	ymin=0;
}
if (rangelimits==" Set own limits "){
	ymax=highy;
	ymin=lowy;
}
if (rangelimits==" Limit to upper signal "){
	ymax=highlevel;
	ymin=0;
}
if (rangelimits==" Limit to signal range "){
	ymin=lowlevel;
	ymax=highlevel;
}


X_title="Time";
Y_title="Intensity";


//plot options
if (change_plot==true){
Dialog.create("Plot Options");
Dialog.addMessage("Axis titles");
  Dialog.addString("X-axis title:",X_title);
  Dialog.addString("Y-axis title:",Y_title);
Dialog.addMessage("Grids and tick marks");
  format=newArray("grid X","grid Y","major ticks X", "major ticks Y", "minor ticks X", "minor ticks Y","numbers X", "numbers Y");
  defaults=newArray(true,true,true,true,true,true,true,true);
  Dialog.addCheckboxGroup(4,2,format,defaults);
  Dialog.addMessage("interval between numbers, major ticks and grid lines");
  Dialog.addNumber("interval in X", 0);
  Dialog.addNumber("interval in Y", 0);
Dialog.show(); 


X_title= Dialog.getString();
Y_title= Dialog.getString();
gX=Dialog.getCheckbox();
gY=Dialog.getCheckbox();
MatX=Dialog.getCheckbox();
MatY=Dialog.getCheckbox();
MitX=Dialog.getCheckbox();
MitY=Dialog.getCheckbox();
NumX=Dialog.getCheckbox();
NumY=Dialog.getCheckbox();
xint=Dialog.getNumber();
yint=Dialog.getNumber();

opts="1100"+toString(MitY)+toString(MitX)+"00"+toString(gY)+toString(gX)+toString(MatY)+toString(MatX)+toString(NumY)+toString(NumX);
//print(opts);


}





//main plot and results
setBatchMode(true);

frm=1;
for (plot=0;plot<ImageFrames;plot++){

Channel=newArray(ImageFrames);

        Plot.create("Time Intensity Plot - time point:"+plot, X_title+" (" + Time + ")",Y_title);
        if(change_plot==true){
        Plot.setFormatFlags(opts);
        Plot.setOptions("xinterval="+xint+" yinterval="+yint+"");
        }
        Plot.setLimits(0, xscalelen, ymin, ymax);
        Plot.setFrameSize(plotsizex, plotsizey);
        Plot.setLineWidth(plotlinewidth);

for (k=0;k<ImageChannels;k++){
	if (Chans[k]=="Yes"){
selectWindow("temp");
if (ImageChannels>1){
Stack.setChannel(k+1);
}

for (j=0;j<frm;j++){
	  Channel[j]=ChannelData[j*ImageChannels+(k)];	
      name= titletext[k];
      setResult(name, j, Channel[j]);
}

PartChannel=Array.trim(Channel, frm);
col=LookupLUT();

		Plot.setColor(col);		     
        Plot.add("line",Frame_Interval, PartChannel);
        Plot.addText(titletext[k], k*0.2, 0);              
}
}
        Plot.setColor("#000000");
        Plot.drawLine((frm-1)*Fr, ymax, (frm-1)*Fr, ymin);        
Plot.show();

frm=frm+1;
}


run("Images to Stack", "name=Time Intensity Plot title=[] use");
setBatchMode(false);

rename("plot");
getDimensions(plotwidth, plotheight, plotchannels, plotslices, plotframes);

borderbit="RGB black";
if (bitDepth()==8){
	borderbit="8-bit black";
}

//add space above plot
newImage("top", borderbit, plotwidth, 8, plotslices);
selectWindow("top");
run("Invert", "stack");

run("Combine...", "stack1=top stack2=plot combine");

if(Inv=="Yes"){
run("Invert", "stack");
}


rename("plot of " + fn);

//setBatchMode(false);


//scale and add to image
if (Attach=="Below"){
sc="x=- y=- z=1.0 width="+ImageWidth+" height="+ floor(2*ImageWidth/3) + " depth=slices interpolation=Bilinear average process create title=plot";
selectWindow("plot of " + fn);
run("Scale...",sc );
rename("plot2");
run("RGB Color");

selectWindow("temp");
run("RGB Color", "frames");

newImage("border", "RGB white", ImageWidth, 2, ImageFrames);
run("Combine...", "stack1=border stack2=plot2 combine");
rename("plot2");
run("Sharpen", "stack");
run("Combine...", "stack1=temp stack2=plot2 combine");
rename("Combined " + fn);
roiManager("Show All");
run("Flatten", "stack");
selectWindow("plot of "+fn);
close();
}

if (Attach=="Right"){
sc="x=- y=- z=1.0 width="+ floor(ImageHeight*1.3) + " height="+ImageHeight+" depth=ImageSlices interpolation=Bilinear average process create title=plot";
selectWindow("plot of " + fn);
run("Scale...",sc );
rename("plot2");
run("RGB Color");

selectWindow("temp");
run("RGB Color", "frames");

newImage("border", "RGB white", 2, ImageHeight, ImageFrames);
run("Combine...", "stack1=border stack2=plot2");
rename("plot2");
run("Sharpen", "stack");
run("Combine...", "stack1=temp stack2=plot2");
rename("Combined " + fn);
roiManager("Show All");
run("Flatten", "stack");
selectWindow("plot of "+fn);
close();
}

if (Attach=="No"){
	selectWindow("temp");
	close();
}

IJ.renameResults("Results",fn+" Intensity Measurements");



function LookupLUT(){
//get colour data
getLut(reds, greens, blues);
Array.getStatistics(reds, min, Rmax, mean, stdDev); 
Array.getStatistics(greens, min, Gmax, mean, stdDev); 
Array.getStatistics(blues, min, Bmax, mean, stdDev);
ChannelColour=newArray(Rmax,Gmax,Bmax);

//get hex of normal channel
NormalColour="#";
InverseColour="#";
for (c=0;c<3;c++){
Hx=toHex(ChannelColour[c]);
if (lengthOf(Hx)<2){
	Hx="0"+Hx;
}

if ((ChannelColour[c]+128)>255){
	InverseChannelColour=255-ChannelColour[c];
} else {InverseChannelColour=ChannelColour[c]+255;}

HI=toHex(InverseChannelColour);
if (lengthOf(HI)<2){
	HI="0"+HI;
}
NormalColour=NormalColour+Hx;
InverseColour=InverseColour+HI;	
}
if (Inv=="Yes"){
return InverseColour;
} else return NormalColour;
}

}





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

macro " Multi Roi (max 10) Intensity Time Plots (display frame by frame) Action Tool - C0g0 L1h43 L43hd C00g L1d6e L6eh4 Cg00 L1649 L49h8 C000 T0408f T3408r T6408a T8408m Tg408e T3g08R T9g08O Tgg08I L000h L0hhh"
{

//initialize
run("Clear Results");
setTool("oval");
n=roiManager("Count");


//get file info
fn=getTitle();
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);

//check for time series and multi channel
if (ImageChannels>1){
	exit("This macro does not work on multichannel Images"); 
}

if (ImageFrames==1 && ImageSlices==1){
	exit("This is not a time series");
}
if (ImageFrames==1 && ImageSlices!=1){
con=getBoolean("Image has only 1 frame, but " + ImageSlices + " slicess, do you want to convert slices to frames");
if (con==1){
run("Stack to Hyperstack...", "order=xyczt(default) channels=1 slices=" + ImageFrames + " frames=" + ImageSlices + " display=Color");	
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);

Stack.setTUnit("frame");
}
}
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);

plotheight=floor(ImageHeight/5*4);
plotwidth=floor(plotheight/2*3);


//get bit depth
bit=bitDepth();
yscalelim=pow(2, bit)-1;
ymin=0;


X_title="Time";
Y_title="Intensity";

//get plot details
Dialog.create("Plot size");
  Dialog.addMessage("Select Plot options");
	opt = newArray("Yes","No");
	if (n>0){
		Dialog.addChoice("Do you want to keep existing ROI's", opt, "Yes")
	}
  range = newArray(" Set own limits ", " Full intensity range ", " Limit to upper signal "," Limit to signal range ");
  Dialog.addRadioButtonGroup("Select intensity range (y-axis)", range, 1, 4, " Limit to signal range ");
  Dialog.addNumber("Low intensity value ", 0, 0, 6," " );
  Dialog.addNumber("High intensity value ", yscalelim, 0, 6," " );
  Dialog.addMessage("Enter dimensions of plot window");
  Dialog.addNumber("X dimension ", plotwidth, 0, 4," pixels" );
  Dialog.addNumber("Y dimension ", plotheight, 0, 4," pixels" );
  Dialog.addMessage("Additional options");
  Dialog.setInsets(-6, 200, 20);
  Dialog.addCheckbox("Edit axis titles, tick marks and grids", false);  
  Dialog.addNumber("Line width ", 2, 0, 4," pixels" );
  option = newArray("yes","No");
  Dialog.addChoice("Invert graph", option, "No");
  position = newArray("Below", "Right", "No"); 
  Dialog.addChoice("Attach graph to image", position, "No");
Dialog.show;


//get responses
if (n>0){
answer=Dialog.getChoice();
if (answer=="No"){
roiManager("Reset");	
}
}
rangelimits = Dialog.getRadioButton();
lowy = Dialog.getNumber(); 
highy = Dialog.getNumber(); 
plotsizex = Dialog.getNumber(); 
plotsizey = Dialog.getNumber();
change_plot=Dialog.getCheckbox();
plotlinewidth = Dialog.getNumber(); 
Inv= Dialog.getChoice();
Attach= Dialog.getChoice();



//set background
pBackground="White";
pLineColour="Black";
//if(Inv=="Yes"){
//pBackground="Black";
//pLineColour="White";
//}

if (Attach!="No"){
	run("Select None");
	run("Duplicate...", "title=temp duplicate");
}


//draw rois
waitForUser("Add ROI's", "Draw ROI's (- press t to add each ROI to ROImanager)\n \n then select OK to continue");
run("Select None");

// create arrays
n=roiManager("count");
if (n==0){
	exit("No ROI's");
}
roiManager("deselect");
roiManager("Remove Channel Info");
roiManager("Remove Slice Info");
roiManager("Remove Frame Info");

if (n>10){
	n=10;
}

RoiData=newArray(ImageFrames*n);
RoiPlot=newArray(ImageFrames);
//colours=newArray("red","green","blue","magenta","yellow","cyan","white");
colours=newArray("red","green","blue","magenta","cyan","#FFFF22","#FF5500", "#660066","#008833", "#9966FF");


//reame and colour and roi's
for (roi=0;roi<n;roi++){
roiManager("select", roi);
roiManager("Rename", "ROI " + roi+1);
roiManager("Set Color", colours[roi]);
roiManager("Set Line Width", plotlinewidth);
roiManager("Remove Frame Info");
}
roiManager("Deselect");
roiManager("Multi Measure");


if(Inv=="Yes"){
//colours=newArray("cyan","magenta","yellow","green","blue","red","white");
colours=newArray("cyan","magenta","#FFFF22","green","red","blue","#00AAFF","#99FF99","#FF88CC", "#669900");
}

//read data
for (roi=0;roi<n;roi++){
for (j=0;j<ImageFrames;j++){	
  RoiData[j+(ImageFrames*roi)]=getResult("Mean(ROI "+roi+1+")", j);
} 
}

selectWindow("Results");
run("Close");

//get y range
Array.getStatistics(RoiData, lowlevel, highlevel, mean, stdDev);
extend=(highlevel-lowlevel)*0.025;
highlevel=highlevel + extend;
lowlevel=lowlevel - extend;


//get x range
Frame_Interval=newArray(ImageFrames);
Fr=Stack.getFrameInterval();
if (Fr==0){
	Fr=1;
}
Stack.getUnits(X, Y, Z, Time, Value);
for (fi=1;fi<ImageFrames;fi++){
Frame_Interval[fi]=fi * Fr;
} 
Array.getStatistics(Frame_Interval, min, xscalelen, mean, stdDev);

for (t=0;t<ImageFrames;t++){
      setResult("Frame Interval (" + Time + ")", t, Frame_Interval[t]);
}

//y range selection
if (rangelimits==" Full intensity range "){
	ymax=yscalelim;
	ymin=0;
}
if (rangelimits==" Set own limits "){
	ymax=highy;
	ymin=lowy;
}
if (rangelimits==" Limit to upper signal "){
	ymax=highlevel;
	ymin=0;
}
if (rangelimits==" Limit to signal range "){
	ymin=lowlevel;
	ymax=highlevel;
}


X_title="Time";
Y_title="Intensity";


//plot options
if (change_plot==true){
Dialog.create("Plot Options");
Dialog.addMessage("Axis titles");
  Dialog.addString("X-axis title:",X_title);
  Dialog.addString("Y-axis title:",Y_title);
Dialog.addMessage("Grids and tick marks");
  format=newArray("grid X","grid Y","major ticks X", "major ticks Y", "minor ticks X", "minor ticks Y","numbers X", "numbers Y");
  defaults=newArray(true,true,true,true,true,true,true,true);
  Dialog.addCheckboxGroup(4,2,format,defaults);
  Dialog.addMessage("interval between numbers, major ticks and grid lines");
  Dialog.addNumber("interval in X", 0);
  Dialog.addNumber("interval in Y", 0);
Dialog.show(); 


X_title= Dialog.getString();
Y_title= Dialog.getString();
gX=Dialog.getCheckbox();
gY=Dialog.getCheckbox();
MatX=Dialog.getCheckbox();
MatY=Dialog.getCheckbox();
MitX=Dialog.getCheckbox();
MitY=Dialog.getCheckbox();
NumX=Dialog.getCheckbox();
NumY=Dialog.getCheckbox();
xint=Dialog.getNumber();
yint=Dialog.getNumber();

opts="1100"+toString(MitY)+toString(MitX)+"00"+toString(gY)+toString(gX)+toString(MatY)+toString(MatX)+toString(NumY)+toString(NumX);
//print(opts);


}




//print results
for (m=0;m<n;m++){
for (p=0;p<ImageFrames;p++){
	  RoiPlot[p]=RoiData[p+(ImageFrames*m)];	
      name="Roi " + m+1;
      setResult(name, p, RoiPlot[p]);
}
}
IJ.renameResults("Results",fn+" Intensity Measurements");


//main plot
setBatchMode(true);
Currfrm=1;

//start
for (fr=0;fr<ImageFrames;fr++){

//plot options
Plot.create("Time Intensity Plot - time point:"+fr , X_title+" (" + Time + ")",Y_title);
        Plot.setBackgroundColor(pBackground);
        if(change_plot==true){
        Plot.setFormatFlags(opts);
        Plot.setOptions("xinterval="+xint+" yinterval="+yint+"");
        }
        Plot.setLimits(0, xscalelen, ymin, ymax);
        Plot.setFrameSize(plotsizex, plotsizey);
        Plot.setLineWidth(plotlinewidth);
        
//for each roi add line
for (roi=0;roi<n;roi++){

//gets line data up to frm
for (p=0;p<Currfrm;p++){
	RoiPlot[p]=RoiData[p+(ImageFrames*roi)];
	PartChannel=Array.trim(RoiPlot, Currfrm);
}

//plots line
		Plot.setColor(colours[roi]);     
        Plot.add("line",Frame_Interval, PartChannel);
        Plot.setFontSize(14, "bold");
        Plot.addText("("+roi+1+")", 0.075+(roi*0.05), 0);
        Plot.setColor(pLineColour);
        Plot.addText("ROI:", 0, 0);
        Plot.setFontSize(12, "plain");
}

//adds vertical line
      Plot.setColor(pLineColour);
      Plot.drawLine((Currfrm-1)*Fr, ymax, (Currfrm-1)*Fr, ymin); 
//displys plot      
Plot.show();

//next frame
Currfrm=Currfrm+1;
}


//join plots
run("Images to Stack", "name=Time Intensity Plot title=[] use");
setBatchMode(false);

//format plots
rename("plot");
getDimensions(plotwidth, plotheight, plotchannels, plotslices, plotframes);

borderbit="RGB black";
if (bitDepth()==8){
	borderbit="8-bit black";
}

//add border at top
newImage("top", borderbit, plotwidth, 8, plotslices);
run("Invert", "stack");
run("Combine...", "stack1=top stack2=plot combine");
if(Inv=="Yes"){
run("Invert", "stack");
}
rename("plot of " + fn);


//scale and add to image
if (Attach=="Below"){
sc="x=- y=- z=1.0 width="+ImageWidth+" height="+ floor(2*ImageWidth/3) + " depth=slices interpolation=Bilinear average process create title=plot";
selectWindow("plot of " + fn);
run("Scale...",sc );
rename("plot2");
run("RGB Color");

selectWindow("temp");
run("RGB Color", "frames");

newImage("border", "RGB white", ImageWidth, 2, ImageFrames);
run("Combine...", "stack1=border stack2=plot2 combine");
rename("plot2");
run("Sharpen", "stack");
run("Combine...", "stack1=temp stack2=plot2 combine");
rename("Combined " + fn);
roiManager("Show All");
run("Flatten", "stack");
selectWindow("plot of "+fn);
close();
}

if (Attach=="Right"){
sc="x=- y=- z=1.0 width="+ floor(ImageHeight*1.3) + " height="+ImageHeight+" depth=ImageSlices interpolation=Bilinear average process create title=plot";
selectWindow("plot of " + fn);
run("Scale...",sc );
rename("plot2");
run("RGB Color");

selectWindow("temp");
run("RGB Color", "frames");

newImage("border", "RGB white", 2, ImageHeight, ImageFrames);
run("Combine...", "stack1=border stack2=plot2");
rename("plot2");
run("Sharpen", "stack");
run("Combine...", "stack1=temp stack2=plot2");
rename("Combined " + fn);
roiManager("Show All");
run("Flatten", "stack");
selectWindow("plot of "+fn);
close();
}


}



