function [fittedFrames, vesiclesFrames] = fGauss2DFitFrames(frames, vesicles, timeStamps)
% V3. Parallel. This function fits all time frames on both channels in 'frames'
% according to the vesicles coordinates in 'vesicles'. It returns fitted 4D-image
% and two 3D-vesicles structure (Vesicle x Channel x timeframe) with appended time stamps for each channel.
% It also calculates and attaches the intensity ratio to each channel
% vesicle
global PARAM;

if size(frames, 4) > length(timeStamps)
    error('number of image time frames is bigger than number of time stamps'); 
end

% prepares arrays for storing the data
fittedFrames = zeros(size(frames), 'uint16');
vesiclesFrames = [];

% clears already fitted columns in vesicles 
emptyVesicles = vesicles;
[emptyVesicles(:).x0, emptyVesicles(:).y0, emptyVesicles(:).sx,...
    emptyVesicles(:).sy, emptyVesicles(:).a, emptyVesicles(:).b,...
    emptyVesicles(:).r2, emptyVesicles(:).pointerror, emptyVesicles(:).timestamp,...
    emptyVesicles(:).ratio] = deal([]);

% replicate the vesicles structures two times in 2nd dimension and in 3d dimension for each time frame
vesiclesFrames = repmat(emptyVesicles, 1, 2, size(frames, 4));   

% passes the global PARAM to each pool worker 
paralPARAM = parallel.pool.Constant(PARAM);

% fitting vesicles on each time frame, first on the 1st, then on 2nd
% channel. Surprisingly, two parfor loops run faster than one...
parfor i = 1:size(frames, 4)   
    [fittedFrames(:,:,1,i), vesiclesFrames(:,1,i)] = fGauss2DFit(frames(:,:,1,i), vesiclesFrames(:,1,i), paralPARAM.Value);
end
parfor i = 1:size(frames, 4)
    [fittedFrames(:,:,2,i), vesiclesFrames(:,2,i)] = fGauss2DFit(frames(:,:,2,i), vesiclesFrames(:,2,i), paralPARAM.Value);
end

% attaching time stamp for each vesicle on each frame
vesiclesTimeStamps = num2cell(repmat(timeStamps', length(vesicles), 1)); % transposing and NoVesicles duplicating timestamps
[vesiclesFrames(:,1,:).timestamp] = vesiclesTimeStamps{:};
[vesiclesFrames(:,2,:).timestamp] = vesiclesTimeStamps{:};

% calculating and attaching intensity ratio 470/410 nm to the structure
vol1 = 2 .* pi .* [vesiclesFrames(:,1,:).a] .* [vesiclesFrames(:,1,:).sx] .* [vesiclesFrames(:,1,:).sy];
vol2 = 2 .* pi .* [vesiclesFrames(:,2,:).a] .* [vesiclesFrames(:,2,:).sx] .* [vesiclesFrames(:,2,:).sy];
ratio = num2cell(vol1 ./ vol2);
[vesiclesFrames(:,1,:).ratio] = ratio{:};
[vesiclesFrames(:,2,:).ratio] = ratio{:};

