//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 "Add scale bar  Action Tool - Cg00T1g12u Cg00T8g12m C000L03g3 L0105 Lg1g5" 
{
run("Scale Bar...");
}

//**************************************3

macro "Freehand Duplicate/Crop Action Tool -Caaa F00hh Cggg G82288ee8"
{

setTool("rotrect");
ver=getVersion();

if (endsWith(ver, "j")==true){
setTool("tiltrect");
}


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


//draw roi
title = "Draw Crop";
msg = "Draw crop region\n then select OK to continue";
waitForUser(title, msg);

run("Duplicate...");

setTool("rectangle");

do {
Dialog.create("Overlay options");
	title=newArray("Rotate 180 Degrees", "Rotate 90 Degrees Right", "Rotate 90 Degrees Left", "Flip Horizontally","Flip Vertically", "Finish");
	Dialog.addRadioButtonGroup("Modify Orientation", title, 6, 3, "Finish");
Dialog.show(); 

option=Dialog.getRadioButton();

if (option=="Finish"){
	exit();
}
if (option=="Rotate 180 Degrees"){
	run("Rotate... ", "angle=180 grid=1 interpolation=None stack");
} else {
	run(option);
}

} while (option!="Finish");


}




//**********************************************4


macro "Annotated Gallery from multichannel image Action Tool -C00gF0088 C777F8888 Cg00F0888 C0c0F8088  Cggg T3708a Tc708b T3g08c Tcg08d L08h8 L808h C000R00gg" 
{

roiManager("Reset");
run("Colors...", "foreground=white background=black selection=white");
//get user dye names
path=getDirectory("luts");
dye_file=path+"Dyes.txt";
Dye = newArray("DAPI", "488", "546", "568", "594", "647", "GFP","RFP","mCherry","Brightfield","Phase Contrast", "DIC" );


if (File.exists(dye_file)==true){
	dyes=File.openAsString(dye_file); 
	dye_names=split(dyes, "\n");
	Dye = Array.concat(dye_names,Dye); 
}


//get info
fn=getTitle();
rename("new");

setBatchMode(true);

// convert RGB
if (bitDepth()==24){
run("Split Channels");
run("Merge Channels...", "c1=[new (red)] c2=[new (green)] c3=[new (blue)] create");
	rename("new");
}

// check for RGB stack error
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
rename("new");
run("Split Channels");
seq="";
for (chan=1;chan<=ImageChannels;chan++){
nextImage="c"+chan+"=[C"+chan+"-new] ";
seq=seq+nextImage;
}
seq=seq+"create";
run("Merge Channels...", seq);


setBatchMode("exit and display");

getVoxelSize(px, py, pz, units);

run("Channels Tool...");
waitForUser("Select Channels to be included in overlay image");



textfactor=(ImageWidth/325);
totaldisplaychannels=ImageChannels+1;

if(ImageSlices>1 || ImageFrames>1){
	exit("This macro does not work on a Z-Stack ot time series, use 3D Gallery tool");
};


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


//get output info
Dialog.create("Select Output Options");
  Output = newArray("Colour", "Grayscale");
  Dialog.addRadioButtonGroup("Output of the individual images in colour or grayscale?:", Output, 1, 2, "Colour");
  Dialog.addNumber("Number of Columns",cols );
  Dialog.addNumber("Number of Rows", rows);
  Dialog.addNumber("Border Width", 5);
  Dialog.addCheckbox("Get help with this macro? ", false);
Dialog.show;
//inputs  
Col = Dialog.getRadioButton(); 
cols=Dialog.getNumber();
rows=Dialog.getNumber();
Bord=Dialog.getNumber();
hlp=Dialog.getCheckbox();
titletext=newArray(totaldisplaychannels);


if (hlp==true){
title = "Help";
msg = "Select the desired format options \n \n Channel names can be loaded automatically from a text file. \n  \n Create a channel list using notepad, pressing enter after each entry \n \n then save the text file as Dyes.txt into FIJI's LUT directory \n \n This will be loaded as part of the macro if you select 'Add Title'.\n \n After completion the Overlay can be edited using the RoiManager \n";
waitForUser(title, msg);	
}


xtitle=floor(7*textfactor);
ytitle=floor(7*textfactor);

xtext=floor(7*textfactor);
ytext=ImageHeight-floor(7*textfactor);


//get overlay options
Dialog.create("Overlay options");
yesno=newArray("Yes", "No");
title=newArray("Yes", "No");
Option = newArray("Uppercase - ABC", "Lowercase - abc", "Numbers - 123", "No");
Dialog.addRadioButtonGroup("Insert image titles? ", title, 1, 2, "No");
Dialog.setInsets(0, 20, 0);
Dialog.addMessage("NOTE: A user-defined 'title' list can be added to the drop down lists. This will be loaded automatically when the macro runs.");
Dialog.setInsets(-5, 20, 0);
Dialog.addMessage("To create the list, use Notepad to add one dye per line of text, then save the file as 'Dyes.txt' into the LUT directory of FIJI.");
Dialog.setInsets(5, 20, 0);
Dialog.addNumber("Title Text size:", floor(20*textfactor));
Dialog.addCheckbox("Check box to select the position of the title on the image or enter/use the co-ordinates below", false);
Dialog.addNumber("Position of top left of title text from left", xtitle);
Dialog.addNumber("Position of top left of title text from top", ytitle);
Dialog.addRadioButtonGroup("Insert figure letter/numbers?", Option, 1, 4, "No");
Dialog.addNumber("Text size: ", floor(20*textfactor));
Dialog.addCheckbox("Check box to select position of the figue number on the image or enter/use the co-ordinates below", false);
Dialog.addNumber("Position of bottom left of figure text from left", xtext);
Dialog.addNumber("Position of bottom left of figure text from top", ytext);
Dialog.addRadioButtonGroup("Add a scale bar?", yesno, 1, 2, "No");
Dialog.show(); 

//get response
AddTitle=Dialog.getRadioButton();
titleheight=Dialog.getNumber();
marktitle=Dialog.getCheckbox();
xtitle=Dialog.getNumber();
ytitle=Dialog.getNumber();
AddFigNum=Dialog.getRadioButton();
numberheight=Dialog.getNumber();
marktext=Dialog.getCheckbox();
xtext=Dialog.getNumber();
ytext=Dialog.getNumber();
AddScaleBar = Dialog.getRadioButton();

if (AddTitle=="Yes"){
Dialog.create("Overlay options 2");
Dialog.addMessage("Select text names for image titles");
for (i=1; i<totaldisplaychannels; i++) {
Dialog.addChoice("Channel " + i, Dye, Dye[i-1]);
Dialog.addString("or Antibody name: ", "");
}
Dialog.addMessage("Select title name for merged image");
over=newArray("Merged", "Overlay", "Combined", "All Channels", "Blank");
Dialog.addChoice("Select from list ", over, "Merged");
Dialog.addString("or insert your own: ", "");
Dialog.show(); 


for (j=0; j<ImageChannels; j++){
titletext[j] = Dialog.getChoice();
AlternateText=Dialog.getString();
if (AlternateText!=""){
    	titletext[j]=AlternateText;
}	
}
}
merged=Dialog.getChoice();
mergedAlternText=Dialog.getString();
if (merged=="Blank"){
	merged="";
}
if (mergedAlternText!=""){
	merged=mergedAlternText;
}

totalwindows=rows*cols;

//figure number format
if (AddFigNum=="Uppercase - ABC"){
Textformat=newArray("A","B","C","D","E","F","G","H","I","J","K","L");
}
if (AddFigNum=="Lowercase - abc"){
Textformat=newArray("a","b","c","d","e","f","g","h","i","j","k","l");	
}
if (AddFigNum=="Numbers - 123"){
Textformat=newArray(1,2,3,4,5,6,7,8,9,10,11,12);
}




setTool("point");

//select position for title
if (AddTitle=="Yes"){
	titletext[ImageChannels]=merged;	
if (marktitle==true){ 
title = "Get info";
msg = "Mark top left of text for position for figure titles \n then select OK to continue";
waitForUser(title, msg);
getSelectionBounds(xtitle, ytitle, wtitle, htitle);
}
}


//select position for figurenum
if (AddFigNum!="No"){
	if (marktext==true){	
title = "Get info";
msg = "Mark bottom left or text for position for figure numbers \n then select OK to continue";
waitForUser(title, msg);
getSelectionBounds(xtext, ytext, wtext, htext);
}
}



setBatchMode(true);

//main process
selectWindow("new");
run("Duplicate...", "duplicate");
rename("tempx");


selectImage("tempx");     
 if (Col=="Grayscale"){
      Stack.setDisplayMode("grayscale");  
} 
   
run("Split Channels");

selectWindow("new");
rename("C" + totaldisplaychannels + "-tempx");



for (i=1;i<=totaldisplaychannels;i++){
	selectWindow("C"+i+"-tempx");
	run("RGB Color");
	rename(i);
}


//add channels if necessary
v=totaldisplaychannels;
for (i=totaldisplaychannels; i<totalwindows; i++){   
    AddChan2(v);
    v=v+1;
}


//output selection 
if (rows==1 &&   cols>1) {
	format=totaldisplaychannels;
	cols=totaldisplaychannels;
      MontRow2();
   } else if (cols==1 && rows>1){
  	format=totaldisplaychannels;
  	rows=totaldisplaychannels;
  	MontCol2();
   }  else{
      MontBoth2();
   }  



//functions


//row construct
function MontRow2(){
for (j=1; j<format; j++){
selectWindow("1");
XCombine2();
}
}

//combine images in x
function XCombine2(){
newImage("border", "8-bit white", Bord, ImageHeight, 1);
run("RGB Color");
tb="stack1=[1] stack2=[border]";
t="stack1=[1] stack2=["+(j+1)+"]";
run("Combine...", tb);
rename("1");
run("Combine...", t);
rename("1");	
}


//column consruct
function MontCol2(){
for (j=1; j<format; j++){
selectWindow("1");
YCombine2();
}
}

//combine images in y
function YCombine2(){
newImage("border", "8-bit white",ImageWidth, Bord, 1);
run("RGB Color");
tb="stack1=[1] stack2=[border] combine";
t="stack1=[1] stack2=["+(j+1)+"] combine";
run("Combine...", tb);
rename("1");
run("Combine...", t);
rename("1");	
}


//multi function
function MontBoth2(){
totalwindows=rows*cols;
CurrentTotalWindows=totaldisplaychannels;

//combine images into rows and rename
w=1;
format=cols;
for (r=0; r<rows; r++) 
{
MontRow2();
a="r"+w;
rename(a);
w=w+1;
if (rows>1){
	begin=cols+1;
	end=totalwindows-(cols*r);
renumber(begin,end);
}
}

//rename rows and combine rows
for (v=1; v<=rows; v++){
selectWindow("r"+v);
rename(v);
}

for (j=1; j<rows; j++){
selectWindow("1");
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
YCombine2();
}
}
//end of montboth2


//renumber function
function renumber(begin,end){
renum=1;
for (i=begin; i<=end; i++){
selectWindow(i);
rename(renum);
renum=renum+1;
}
}

//add blank channels
function AddChan2(v){
selectWindow(v);
getDimensions(width, height, channels, slices, frames);
newImage("HyperStack", "8-bit grayscale-mode", width, height, 1, slices, frames);
run("RGB Color");
rename(v+1);	
}
///end of functions

//finish up
rename("3D Montage of " + fn);
selectWindow("3D Montage of " + fn);
setVoxelSize(px, py, pz, units);

//add overlay
p=0;
for (rws=0;rws<rows;rws++){
for (cls=0;cls<cols;cls++){
if (p<totaldisplaychannels){
if (AddFigNum!="No"){	
setFont("Arial", numberheight, " antialiased");
Overlay.drawString(Textformat[p], ImageWidth*cls+xtext+(Bord*cls), ImageHeight*rws+ytext+(Bord*rws));
}
if (AddTitle=="Yes" || AddTitle=="Load from file"){
setFont("Arial", titleheight, " antialiased");
Overlay.drawString(titletext[p], ImageWidth*cls+xtitle+(Bord*cls), ImageHeight*rws+ytitle+titleheight+(Bord*rws));
}
p=p+1;
}
}
}

//disply overlay and add to roi manager
Overlay.show();
roiManager("Deselect");
setBatchMode("exit and display");

//scale bar	
if (AddScaleBar=="Yes"){
title = "Get info";
msg = "Adjust scale, check to <Overlay> option and \n mark top left position (optional) \n then select OK to continue";
waitForUser(title, msg);
scalex=(cols-1)*(ImageWidth+Bord) +(floor(ImageWidth*0.8));
scaley=(rows-1)*(ImageHeight+Bord) + (floor(ImageHeight*0.925));
makePoint(scalex, scaley);
run("Scale Bar...");	
}
if (getInfo("overlay")!=""){
run("To ROI Manager");
roiManager("Show All without labels");
}

//tidy up
run("Select None");
setTool("rectangle");
title = "Get info";
msg = "If you have added graphics you will need to flatten the image for export or saving \n In ROI Manager select Flatten \n then select OK to continue";
waitForUser(title, msg);


selectWindow("C" + totaldisplaychannels + "-tempx");
rename(fn);


}










