
%Script for MitoSholl Analysis
%Lorena Arancibia 01/02/2017

clear all

%Define XY and Z resolution
xyresolution=0.62517;
zresolution=1;

%Define Soma radius:
Soma = 5;
%Define Sholl Radius:
SR = 2;
%Define Max Radius
MR=1000;
%Sholl Radii
edges=[Soma:SR:MR];


%Create results table (columns: Sholl Rdius, Branches, Terminals,
%Intersections)
Results = [edges' zeros(length(edges),1)];

rootpath = '/Users/GeorginaKontou/Documents/MATLAB/mitosholl/new mitosholl';
files    = dir([rootpath '/*.tif']);
cfiles   =  dir([rootpath '/*.csv']);
mkdir(rootpath, sprintf('%d', SR));
fpath = fullfile(rootpath, sprintf('%d', SR));

for a=1:length(files);

    % Define Centre
    Centre = csvread([rootpath '/' cfiles(a).name],1,1);
   
    
    % import image frame data
    info=imfinfo([rootpath '/' files(a).name]);
    
    %create NAN matrix for Distances
    Dist= NaN([(info(1).Width)^2 length(info)]);
    % to set frame write number at frm = x
    for frm = 1:1:length(info);
        C(:,:,frm) = imread([rootpath '/' files(a).name],'Index',frm);
    end
  for frm = 1:1:length(info);
        [y x]=find(C(:,:,frm));
        f=frm*ones(length(x),1);
        Coord=[x y f];
        CoordUM=bsxfun(@times,Coord,[xyresolution xyresolution zresolution]);
            
        % Create a column calculating the distance from centre
        d = bsxfun(@minus, CoordUM(:,1:3), Centre(1,1:3));
        [r ~]=size(d);
        Dist(1:r ,frm) = sqrt(sum(d.^2 ,2));
      
        clearvars Coord CoordUM d
  end
  
        %Find pixels within each Sholl Radius
        Results(2:end,2) = histcounts(Dist, edges);
        %Save results in tab delimited file
        idx = strfind(files(a).name, '.tif'); %find .tif in filename
        
        newfile=sprintf('%s%s',files(a).name(1:idx-1),'.dat');
        
        fid=fopen(fullfile(fpath,newfile),'w');
        fprintf(fid, '%s\t%s\n','SR','Mito');
        dlmwrite(fullfile(fpath,newfile), Results, 'delimiter','\t', '-append');
        fclose('all');
        %clear variants before next loop
        clearvars C
        
        end
 
        