function sorted = volumes(slices,num,sorted)
%this recursive function enables to sort the separate slices into uniform volume sets to enable 
%further processing

%slices . . . a structure containing respectively: path to a DICOM file as a string; voxel size as a vector [1x3]; global z-coordinate 
%       . . . e.g. {1x3} cell array :   ['path/to/image.dcm'], [1.2 1.2 4.5], [222.33] 
%num . . . initialization number, moves the position in the output cell

%sorted . . . is a cell array of sorted uniform volume sets when at the end of the recursive process, each step of recursion, a new volume is stored
%       . . . for initialization use empty cell {}
S = size(slices)
slicesNew=slices;
% The information from the slices is loaded and the minimum global z-coordinate(=MIN) is found
if S(1)>0
    loc= cell2mat(slices(:,3));
    [start,pos] = min(loc);
    gap(num,:)=slices{pos,2};
    loc = (round((loc-start)*10)/10)/gap(num,3);
k=1;  index=[]; 
%The information of MIN is compared: voxel size and the uniformity of the possible grid
%If a slice does not belong to this volume, its index is kept to be processed in another loop 
for i=1:S(1)
    if (sum(slices{i,2}==gap(num,:))==3) && (rem(loc(i)+1,floor(loc(i))+1)==0)
        vol(k,1:3) = slices(i,1:3);
       k =k+1;
    else  index=[index; i];
    end
end
%The volume set is additionally tested for its size and completion
sVol = size(vol);
if sVol(1)<4
    num = num-1;
end
slicesNew=slices(index,:);
[~,ind] = sort(cell2mat(vol(:,3)));
if ((vol{ind(end),3}-vol{ind(1),3})/gap(num,3)) == (sVol(1)-1)
    sorted{num}=vol(ind,:);
    else num = num-1;
end
%The recursion goes until all slices have been sorted
sorted = volumes(slicesNew,num+1,sorted);
end
end