//*******************************************5

macro "Copy overlay to all panels Action Tool -C000 R008f R808f Cg00 H4bc74400 " 
{

eixstroi=roiManager("count");



if (eixstroi>0){
	if (getBoolean("Copy existing ROI's")==true){
	eixstroi=0;
	}
}

title = "Get info";
msg = "select original composite image \n select ok when done";
waitForUser(title, msg);


scl=getBoolean("Do you want to add a scale bar \n if Yes then make sure you add it to overlay");
if (scl==true){
run("Scale Bar..." );
run("To ROI Manager");
}

title = "Add graphics";
msg = "Add graphics (t) \n select ok when done";
waitForUser(title, msg);



run("Make Composite");

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

totaldisplaychannels=channels+1;

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


Dialog.create("Title");
Dialog.addNumber("Image X pixel number", width);
Dialog.addNumber("Image Y pixel number", height);
Dialog.addNumber("Number of rows", rows);
Dialog.addNumber("Number of columns", cols);
Dialog.addNumber("Border width", 5);
Dialog.show(); 

overwidth=Dialog.getNumber(); 
overheight=Dialog.getNumber();
rows=Dialog.getNumber();  
columns=Dialog.getNumber(); 
border=Dialog.getNumber();


panel=1;
n=roiManager("Count")-eixstroi;
for (re=0;re<n;re++){
	roiManager("Select",re+eixstroi);
roiManager("Rename","Panel 1 graphic "+re+1);
}


title = "Get info";
msg = "select destination image";
waitForUser(title, msg);


// number of rows
for (row=0;row<rows;row++){

// number of columns
for (col=0;col<columns;col++){

//ignore panel 1
if (col!=0 || row!=0){

//copy and translate overlay objects to next panel
for (ovobj=0;ovobj<n;ovobj++){
roiManager("Select",ovobj+eixstroi);
roiManager("Add");
roiManager("Select",(n*panel+ovobj)+eixstroi);

roiManager("Rename","Panel "+panel+1+" graphic "+ovobj+1);
roiManager("Select",(n*panel+ovobj)+eixstroi);
roiManager("translate", (overwidth+border)*col,(overheight+border)*row);
}
//next panel
panel=panel+1;

}//end of if
}//end of col
}//end of row


roiManager("Show All without labels");
}




//*******************************************6

macro "Multi Image Gallery from multiple images Action Tool - C44f F00gg  C000  R00gg Cggg L07h7 L808f T36071 Tc6072 T3g073 Tcg074" 
{
roiManager("reset");
//get list of open images
list=getList("image.titles");

list=Array.sort(list);

InitialImages=newArray(list.length);
ImagetoGall=newArray(list.length);
wd=newArray(list.length);
ht=newArray(list.length);

run("Colors...", "foreground=white background=black");
setColor(255, 255, 255);


//add none to list
NoImage=newArray("None");
list=Array.concat(list, NoImage);

//select images
Dialog.create("Select Images and Order");
	Dialog.addMessage("Select Order for Images",14,"Red");
	for (Im=0;Im<list.length-1;Im++){
	Dialog.addChoice("Image "+Im+1, list, list[Im]);
	}
	Dialog.addCheckbox("Overlay filenames on gallery", true);
	Dialog.addCheckbox("Add scale bar to images", false);
	Dialog.addCheckbox("Resize Images for best fit", true);
	colour=newArray("White", "Black");
	Dialog.addRadioButtonGroup("Text Colour?", colour, 1, 2, "White");
	Dialog.addRadioButtonGroup("Border Colour?", colour, 1, 2, "White");
Dialog.show();

//get responses 
for (Im=0;Im<list.length-1;Im++){
InitialImages[Im]=Dialog.getChoice();
}

addTitle=Dialog.getCheckbox();
addScale=Dialog.getCheckbox();
resize=Dialog.getCheckbox();
TextColour=Dialog.getRadioButton();
LineColour=Dialog.getRadioButton();



	
//create image list and max dimensions
nn=0;
for (Im=0;Im<list.length-1;Im++){
if (InitialImages[Im]!="None"){
	ImagetoGall[nn]=InitialImages[Im];
	
	selectWindow(InitialImages[Im]);
	getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
	if (ImageSlices>1 || ImageFrames>1){
		exit("This macro does not work on time or Z Series"); 
	}
	
	wd[Im]=ImageWidth;
    ht[Im]=ImageHeight;
    
    nn=nn+1;
}
}	
ImagetoGall=Array.trim(ImagetoGall, nn);
Array.getStatistics(wd, min, max, mean, stdDev);
maxwd=max;
Array.getStatistics(ht, min, max, mean, stdDev);
maxht=max;


//text size
textsize=floor(12*maxwd/300);



//main routine to make rgb and add title
for (Im=0;Im<nn;Im++){

selectWindow(ImagetoGall[Im]);
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);



//*********************for RGB and single channel iamges ****************
if (bitDepth()==24 || ImageChannels==1){
CreateImages();
selectWindow(ImagetoGall[Im]);
run("Remove Overlay");
}


//********************* for multichanel images **********************
if (bitDepth()!=24 && ImageChannels>1){
CreateImages();
}
}



//***********************stack images****************
run("Images to Stack", "name=Stack title=ImageG use");


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

//scalefactor  *******************

scalefactor=round(cols*maxwd/1000);
scalefactor=1/scalefactor;


