function varargout = getVoxelSizeFromString(varargin)
% function varargout = getVoxelsizeFromString(varargin)
% 
% Description:
% Given a string, typically a directory- or filename return
% a vector containing the voxel size as given in the string
%
% Author: Johann Strasser
% Date: 071105

str = [];
voxelSize = [];

if length(varargin)>1
    for i = 1:2:length(varargin)
        switch(lower(varargin{i}))
            case 'string'
                str = varargin{i + 1};
            otherwise
                error(['Unknown parameer name passed to ', mfilename, '.  Name was ' varargin{i}]);
        end
    end
end

if isempty(str)
    %     str = '825gfp32_140806_1724_ed_128x128x128_x1p00y1p00z1p00'; %cop, pop and con
    %     str = '825gfp32_140806_1724_ed_128x128x128_x1y1z1';
    % Test error cases
    %     str = '825gfp32_140806_1724_ed_128x128x128_x1p00y1p00z1p00_825gfp32_140806_1724_ed_128x128x128_x1p00y1p00z1p00';
    %     str = '825gfp32_140806_1724_ed_128x128x128_x1p00y1p00';
    error([mfilename, ':  String to be searched is empty.']);
end

% Regular expression to find x, y and z voxel dimension substrings
% (?:blabla) The ?: tells the engine not to create a backreference
resExp = 'x(\d+(?:p\d+)?)y(\d+(?:p\d+)?)z(\d+(?:p\d+)?)';
[startIndices, endIndices, tokenExtents, matches, tokens, names] = regexp(str, resExp);

found = 0;

if length(matches) == 1
    voxelSizeString = matches{1};
    % Now replace p by . if p exists at all and assign to vector
    tokensMatch1 = tokens{1, 1};
    xStr = tokensMatch1{1};
    xStr = regexprep(xStr, 'p', '.');
    voxelSize(1) = str2num(char(xStr));

    yStr = tokensMatch1{2};
    yStr = regexprep(yStr, 'p', '.');
    voxelSize(2) = str2num(char(yStr));

    zStr = tokensMatch1{3};
    zStr = regexprep(zStr, 'p', '.');
    voxelSize(3) = str2num(char(zStr));
    found = 1;
elseif length(matches) == 0
    warning([mfilename, ': Voxel size substring not found. Returning default voxel size.']);
    voxelSize = [1, 1, 1];
    voxelSizeString = 'x1p00y1p00z1p00';
else
    error([mfilename, ': Voxel size substring found multiple times.']);
end

disp(sprintf('%s:  VoxelSize(µm): %s', mfilename, mat2str(voxelSize)));
varargout{1} = voxelSize;
varargout{2} = found;
varargout{3} = voxelSizeString;