function trial_data = VectorMean(trial_data,parameter,presented_items,targets)

%    This file is part of VectorMean.
%
%   VectorMean is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    VectorMean is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with VectorMean.  If not, see
%    <http://www.gnu.org/licenses/>.

%% Converts population vector into a single vector mean
%

% Setting up polar values
polarC = [1:parameter.type_size]';
polarC = (polarC * 6.28/parameter.type_size) - 6.28/parameter.type_size;
polarC(:,2) = trial_data.representation;

% Summing cartesian values
[X Y] = pol2cart(polarC(:,1),polarC(:,2));
x_value_sum = sum(X);
y_value_sum = sum(Y);

% Here are the two proporties of the retrieved mean vector.
[retrieved_location retrieved_length] = cart2pol(x_value_sum,y_value_sum);

if retrieved_location < 0
    retrieved_location = retrieved_location + 6.28;
end

% If the model could not accurately retrieve a token, then the retrieved
% color is random.
if trial_data.not_guess == 0
   retrieved_location = deg2rad(randi(parameter.sensory_space)); 
end

nontarget_radians = deg2rad(presented_items(trial_data.nontoken));
target_radians = deg2rad(presented_items(trial_data.token));

deviation = retrieved_location - target_radians;

raw_deviation = deviation;

%deviation between target and retrieved from -pi to pi
if raw_deviation < -pi
    raw_deviation = raw_deviation + 2*pi;
end

if raw_deviation > pi
    raw_deviation = raw_deviation - 2*pi;
end

%Relative deviation between target and retrieved from 0 to pi
if deviation < 0
    deviation = deviation + 2*pi;
end

%reflects the value over the 0 axis to make the result symmetrical
if  deviation > pi
    deviation = 2*pi - deviation;
end

trial_data.raw_deviation = raw_deviation;
trial_data.retrieved_location = retrieved_location;
trial_data.nontarget_radians = nontarget_radians;
trial_data.target_radians = target_radians;
trial_data.retrieved_length = retrieved_length;
trial_data.deviation = deviation;
trial_data.presented_items = presented_items;
trial_data.targets = targets;

% If the model could not accurately retrieve a color, then the retrieved
% length is set to a small value. 
if trial_data.not_guess == 0
    trial_data.retrieved_length = .01;
end


end