Dialog.create("Select Output Options");
  Dialog.addNumber("Number of Columns",cols );
  Dialog.addNumber("Number of Rows", rows);
  Dialog.addNumber("Scale factor", scalefactor);
  Dialog.addNumber("Border Width", 5);
Dialog.show;

cols=Dialog.getNumber();
rows=Dialog.getNumber();
scalefactor=Dialog.getNumber();
bord=Dialog.getNumber();




//*********************montage images******************
if (LineColour=="black"){
run("Colors...", "foreground=black background=black");
}
run("Make Montage...", "columns="+cols+" rows="+rows+" scale="+scalefactor+" use border="+bord);
rename("Gallery");

//tidy up
selectWindow("Stack");
close();
run("Colors...", "foreground=white background=black");
setColor(255, 255, 255);

//add titles
if (addTitle==true){
fnt=getFontList();
Dialog.create("Text options");
for (Im=0;Im<ImagetoGall.length;Im++){
	Dialog.addString("Title for Image "+ImagetoGall[Im], ImagetoGall[Im],40);
}
Dialog.addChoice("Font",fnt,"Arial" );
Dialog.addNumber("Font Size:", textsize);
Dialog.addChoice("Font Style", newArray("normal","bold","italic","bold italic"),"bold");
Dialog.show();
//responses
for (Im=0;Im<ImagetoGall.length;Im++){
ImagetoGall[Im]=Dialog.getString();
}
fonttype=Dialog.getChoice();
textsize=Dialog.getNumber();
fontstyle=Dialog.getChoice();

ypos=textsize*scalefactor+5;


setFont(fonttype, textsize*scalefactor, fontstyle+" antialiased");
//setFont("Arial", textsize*scalefactor, " antialiased");
if (TextColour=="Black"){
setColor(0, 0, 0);
}


tt=0;
for (r=0;r<rows;r++){
for (c=0;c<cols;c++){
Overlay.drawString(ImagetoGall[tt], scalefactor*maxwd*c+bord*c+5, scalefactor*maxht*r+bord*r+ypos);
if (tt<ImagetoGall.length){
tt=tt+1;
}
}
}
Overlay.show();
run("To ROI Manager");
roiManager("Show All without labels");

title = "Get info";
msg = "If you have added titles you will need to flatten the image for export or saving \n In ROI Manager select Flatten \n then select OK to continue";
waitForUser(title, msg);
}



function CreateImages (){
//add overlay
	run("Duplicate...", "duplicate");
	rename("temp1");

//resize as neccessary
if (resize==true){	

if(wd[Im]!=maxwd || ht[Im]!=maxht){
wdiff=maxwd-wd[Im];
hdiff=maxht-ht[Im];
enlargeImage=wdiff;
if (wdiff>hdiff){
	enlargeImage=hdiff;
}

run("Size...", "width="+wd[Im]+enlargeImage+"  height="+ht[Im]+enlargeImage+"  constrain interpolation=Bilinear");
}
}
//change canvas size	
run("Canvas Size...", "width="+maxwd+" height="+maxht+" position=Center zero");

run("Flatten");
if (addScale==true){	
	run("Scale Bar...");
}

//rename
rename("ImageG"+Im);
if (isOpen("temp1")==true){
selectWindow("temp1");
close();
}
}
//end of function

}

//*******************************************7

macro "3D Gallery from multichannel image (v2) Action Tool - C99gF1188 C777F9988 Cg99F1988 C9g9F9188 C000R11gg C000T3e123 Tae12D" 
{

//get info
fn=getTitle();

//create Duplicate
run("Make Composite");
run("Duplicate...", "duplicate");
rename("new");
getDimensions(width, height, channels, slices, frames);
getVoxelSize(px, py, pz, units);


if (slices>1 && frames>1){
	exit(Macro does not work on a timed Z stack);
}

totaldisplaychannels=channels+1;
steps=frames;
step="frames";
if (slices>1){
step="slices";
steps=slices;
}	

//work out columns
rows=1;
if ((channels+1)/3>1){
rows=floor((channels+1)/3)+1;
}
cols=floor((channels+1)/rows);
if (cols*rows<channels+1){
cols=cols+1;
}

//dialog
Dialog.create("3D Gallery");
  Dialog.addMessage("Select layout for the final images");
  Output = newArray("One row", "One column", "Multiple");
  Dialog.addRadioButtonGroup("Arrangement Shape:", Output, 3, 2, "Multiple");
  Dialog.addNumber("If multiple select number of  rows:", rows);
  Dialog.addNumber("and number of columns:", cols);
  Dialog.addNumber("Image border width in pixels:", 4);
  Scale = newArray("Yes", "No");
  Dialog.addRadioButtonGroup("Scale bar? (tick - 'Label all slices')", Scale, 1, 1, "No");
Dialog.show;
  
Arrangement=Dialog.getRadioButton();
rows=Dialog.getNumber();
cols=Dialog.getNumber();
bw=Dialog.getNumber(); 
ScaleBar = Dialog.getRadioButton();
if (bw==0){
borderwidth=1;
}
else if (bw>0){
borderwidth=bw;
}


setBatchMode(true);
//duplicate
run("Duplicate...", "title=[tempx] duplicate range=1-"+steps);


//split channels
selectWindow("tempx");
run("Split Channels");
for (i = 1; i<=channels; i++)
{
selectWindow("C"+i+"-tempx");
run("RGB Color");
rename(i);
}

//create overlay
selectWindow("new");
run("Stack to RGB", step);
if (steps>1){
selectWindow("new");
}
rename(totaldisplaychannels);


//output selection
if (Arrangement=="One row") {
	  format=totaldisplaychannels;
      MontRow();
   } else if (Arrangement=="Multiple"){
      MontBoth();
   }  else if (Arrangement=="One column"){
   	  format=totaldisplaychannels;
      MontCol();
   }  


//multi function
function MontBoth(){
totalwindows=rows*cols;
CurrentTotalWindows=totaldisplaychannels;

//add channels if necessary
v=totaldisplaychannels;
for (i=CurrentTotalWindows; i<totalwindows; i++){   
    AddChan(v);
    v=v+1;
}

//main part
w=1;
format=cols;
for (r=0; r<rows; r++) 
{
MontRow();
a="r"+w;
rename(a);
w=w+1;

if (rows>1){
	begin=cols+1;
	end=totalwindows-(cols*r);
renumber(begin,end);
}
}

for (v=1; v<=rows; v++){
selectWindow("r"+v);
rename(v);
}

for (j=1; j<rows; j++){
YCombine();
}
}


//renumber function
function renumber(begin,end){
renum=1;
for (i=begin; i<=end; i++){
selectWindow(i);
rename(renum);
renum=renum+1;
}
}

//row construct
function MontRow(){
for (j=1; j<format; j++){
selectWindow("1");
XCombine();
}
}

//column consruct
function MontCol(){
for (j=1; j<format; j++){
selectWindow("1");
YCombine();
}
}

//combine images in x
function XCombine(){
getDimensions(width, height, channels, slices, frames);
newImage("HyperStack", "8-bit grayscale-mode", borderwidth, height, 1, slices, frames);
if (bw>0){
run("Invert LUT");
}
run("RGB Color");
rename("border");
t="stack1=[1] stack2=["+(j+1)+"]";
tb="stack1=[1] stack2=[border]";
run("Combine...", tb);
rename("1");
run("Combine...", t);
rename("1");	
}

//combine images in y
function YCombine(){
getDimensions(width, height, channels, slices, frames);
newImage("HyperStack", "8-bit grayscale-mode", width, borderwidth, 1, slices, frames);
if (bw>0){
run("Invert LUT");
}
run("RGB Color");
rename("border");
t="stack1=[1] stack2=["+(j+1)+"] combine";
tb="stack1=[1] stack2=[border] combine";
run("Combine...", tb);
rename("1");
run("Combine...", t);
rename("1");	
}

//add blank channels
function AddChan(v){
selectWindow(v);
getDimensions(width, height, channels, slices, frames);
newImage("HyperStack", "8-bit grayscale-mode", width, height, 1, slices, frames);
run("RGB Color");
rename(v+1);	
}

setBatchMode(false);

//finish up
if (steps==frames){
	swap="order=xyczt(default) channels=1 slices=" + slices + " frames=" + frames +" display=Composite";
run("Stack to Hyperstack...", swap);
}

//scalr bar
if (ScaleBar=="Yes")
{
run("Scale Bar...");	
}
	
setVoxelSize(px, py, pz, units);
rename("3D Montage of " + fn);
}




//*******************************************8

