function newVesicles3D = fGetATTO(filteredVesicles3D)
%V1. This function loads the Atto-file, fits the vesicles within it and
%converts the values to the vesicle diameter, appending it to the original
%vesicles3D structure.

global PARAM;

%cropping size
MCrop=10;
NCrop=10;

% defining regexp to search atto file
attoRegExp = '.*atto.*';

files = dir(PARAM.folder);
pathname = PARAM.folder;
attoFile = '';
% iterating over all files in the folder and stop if atto file is found
for i = 1:length(files)
   if regexpi(files(i).name, attoRegExp) ~= 0
       attoFile = files(i).name;
       break
   end
end

% if atto file isn't found, replaces diameters by 1
if isempty(attoFile) == true
    fprintf('Atto-file is not found, unities replaced vesicles diameters \n');
    [filteredVesicles3D(:).diameter] = deal(1);
    newVesicles3D = filteredVesicles3D;
    return
end

fprintf('File %s used as Atto-file for size determination \n', attoFile);

% loading and cropping atto image
attoImg = imread(strcat(pathname, '\', attoFile));  
M = size(attoImg, 1); N = size(attoImg, 2);
attoImg = attoImg((MCrop+1):(M-MCrop),(NCrop+1):(N-NCrop));

% duplicating 1D- atto vesicles structure and deleting all fields, except 'date','experiment', 'id', 'm', 'n'
attoVesicles = filteredVesicles3D(1:end,1,1);
fields = fieldnames(attoVesicles);
fieldsToDelete = fields(~ismember(fields, {'date','experiment', 'id', 'm', 'n'}));
attoVesicles = rmfield(attoVesicles, fieldsToDelete);

% fitting atto vesicles to 2D-Gaussian
[fittedAttoImg, attoVesicles] = fGauss2DFit(attoImg, attoVesicles);

% converting peak volumes to vesicle diameters from calibration parameters
vol = 2 .* pi .* [attoVesicles(:).a] .* [attoVesicles(:).sx] .* [attoVesicles(:).sy];
diameter = num2cell(PARAM.atto(1) + PARAM.atto(2).*vol .* PARAM.atto(3)); % PARAM.atto(3) - correction factor
[attoVesicles(:).diameter] = diameter{:};

% writing vesicles diameter field to initial 3D vesicles strucutre.
attoVesicles3D = repmat(attoVesicles, 1, size(filteredVesicles3D, 2), size(filteredVesicles3D, 3));
[filteredVesicles3D(:).diameter] = attoVesicles3D(:).diameter;
newVesicles3D = filteredVesicles3D;