macro "Orthoview Gallery Action Tool - C00g F1ed3  Cg00 F22cc C0g0 Fe13d C000 Fee33 C000 R11gg  Cgg0 L28d8 L828d" 
 {

//get info
fn=getTitle();
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
getVoxelSize(px, py, pz, unit);
main_Option=newArray("Single slice","Max Intensity","Average Intensity");
roiManager("reset");

//error check
if (ImageSlices==1) {
	exit("Image not a stack");
}

//dialog
Dialog.create("Ortho Gallery");
  Dialog.addMessage("Main Panel (En-face View) option");
  Dialog.addChoice("Display as:", main_Option);
  Dialog.addNumber("Image border width in pixels:", 4);
  Dialog.addCheckbox("Add Line Overlays to Z Profiles", false);
  Scale = newArray("Yes", "No");
  Dialog.addRadioButtonGroup("Add a Scale Bar?", Scale, 1, 1, "No");
Dialog.show;

//responses
main=Dialog.getChoice();
bw=Dialog.getNumber(); 
ln=Dialog.getCheckbox();
Sc = Dialog.getRadioButton();

//updat responses
if (main!="Single slice"){
	ln=false;
}


//run orthogonal
run("Duplicate...", "title=temp duplicate");
run("Orthogonal Views");

selectWindow("temp");
waitForUser("Edit View","Select x, y & z position in main image\n \n then select OK to continue");

//get image titles
Imtitles=getList("image.titles");
for (im=0;im<Imtitles.length;im++){
if (startsWith(Imtitles[im], "YZ ")){
    yz=Imtitles[im];
}
if (startsWith(Imtitles[im], "XZ ")){
	xz=Imtitles[im];
}
}

setBackgroundColor(255, 255, 255);

//create yz view
selectWindow(yz);
run("To ROI Manager");
run("Remove Overlay");
run("Duplicate...", " ");
run("RGB Color");
rename("2");
if (ln==true){
roiManager("Draw");
}
selectWindow("2");
getDimensions(Slice1Width, Slice1Height, Slice1Channels, Slice1Slices, Slice1Frames);
run("Canvas Size...", "width="+Slice1Width+" height="+Slice1Height+bw+" position=Top-Center");

//create xz view
selectWindow(xz);
run("To ROI Manager");
run("Remove Overlay");
run("Duplicate...", " ");
run("RGB Color");
rename("3");
if (ln==true){
roiManager("Draw");
}
selectWindow("3");
getDimensions(Slice2Width, Slice2Height, Slice2Channels, Slice2Slices, Slice2Frames);
run("Canvas Size...", "width="+Slice2Width+bw+" height="+Slice2Height+" position=Center-Left");


//create main view
selectWindow("temp");
run("To ROI Manager");
if (main!="Single slice"){
	selectWindow("temp");
run("Z Project...", "projection=["+main+"]");
rename("1");
}else{
selectWindow("temp");
run("Duplicate...", "title=1");
}
selectWindow("temp");
close();
selectWindow("1");
run("RGB Color");
roiManager("Draw");
if (ImageChannels>1){
	selectWindow("1");
close();
selectWindow("1 (RGB)");
}
rename("1");


//Join images
selectWindow("1");	
run("Canvas Size...", "width="+ImageWidth+bw+" height="+ImageHeight+bw+" position=Top-Left");
setBackgroundColor(0,0,0);
run("Combine...", "stack1=1 stack2=2");
rename("1");
run("Combine...", "stack1=1 stack2=3 combine");


//add scalr bar
if (Sc=="Yes")
{
run("Scale Bar...");	
}

 }

//*********************************************9

macro "Multi Slice Action Tool - C000 R03g8 C0g0 H1a386586a8c9d9fa00 Cg00 P19386988a9c8f90 "
{
setTool("Line");
run("Set Measurements...", "area mean min display redirect=None decimal=3");
run("Clear Results");
n=roiManager("Count");
fn=getTitle();


//get info
Dialog.create("Options");
	items=newArray("Yes","No");
if (n>0){
	Dialog.addChoice("Do you want to keep existing ROI's", items, "Yes")
}	
	Dialog.addNumber("Thickness of line (pixels) ", 1);
	Dialog.addChoice("Do you want to create a XY projection", items, "No")
	Dialog.addCheckbox("Flip image vertically", false);
	Dialog.addCheckbox("Rotate 90 degrees", false);
Dialog.show();	

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

thick=Dialog.getNumber();
run("Line Width...", "line=thick");
projection=Dialog.getChoice();
Flip=Dialog.getCheckbox();
Rot=Dialog.getCheckbox();

if (Flip==true){
	Flip=" flip";
}else {
	Flip="";
}

if (Rot==true){
	Rot=" rotate";
}else {
	Rot="";
}

//get line info

title = "Add lines";
msg = "Draw lines and add to ROI Manager (t) \n press OK to continue";
waitForUser(title, msg);

roiManager("Deselect");
roiManager("Measure");
n=roiManager("Count");

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


for (roi=0;roi<n;roi++){
roiManager("Select",roi);
roiManager("rename","Line "+roi+1);

ang=getResult("Angle",roi);
if (ang<-90){
	ang=180-(ang*-1);
}
else if (ang>90){
	ang=ang-180;
}


//create crop and rotate
selectWindow(fn);
roiManager("Select",roi);
getBoundingRect(xbr, ybr, wbr, hbr);
if (wbr<thick){
	wbr=wbr+(thick*2);
	xbr=xbr-thick;
}
if (hbr<thick){
	hbr=hbr+(thick*2);
	ybr=ybr-thick;
}
run("Specify...", "width=wbr height=hbr x=xbr y=ybr slice=1");
run("Duplicate...", "duplicate");
rename("tempcut");
run("Rotate... ", "angle=ang grid=1 interpolation=Bilinear enlarge stack");
run("Select None");


//get line image
selectWindow("tempcut");
getDimensions(width, height, channels, slices, frames);
halfway=(height/2)-(thick/2);
run("Specify...", "width=width height=thick x=0 y=halfway slice=1");
run("Duplicate...", "duplicate");
rename("slice");

selectWindow("tempcut");
close();


//reslice
selectWindow("slice");
getVoxelSize(px, py, pz, unit);
run("Reslice [/]...", "output=px start=Top"+Flip+Rot);
rename("Line "+roi+1+" Profile "+fn);
selectWindow("slice");
close();


//make projection
if (thick>1){
	selectWindow("Line "+roi+1+" Profile "+fn);
	run("Z Project...", "projection=[Max Intensity]");
	rename("Max projection of Line "+roi+1+" Profile scaled & interpolated "+fn);
	run("Select None");
}


//end of loop
}


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

if (projection=="Yes"){
selectWindow(fn);
run("Z Project...", "projection=[Max Intensity]");
rename("Max Projection of "+fn);
roiManager("Deselect");
roiManager("Set Line Width", thick);
roiManager("Show All with labels");
}

for (im=0;im<n;im++){
	selectWindow("Line "+im+1+" Profile "+fn);
		run("Select None");
if (thick>1){
	selectWindow("Max projection of Line "+im+1+" Profile scaled & interpolated "+fn);
		run("Select None");
}		
}

run("Line Width...", "line=1");
}



************************************************10

macro "ReSlice Movie Action Tool - C555 F00hb F0bh6 C6g6 H245679b9d7e582530 P2e3f4e6f9eafee0 C999 G245679b9d7e582530 C00g V7e32 V7434 Cggg R00hb R0bh6" 
{
//requires("1.53c");
ver=IJ.getFullVersion;

//initialise
roiManager("reset");
roiManager("Associate", "true");
roiManager("Centered", "false");
roiManager("UseNames", "false");
run("Colors...", "foreground=white background=black selection=white");
cols=newArray("White","Red","Green","Blue","Magenta","Cyan","Yellow","orange","Black");
transparent=newArray("#4dffffff","#4dff0000","#4d00ff00", "#4d0000ff","#4dff00ff","#4d00ffff","#4dffff00","#4dffc800","#4dffffff");
setLineWidth(1);
fl="";

//get info
fn=getTitle();
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
getVoxelSize(px, py, pz, unit);
bd=bitDepth();
border=round(ImageHeight/250);
if (border<1){
	border=1;
}

if (ImageSlices==1){
	exit("This macro only works on z stack"); 
}

pos=newArray("Top","Bottom");

//dialog
Dialog.create("Options");
	Dialog.addMessage("Re-sample in Z for thicker Z profile slices and smaller final size");
	Dialog.addMessage("(eg. 2 = half the size & double the thickness, 1 = no resampling)");
	Dialog.setInsets(10, 30, 0);
	Dialog.addNumber("Re-sampling size (Integer):", 2);
	Dialog.addCheckbox("Create a Multi-Channel Gallery for Z the profile", false);
	Dialog.setInsets(0, 60, 0);
	Dialog.addRadioButtonGroup("Position of merged image", pos, 1, 2, pos[1]);
	Dialog.setInsets(20, 30, 0);
	Dialog.addCheckbox("Flip Z Profile Vertically", false);
	Dialog.addChoice("Line Position Colour", cols);
	Dialog.addCheckbox("Make Line Semi-transparent", false);
	Dialog.addCheckbox("Add a Scale Bar to Projection Image", true);	
Dialog.show();

//responses
resample=round(Dialog.getNumber());
mc=Dialog.getCheckbox();
merpos=Dialog.getRadioButton();
flip_Z=Dialog.getCheckbox();
col=Dialog.getChoice();
Semi_transparent=Dialog.getCheckbox();
sb=Dialog.getCheckbox();

//flip z
if (flip_Z==true){
	fl="flip";
}

//setLineWidth(resample);
Line_colour=col;

if (Semi_transparent==true){
for (c=0;c<9;c++){
	if (col==cols[c]){
	Line_colour=transparent[c];
}
}
}

//initial duplicate and reslice
run("Duplicate...", "title=XY duplicate");
if (bd==24){
	run("Make Composite");
}
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
setVoxelSize(px, py, pz, unit);
run("Reslice [/]...", "output="+px*resample+" start=Top "+fl+"");
rename("Resliced");
getDimensions(stackWidth, stackHeight, stackChannels, stackSlices, stackFrames);
setBackgroundColor(255,255,255);


//create Gallery
if (mc==true && ImageChannels>1){
run("Duplicate...", "title=channels duplicate");
selectWindow("Resliced");
run("RGB Color", "slices");
run("Canvas Size...", "width=ImageWidth height="+stackHeight+border+" position=Bottom-Center");
rename("1");

selectWindow("channels");
run("Split Channels");
for (ch=1;ch<=ImageChannels;ch++){
selectWindow("C"+ch+"-channels");
run("RGB Color", "slices");
run("Canvas Size...", "width=ImageWidth height="+stackHeight+border+" position=Bottom-Center");
rename(ch+1);
}

if (merpos==pos[1]){
	selectWindow("1");
	rename("end");
	for (ch=1;ch<=ImageChannels;ch++){
	selectWindow(ch+1);
	rename(ch);	
}
	selectWindow("end");
	rename(ImageChannels+1);
}



for (ch=1;ch<=ImageChannels;ch++){
run("Combine...", "stack1=1 stack2="+ch+1+" combine");
rename("1");
}
rename("Resliced");


}else{
	selectWindow("Resliced");
	run("RGB Color", "slices");
}

//build new image
getDimensions(NewStackWidth, NewStackHeight, NewStackChannels, NewStackSlices, NewStackFrames);
run("Canvas Size...", "width=ImageWidth height="+ImageHeight+NewStackHeight+1+" position=Bottom-Center");

//create projection and add scale bar
selectWindow("XY");
run("Z Project...", "projection=[Max Intensity]");
run("RGB Color");
rename("Max");
if (sb==true){
	run("Scale Bar...");
}
run("Copy");


//add projection and progress line
for (sl=1;sl<=NewStackSlices;sl++){
selectWindow("Resliced");
Stack.setSlice(sl);
makeRectangle(0, 0, ImageWidth, ImageHeight);
run("Paste");
makeRectangle(0, (sl)*resample-resample, ImageWidth, resample);
roiManager("add");
}


//flatten
n=roiManager("count");
for (roi=0;roi<n;roi++){
roiManager("select", roi);
if (ver>"1.52u"){
RoiManager.setPosition(roi+1);
}
roiManager("Set Line Width", 0);
roiManager("Set Color", Line_colour);
roiManager("Set Fill Color", Line_colour);
}

roiManager("Show All without labels");
run("Flatten", "stack");

rename(fn+" Z Slice movie");

//finish up
run("Select None");
selectWindow("XY");
close();
if (isOpen("MAX_XY")){
	selectWindow("MAX_XY");
	close();
}
selectWindow("Max");
close();
run("Colors...", "foreground=white background=black selection=white");
}



//***********************************11

macro "Zoom movie creation Action Tool - Cg00 V5177 V1255 C00g H6ah6he00 L883h L489h C555 F06c9  Cggg T4e08Z"
{
//initialise
fn=getTitle();
roiManager("reset");
run("Clear Results");
run("Remove Overlay");
run("Select None");
run("Set Measurements...", "area mean min centroid display redirect=None decimal=3");
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
getVoxelSize(px, py, pz, unit);
CentreX=ImageWidth/2;
CentreY=ImageHeight/2;

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

Orig=fn;
CoreImageNumber=40;

if (ImageChannels>1){
	run("Stack to RGB");
	rename("OriginalRGB");
	Orig="OriginalRGB";
}

Dialog.create("Movie Options");
Dialog.addMessage("Image frame dimensions currently is "+ImageWidth+" by "+ImageHeight+" pixels");
if (ImageWidth>1024 || ImageHeight>1024){
Dialog.addMessage("!! Image dimensions may be too large for AVI format - Suggest scaling");	
}
Dialog.addMessage("Frame size (uncompressed) currently is approximately "+floor(ImageWidth*ImageHeight*3/75000)/10+" MB per frame");
Dialog.addMessage("eg Final size (uncompressed)= frame size * number of images (default settings="+(CoreImageNumber+10)*floor(ImageWidth*ImageHeight*3/75000)/10+" MB)"); 
Dialog.addMessage("NB. Saving as AVI using JPEG compression will substantially reduce the final file size\n ");
Dialog.addMessage("Scaling the final image will increase or reduce final movie size");
Dialog.addNumber("Scale final image (values between 0 & 1 to reduce size)", 1);
Dialog.addNumber("Number of Fixed Images before zoom: ", 5);
Dialog.addNumber("Number of steps during zoom (more steps = smoother movie: ", CoreImageNumber);
Dialog.addNumber("Number of Fixed Images after zoom: ", 5);
Dialog.addCheckbox("Add zoom mask to image", true);
Dialog.addCheckbox("Add a Scale Bar", true);
Dialog.show(); 

scale=Dialog.getNumber();
pre=Dialog.getNumber();
steps=Dialog.getNumber();
post=Dialog.getNumber();
AddMask=Dialog.getCheckbox();
AddScaleBar=Dialog.getCheckbox();


//create roi
run("Specify...", "width="+ImageWidth/2+" height="+ImageHeight/2+" x=CentreX y=CentreY centered");
waitForUser("Rectangle","Edit/move Rectangle");

//get size and location
getSelectionBounds(x, y, ZoomWidth, ZoomHeight);
run("Measure");
FinalCentreX=getResult("X",0)/px;
FinalCentreY=getResult("Y",0)/py;

//error check for roi
if (ZoomWidth/ZoomHeight!=ImageWidth/ImageHeight){
	ZoomWidth=ZoomHeight*ImageWidth/ImageHeight;
}


setBatchMode("hide");


//get differences between start and finish
diffx=CentreX-FinalCentreX;
diffy=CentreY-FinalCentreY;
diffZoomWidth=ImageWidth-ZoomWidth;
diffZoomHeight=ImageHeight-ZoomHeight;

//create arrays for steps
tempx=newArray(steps);
tempy=newArray(steps);
tempZoomWidth=newArray(steps);
tempZoomHeight=newArray(steps);


//create rois
for (crop=0;crop<steps;crop++){
tempx[crop]=CentreX-(diffx/(steps-1)*crop);
tempy[crop]=CentreY-(diffy/(steps-1)*crop);
tempZoomWidth[crop]=ImageWidth-(diffZoomWidth/(steps-1)*crop);
tempZoomHeight[crop]=ImageHeight-(diffZoomHeight/(steps-1)*crop);
run("Specify...", "width="+tempZoomWidth[crop]+" height="+tempZoomHeight[crop]+" x="+tempx[crop]+" y="+tempy[crop]+" centered");
roiManager("Add");	
}

n=roiManager("count");

///add mask to image
selectWindow(Orig);
roiManager("select",n-1);
run("Add Selection...");

run("Flatten", "stack");
rename("mask");



//fisrt image
	selectWindow(Orig);
	run("Select None");
run("Duplicate...", "title=Zoom duplicate");
run("RGB Color");
	run("Size...", "width="+ImageWidth*scale+" height="+ImageHeight*scale+" average interpolation=Bilinear");
if (AddScaleBar==true){
	AddScale1();
}

//pre images
for (before=0;before<pre-1;before++){
	selectWindow(Orig);
	DUPZ1();
}


//create each step and concatenate
for (crop=1;crop<steps;crop++){
if (AddMask==true){
	selectWindow("mask");
}	else selectWindow(fn);
	roiManager("Select",crop);
	DUPZ1();
}

//post images
for (after=0;after<post;after++){	
	selectWindow(Orig);
	roiManager("Select",steps-1);
	DUPZ1();
}

setBatchMode("exit and display");



function DUPZ1(){
	run("Duplicate...", "title=[Im] duplicate");
	run("RGB Color");    
	run("Size...", "width="+ImageWidth*scale+" height="+ImageHeight*scale+" average interpolation=Bilinear");

if (AddScaleBar==true){
	AddScale1();
}
	run("Concatenate...", "  title=[Zoom] open image1=Zoom image2=Im");	
}



function AddScale1(){
getVoxelSize(barpx, barpy, barpz, unit);
bar=floor(ImageWidth*scale*barpx/5);
barHT=round(ImageHeight*scale/100);
barFT=round(ImageHeight*scale/25);
	run("Scale Bar...", "width=bar height=barHT font=barFT color=White background=None location=[Lower Right] bold");
}

selectWindow("mask");
close();
selectWindow("Results");
run("Close");
if (ImageChannels>1){
	selectWindow(Orig);
	run("Close");
}
selectWindow(fn);
run("Remove Overlay");
run("Select None");
selectWindow("Zoom");
rename(fn+" Zoom");

}





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

macro "Panning movie creation tool Action Tool - Cg00 V5177 V1255 C00g H6ah6he00 L883h L489h C555 F06c9  Cggg T4e08P"
{
//initialize
setTool("rectangle");
roiManager("Reset");
run("Colors...", "foreground=white background=black selection=white");
fn=getTitle();
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
getVoxelSize(px, py, pz, unit);
bd=bitDepth();
//check image properties 
if (ImageSlices>1 || ImageFrames>1){
	exit("This macro does not work on time or Z series");
}

BoxLineWidth=round(ImageWidth/100);
cols=newArray("White","Black","Red","Green","Blue","Magenta","Cyan","Yellow");

//get input
Dialog.create("Movie Options");
Dialog.addMessage("## Crop Region Options ##");
Dialog.setInsets(2, 20, 0);
Dialog.addCheckbox("Specify Dimensions of Crop region", false);
Dialog.addSlider("Zoom factor of crop region", 0.25, 3, 1);
Dialog.setInsets(2, 20, 0);
Dialog.addMessage("## Path Options ##");
Dialog.setInsets(-2, 20, 0);
pathtools=newArray("freeline","line","polyline","multipoint");
Dialog.addRadioButtonGroup("Path creation tool", pathtools, 1, 3, pathtools[0]);
Dialog.addNumber("Sampling factor for freeline/line (integers>1 reduce movie length)",1);
Dialog.addMessage("## Over-view Image Options ##");
Dialog.setInsets(2, 20, 0);
Dialog.addCheckbox("Draw path on over-view image", false);
Dialog.addNumber("Width of over-view image (pixels)",200);
Dialog.addNumber("Thickness of box region on over-view image (pixels)",BoxLineWidth);
Dialog.addToSameRow();
Dialog.addChoice("Box Colour", cols);
Dialog.addNumber("Thickness of path line on over-view image (pixels)",floor(BoxLineWidth/3*2));
Dialog.addToSameRow();
Dialog.addChoice("Path Colour", cols);
posit=newArray("Top-Center","Center","Bottom-Center");
Dialog.addChoice("Over-view position in left panel", posit);
Dialog.addToSameRow();
Bkcol=newArray("Black","White");
Dialog.addChoice("Background Colour", Bkcol);
Dialog.addMessage(" \n## Scale Bar Options ##");
Dialog.addCheckbox("Add a scale bar to the Over-view image", true);
Dialog.setInsets(-24, 280, 0);
Dialog.addCheckbox("Add a scale bar to the Crop image", true);
Dialog.addNumber("Estimated length of scale bar (1/10 image width) in "+unit,floor(ImageWidth*px/10));
Dialog.addToSameRow();
Dialog.addChoice("Scale Bar Colour", cols);
Dialog.show(); 

//responses
specify=Dialog.getCheckbox();
zoom=Dialog.getNumber();
PathTool=Dialog.getRadioButton();
step=round(Dialog.getNumber());
DrawPath=Dialog.getCheckbox();
OverViewWidth=Dialog.getNumber();
BoxLineWidth=Dialog.getNumber();
BoxCol=Dialog.getChoice();
PathLineWidth=Dialog.getNumber();
PathCol=Dialog.getChoice();
ViewPosit=Dialog.getChoice();
Bkground=Dialog.getChoice();
AddScaleView=Dialog.getCheckbox();
AddScaleCrop=Dialog.getCheckbox();
ScaleLength=Dialog.getNumber();
ScaleCol=Dialog.getChoice();


//create an RGB copy
selectWindow(fn);
run("Select None");
run("Duplicate...", "title=TempView duplicate");
if (ImageChannels>1){
run("Flatten");
}
if (bd==8 || bd==16){
run("RGB Color");
rename("TempView");
}

if (zoom!=1){
	run("Size...", "width="+ImageWidth*zoom+"  constrain average interpolation=Bilinear");
}


//draw crop region
if (specify==true){
Dialog.create("Crop Region Options");
	Dialog.addNumber("Width of Crop Region (pixels)",floor(ImageWidth/4*zoom));
	Dialog.addNumber("Height of Crop Region (pixels)",floor(ImageHeight/4*zoom));
	Units=newArray("pixels",unit);
	Dialog.addRadioButtonGroup("Units", Units, 1, 2, Units[0]);
Dialog.show();
cropWidth=Dialog.getNumber();
cropHeight=Dialog.getNumber();
ApplyUnits=Dialog.getRadioButton();

if (ApplyUnits==unit){
	cropWidth=cropWidth/px;
	cropHeight=cropHeight/py;
}
	
} else {
waitForUser("","Draw Crop Region");
getSelectionBounds(cropX, cropY, cropWidth, cropHeight);
run("Select None");
}


//get scale bar dimensions for over view image	
getVoxelSize(px1, py1,pz1, unit);
bar1=floor(cropWidth*px1/5);
barHT1=round(ImageHeight/150);
barFT1=round(ImageHeight/30);


//draw pan path
setTool(PathTool);
waitForUser("","Draw Panning Path");
if (PathTool=="freeline"){
	run("Fit Spline");
}
if (PathTool=="line"){
	run("Interpolate", "interval=step smooth");
}
roiManager("add")
getSelectionCoordinates(xpoints, ypoints);
//Array.show(xpoints, ypoints);



//start routine
setBatchMode("hide");

//initial crop
ImNum=1;
selectWindow("TempView");
makeRectangle(xpoints[0]-(cropWidth/2), ypoints[0]-(cropHeight/2),cropWidth,cropHeight);
roiManager("Add");
run("Duplicate...", "title=crop duplicate");
if (AddScaleCrop==true){
		run("Scale Bar...", "width="+ScaleLength+" height="+barHT1+" font="+barFT1+" color="+ScaleCol+" background=None location=[Lower Right] bold");	
}

//initial overview
selectWindow("TempView");
run("Select None");
run("Duplicate...", "title=Oview duplicate");
if (DrawPath==true){
roiManager("select",0);
run("Colors...", "foreground="+PathCol+" background=black selection=white");
run("Line Width...", "line="+PathLineWidth*zoom);
run("Draw", "slice");

}
roiManager("select",1);
run("Colors...", "foreground="+BoxCol+" background=black selection=white");
run("Line Width...", "line="+BoxLineWidth*zoom);
run("Draw", "slice");
run("Select None");
run("Size...", "width="+OverViewWidth+" constrain average interpolation=Bilinear");
if (AddScaleView==true){
		run("Scale Bar...", "width="+ScaleLength+" height="+barHT1+" font="+barFT1+" color="+ScaleCol+" background=None location=[Lower Right] bold");	
}
getDimensions(viewWidth, viewHeight, viewChannels, viewSlices, viewFrames);

//sequential routine

for (pt=step;pt<xpoints.length;pt+=step){
showProgress(pt,xpoints.length);
//sequential crop
selectWindow("TempView");
makeRectangle(xpoints[pt]-(cropWidth/2), ypoints[pt]-(cropHeight/2),cropWidth,cropHeight);
roiManager("Add");
run("Duplicate...", "title=cropnew duplicate");
getDimensions(TempWidth, TempHeight, TempChannels, TempSlices, TempFrames);   

//check crop is not outseide image
if (TempWidth<cropWidth || TempHeight<cropHeight){

	if (ypoints[pt]-(cropHeight/2)+cropHeight>ImageHeight || xpoints[pt]-(cropWidth/2)+cropWidth>ImageWidth){
	type="Top-Left";
}
	if (xpoints[pt]-(cropWidth/2)<0 || ypoints[pt]-(cropHeight/2)<0){
	type="Bottom-Right";
}
	if (xpoints[pt]-(cropWidth/2)<0 && ypoints[pt]-(cropHeight/2)+cropHeight>ImageHeight){
	type="Top-Right";
}
	if (ypoints[pt]-(cropHeight/2)<0 && xpoints[pt]-(cropWidth/2)+cropWidth>ImageWidth){
	type="Bottom-Left";
}
	run("Canvas Size...", "width="+cropWidth+" height="+cropHeight+" position="+type);
}

if (AddScaleCrop==true){
		run("Scale Bar...", "width="+ScaleLength+" height="+barHT1+" font="+barFT1+" color="+ScaleCol+" background=None location=[Lower Right] bold");	
}
run("Concatenate...", "  title=crop open image1=crop image2=cropnew image3=[-- None --]");

//sequential overview
selectWindow("TempView");
run("Select None");
run("Duplicate...", "title=Oviewnew duplicate");
if (DrawPath==true){
roiManager("select",0);
run("Colors...", "foreground="+PathCol+" background=black selection=white");
run("Line Width...", "line="+PathLineWidth*zoom);
run("Draw", "slice");
}
roiManager("select",pt/step+1);
run("Colors...", "foreground="+BoxCol+" background=black selection=white");
run("Line Width...", "line="+BoxLineWidth*zoom);
run("Draw", "slice");
run("Select None");
run("Size...", "width="+OverViewWidth+" constrain average interpolation=Bilinear");
if (AddScaleView==true){
		run("Scale Bar...", "width="+ScaleLength+" height="+barHT1+" font="+barFT1+" color="+ScaleCol+" background=None location=[Lower Right] bold");	
}
run("Concatenate...", "  title=Oview open image1=Oview image2=Oviewnew image3=[-- None --]");
ImNum=ImNum+1;
}
//clean up
selectWindow("TempView");
close();

run("Colors...", "foreground=white background="+Bkground+" selection=white");

//join image
borderheight=cropHeight;
if (borderheight<viewHeight){
	borderheight=viewHeight;
	selectWindow("crop");
	run("Canvas Size...", "height="+borderheight+" position="+ViewPosit);
} else{
	selectWindow("Oview");
	run("Canvas Size...", "height="+borderheight+" position="+ViewPosit);
}

newImage("border", "RGB white", 4, borderheight, ImNum);
run("Combine...", "stack1=Oview stack2=border");
rename("Oview");
run("Combine...", "stack1=Oview stack2=crop");
rename(fn+" Final movie");

setBatchMode("exit and display");

//finish up
run("Line Width...", "line=1");
run("Colors...", "foreground=white background=black selection=white");
setTool("line");

//progress bar function
function getBar(p1, p2){
   n = 25;
   bar1 = "-------------------------";
   bar2 = "*************************";
   index = round(n*(p1/p2));
if (index<1) index = 1;
if (index>n-1) index = n-1;
return substring(bar2, 0, index) + substring(bar1, index+1, n);
}

}



//***************************************13

macro "Zoom then Panning movie creation Action Tool - Cg00 V5177 V1255 C00g H6ah6he00 L883h L489h C555 F06c9  Cggg T2e08Z T9e08P"
{
//initialise
fn=getTitle();
roiManager("reset");
run("Clear Results");
run("Remove Overlay");
run("Select None");
run("Colors...", "foreground=white background=black selection=white");
run("Set Measurements...", "area mean min centroid display redirect=None decimal=3");
getDimensions(ImageWidth, ImageHeight, ImageChannels, ImageSlices, ImageFrames);
getVoxelSize(px, py, pz, unit);
bd=bitDepth();

//estimate scalling factor  
sc=800/ImageWidth;
sch=800/ImageHeight;
if (sc<sch){
	sc=sch;
}
sc=round(sc*10)/10;

//check image type 
if (ImageSlices>1 || ImageFrames>1){
	exit("This macro does not work on time or Z series");
}

//line width default
BoxLineWidth=round(ImageWidth/100);
cols=newArray("White","Black","Red","Green","Blue","Magenta","Cyan","Yellow");

//find centre
CentreX=ImageWidth/2;
CentreY=ImageHeight/2;

//main options
Dialog.create("Movie Options");
Dialog.addMessage("## Zoom Region, Over-view and Path Options ##");
Dialog.addNumber("Number of images before zoom: ", 2);
Dialog.addNumber("Number of steps during zoom (more steps = smoother movie): ", 40);
Dialog.addMessage("## Final image frame dimensions currently are "+ImageWidth+300+" by "+ImageHeight+" pixels ##");
if (ImageWidth>1000 || ImageHeight>1000){
Dialog.addMessage("!!!! Image dimensions may be too large for AVI format - suggested scaling of: "+sc);	
}
Dialog.addNumber("Image scaling (values between 0 & 1 to reduce size)", 1);
pathtools=newArray("freeline","line","polyline","multipoint");
Dialog.addRadioButtonGroup("Path Creation Tool", pathtools, 1, 3, pathtools[0]);
Dialog.addNumber("Sampling factor for freeline/line (integers>1 to reduce movie length)",1);
Dialog.addCheckbox("Draw panning path on over-view image", false);
Dialog.addNumber("Width of over-view image (pixels)",300);
Dialog.addNumber("Thickness of box region on over-view image (pixels)",BoxLineWidth);
Dialog.addToSameRow();
Dialog.addChoice("Box Colour", cols);
Dialog.addNumber("Thickness of path line on over-view image (pixels)",floor(BoxLineWidth/3*2));
Dialog.addToSameRow();
Dialog.addChoice("Path Colour", cols);
posit=newArray("Top-Center","Center","Bottom-Center");
Dialog.addChoice("Over-view position in left panel", posit);
Dialog.addToSameRow();
Bkcol=newArray("Black","White");
Dialog.addChoice("Background Colour", Bkcol);
Dialog.addMessage("## Scale Bars ##");
Dialog.addCheckbox("Add a scale bar to the zoom image", true);
Dialog.setInsets(-25, 250, 0);
Dialog.addCheckbox("Add a scale bar to the Over-view image", true);
Dialog.addCheckbox("Fixed scale bar", false);
Dialog.setInsets(-20, 0, 0);
Dialog.addNumber("Initial length of scale bar in "+unit,floor(ImageWidth*px/5));
Dialog.addToSameRow();
Dialog.addChoice("Scale Bar Colour", cols);
Dialog.show(); 

//responses
preImages=Dialog.getNumber();
ZoomSteps=Dialog.getNumber();
scaling=Dialog.getNumber();
PathTool=Dialog.getRadioButton();
PathSampling=round(Dialog.getNumber());
DrawPath=Dialog.getCheckbox();
OverViewWidth=Dialog.getNumber();
BoxLineWidth=Dialog.getNumber();
BoxCol=Dialog.getChoice();
PathLineWidth=Dialog.getNumber();
PathCol=Dialog.getChoice();
ViewPosit=Dialog.getChoice();
Bkground=Dialog.getChoice();
AddScaleZoom=Dialog.getCheckbox();
AddScaleView=Dialog.getCheckbox();
ScaleLength=Dialog.getNumber();
barsizefixed=Dialog.getCheckbox();
ScaleCol=Dialog.getChoice();


//create an RGB copy
selectWindow(fn);
run("Select None");
run("Duplicate...", "title=TempView duplicate");
if (ImageChannels>1){
run("Flatten");
}
if (bd==8 || bd==16){
run("RGB Color");
rename("TempView");
}

//create initial roi
setTool("Rectangle");
selectWindow("TempView");
run("Specify...", "width="+ImageWidth/2+" height="+ImageHeight/2+" x=CentreX y=CentreY centered");
waitForUser("Rectangle","Edit/move Rectangle to Zoom Region");

//get size and location
getSelectionBounds(x, y, ZoomWidth, ZoomHeight);
run("Measure");
FinalCentreX=getResult("X",0)/px;
FinalCentreY=getResult("Y",0)/py;
selectWindow("Results");
run("Close");

//error check for roi
if (ZoomWidth/ZoomHeight!=ImageWidth/ImageHeight){
	ZoomWidth=ZoomHeight*ImageWidth/ImageHeight;
}

//get differences between start and finish of zoom
diffx=CentreX-FinalCentreX;
diffy=CentreY-FinalCentreY;
diffZoomWidth=ImageWidth-ZoomWidth;
diffZoomHeight=ImageHeight-ZoomHeight;

//create arrays for zoom steps
tempx=newArray(ZoomSteps);
tempy=newArray(ZoomSteps);
tempZoomWidth=newArray(ZoomSteps);
tempZoomHeight=newArray(ZoomSteps);

//create zoom rois
for (Zoom=0;Zoom<ZoomSteps;Zoom++){
tempx[Zoom]=CentreX-(diffx/(ZoomSteps-1)*Zoom);
tempy[Zoom]=CentreY-(diffy/(ZoomSteps-1)*Zoom);
tempZoomWidth[Zoom]=ImageWidth-(diffZoomWidth/(ZoomSteps-1)*Zoom);
tempZoomHeight[Zoom]=ImageHeight-(diffZoomHeight/(ZoomSteps-1)*Zoom);
run("Specify...", "width="+tempZoomWidth[Zoom]+" height="+tempZoomHeight[Zoom]+" x="+tempx[Zoom]+" y="+tempy[Zoom]+" centered");
roiManager("Add");	
}
n=roiManager("count");
roiManager("Show None");

//get last roi position
roiManager("Select", n-1);
getSelectionBounds(x, y, ZoomWidth, ZoomHeight);
run("Select None");

//draw panning path
setTool(PathTool);
waitForUser("","Draw Panning Path");
if (PathTool=="freeline"){
	run("Fit Spline");
}
if (PathTool=="line"){
	run("Interpolate", "interval=PathSampling smooth");
}
roiManager("Add");	
roiManager("Select", n);
getSelectionCoordinates(xpoints, ypoints);


//move start of line to centre of last roi
a=x+ZoomWidth/2-xpoints[0];
b=y+ZoomHeight/2-ypoints[0];
roiManager("Select", n);
roiManager("translate", a, b);
roiManager("deselect");
roiManager("Select", n);
getSelectionCoordinates(xpoints, ypoints);

//create pan rois
for (pan=1;pan<xpoints.length;pan+=PathSampling){
selectWindow("TempView");
makeRectangle(xpoints[pan]-(ZoomWidth/2), ypoints[pan]-(ZoomHeight/2),ZoomWidth,ZoomHeight);
roiManager("Add");
}
t=roiManager("count");

///////////////// create sequence //////////////////
setBatchMode("hide");

//create fisrt image
selectWindow("TempView");
run("Select None");
run("Duplicate...", "title=Zoom duplicate");
	run("Size...", "width="+ImageWidth*scaling+" height="+ImageHeight*scaling+" average interpolation=Bilinear");
	if (AddScaleZoom==true){
		AddScale();
	}
//get scale bar dimensions for over view image	
getVoxelSize(px1, py1,pz1, unit);
bar1=floor(ImageWidth*scaling*px1/5);
barHT1=round(ImageHeight*scaling/150);
barFT1=round(ImageHeight*scaling/30);

selectWindow("TempView");
run("Duplicate...", "title=View duplicate");
	run("Size...", "width=OverViewWidth constrain average interpolation=Bilinear");
	if	(AddScaleView==true){
		run("Scale Bar...", "width="+ScaleLength+" height="+barHT1+" font="+barFT1+" color="+ScaleCol+" background=None location=[Lower Right] bold");	
	}

//create pre images
for (before=0;before<preImages-1;before++){
	selectWindow("TempView");
	DUP();
	selectWindow("TempView");
	run("Select None");
	run("Duplicate...", "title=View2 duplicate");
	run("Size...", "width=OverViewWidth constrain average interpolation=Bilinear");
if	(AddScaleView==true){
	run("Scale Bar...", "width="+ScaleLength+" height="+barHT1+" font="+barFT1+" color="+ScaleCol+" background=None location=[Lower Right] bold");	
	}
	run("Concatenate...", "  title=View open image1=View image2=View2");
}

	
//create zoom and pan images
for (roi=0;roi<t;roi++){
	showProgress(roi,t);
	if (roi==n){
		roi=roi+1;
	}
	selectWindow("TempView");
	roiManager("Select",roi);
	getSelectionBounds(xn, yn, nWidth, nHeight);
	DUP();	
	selectWindow("TempView");
	run("Select None");
	DUP2();
}


//join zoom and view images
selectWindow("View");
getDimensions(viewWidth, viewHeight, viewChannels, viewSlices, viewFrames);
selectWindow("Zoom");
getDimensions(ZWidth, ZHeight, ZChannels, ZSlices, ZFrames);
borderheight=ZHeight;
	run("Colors...", "foreground=white background="+Bkground+" selection=white");
if (borderheight<viewHeight){
	borderheight=viewHeight;
	selectWindow("Zoom");
	run("Canvas Size...", "height="+borderheight+" position="+ViewPosit);
} else{
	selectWindow("View");
	run("Canvas Size...", "height="+borderheight+" position="+ViewPosit);
}
newImage("border", "RGB white", 4, borderheight, viewFrames);
run("Combine...", "stack1=View stack2=border");
rename("View");
run("Combine...", "stack1=View stack2=Zoom");
rename(fn+" Final movie");

setBatchMode("exit and display");


//finish up
run("Line Width...", "line=1");
run("Colors...", "foreground=white background=black selection=white");
setTool("line");
setTool("Rectangle");
selectWindow("TempView");
close();




/////// functions ///////////
//duplicate zoom/pan
function DUP(){
	run("Duplicate...", "title=[Im] duplicate");
	getDimensions(TempWidth, TempHeight, TempChannels, TempSlices, TempFrames);   
//check crop is not outseide image
if (TempWidth<ZoomWidth || TempHeight<ZoomHeight){

	if (yn+ZoomHeight>ImageHeight || xn+ZoomWidth>ImageWidth){
	type="Top-Left";
}
	if (xn<0 || yn<0){
	type="Bottom-Right";
}
	if (xn<0 && yn+ZoomHeight>ImageHeight){
	type="Top-Right";
}
	if (yn<0 && xn+ZoomWidth>ImageWidth){
	type="Bottom-Left";
}
	run("Canvas Size...", "width="+ZoomWidth+" height="+ZoomHeight+" position="+type);
}
	
	run("Size...", "width="+ImageWidth*scaling+" height="+ImageHeight*scaling+" average interpolation=Bilinear");
	if (AddScaleZoom==true){
	AddScale();
	}
	run("Concatenate...", "  title=Zoom open image1=Zoom image2=Im");	
}

//duplicate overview
function DUP2(){
	run("Duplicate...", "title=View2 duplicate");	
	if (DrawPath==true && roi>n+1){
	roiManager("select",n);
	run("Colors...", "foreground="+PathCol+" background=black selection=white");
	run("Line Width...", "line="+PathLineWidth);
	run("Draw", "slice");
	} 
	roiManager("Select",roi);
	run("Colors...", "foreground="+BoxCol+" background=black selection=white");
	run("Line Width...", "line="+BoxLineWidth);
	run("Draw", "slice"); 
	run("Select None"); 
	run("Size...", "width=OverViewWidth constrain average interpolation=Bilinear");
if	(AddScaleView==true){
	run("Scale Bar...", "width="+ScaleLength+" height="+barHT1+" font="+barFT1+" color="+ScaleCol+" background=None location=[Lower Right] bold");	
	}
	run("Concatenate...", "  title=View open image1=View image2=View2");	
}

//add sacle bar to zoom
function AddScale(){
	getVoxelSize(barpx, barpy, barpz, unit);
if (barsizefixed==true){
	bar=floor(ScaleLength*scaling);
}else{
	bar=floor(ScaleLength*scaling*(barpx/px));
	}
	barHT=round(ImageHeight*scaling/150);
	barFT=round(ImageHeight*scaling/30);
	run("Scale Bar...", "width="+bar+" height="+barHT+" font="+barFT+" color="+ScaleCol+" background=None location=[Lower Right] bold");
}

//progress bar function
function getBar(p1, p2){
   n = 25;
   bar1 = "-------------------------";
   bar2 = "*************************";
   index = round(n*(p1/p2));
if (index<1) index = 1;
if (index>n-1) index = n-1;
return substring(bar2, 0, index) + substring(bar1, index+1, n);
}

}



//**************************************14

macro "Set one image/stack for a stack/time series (v2.3) Action Tool - Cg00 L0141 L0444 L0747 L0a4a L0d4d L0g4g   C00g L61a1 L64a4 L67a7 L6aaa L6dad L6gag C000 Lc8g8" 
{

setBackgroundColor(0, 0, 0);

fn=getTitle();

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

if (slices==1 && frames==1) {
	exit("Image is not a multichannel z-stack or time series");
}

title = "Get info";
msg = "Before you start you will either need to know:\n \n   - the channel you want changed \n   - the z-slice you want to copy \n   - the time point you want to copy \n \nor \n \nyou can select now the required channel, slice and frame on the image \n \n then select OK to continue";
waitForUser(title, msg);


selectWindow(fn); 
rename("temp");

Stack.getPosition(channel, slice, frame)
a=channel;
b=slice;
c=frame;

all="";
for (i=1; i<=channels; i++)
{
noc="c"+i+"=C"+i+"-temp ";
all=all + noc;
}
all= all + " create";

//input channel and slice info

Dialog.create("Select");
  Dialog.addMessage("Channel editing options");
  todo = newArray("Copy a single slice into a Z stack", "Clear all but one slice in a Z stack", 
  "Copy a Z stack into time series", "Copy a single slice into a Z stack in a time series" );
  Dialog.addRadioButtonGroup("What do you want to do?", todo, 4, 2, "Copy a single slice into a Z stack");
  Dialog.addMessage("Now enter channel number and  the Z-slice or the timepoint");
  Dialog.addNumber("Which channel", a, 0, 1,"" );
  Dialog.addNumber("Which Slice", b, 0, 1,"" );
  Dialog.addNumber("Which timepoint", c, 0, 1,"" );
Dialog.show;
  
op = Dialog.getRadioButton(); 
CH = Dialog.getNumber(); 
zsl = Dialog.getNumber();
frm = Dialog.getNumber();
//error checking
if (CH>channels) {exit ("Channel does not exist");}
else if (zsl>slices)  {exit("Z Slice does not exist");}
else if (frm>frames)  {exit("Time point does not exist");}

run("Split Channels");

if (op == "Copy a single slice into a Z stack" )
{
setBatchMode(true);
Ch_z_stack();
setBatchMode("exit and display");
}
else if (op == "Copy a Z stack into time series")
{
setBatchMode(true);
Ch_t_series();
setBatchMode("exit and display");
}
else if (op == "Copy a single slice into a Z stack in a time series")
{
setBatchMode(true);
Ch_zt_series();
setBatchMode("exit and display");
}
else if (op == "Clear all but one slice in a Z stack")
{
setBatchMode(true);
single_slice();
setBatchMode("exit and display");
}

function Ch_z_stack()
{
//select source image
selectWindow("C" + CH + "-temp");
run("Duplicate...", "title=Slice duplicate range=zsl");
run("Copy");
//copy image to destination
selectWindow("C" + CH + "-temp");
for (z=1; z<=slices; z++)
{
Stack.setSlice(z);
run("Paste");
}
}


function Ch_t_series()
{
//select source s

selectWindow("C" + CH + "-temp");
run("Duplicate...", "title=Slice duplicate slices=1-slices frames=fn");

setBatchMode(true);

//copy images to destination
for (f=1; f<=frames; f++)
{
for (z=1; z<=slices; z++)
{
selectWindow("Slice");
Stack.setFrame(f);
Stack.setSlice(z);
run("Copy");
selectWindow("C" + CH + "-temp");
Stack.setFrame(f);
Stack.setSlice(z);
run("Paste");
}
}

}

function Ch_zt_series()
{
//select source s
selectWindow("C" + CH + "-temp");
run("Duplicate...", "title=Slice duplicate slices=zsl frames=fn");
selectWindow("Slice");
run("Copy");

selectWindow("C" + CH + "-temp");
//copy images to destination
for (f=1; f<=frames; f++)
{
for (z=1; z<=slices; z++)
{
Stack.setFrame(f);
Stack.setSlice(z);
run("Paste");
}
}
}

function single_slice()
{
//select source image
selectWindow("C" + CH + "-temp");
run("Duplicate...", "title=Slice duplicate range=zsl");
run("Copy");
//copy image to destination
selectWindow("C" + CH + "-temp");
//setTool("rectangle");
makeRectangle(0, 0, width, height);
run("Clear", "stack");
Stack.setSlice(zsl);
run("Paste");
}


//tidy up
selectWindow("Slice");
close();
run("Merge Channels...",all);
g= "New " + fn;
rename("New " + fn);
}




