function data = spOneStep(data)

%% Data in from last step

% This data is constant
m = data.m; % number of grid lines in x-direction
n = data.n; % number of grid lines in y-direction
b = data.b; % rotation coefficient
a = data.a; % bottom friction coefficient
mu = data.mu; % eddy viscocity
dt = data.dt; % time step
%dx = data.dx;

m1 = data.m1; % matrices of masses
m2 = data.m2; 
M = data.M;

% This data is changed
X = data.X; % matrix of x-coordinate values
Y = data.Y; % matrix of y-coordinate values
u = data.u; % matrix of x-components of velocity
v = data.v; % matrix of y-components of velocity


%% Calculate properties along edges of triangles
% positions differences

DxX1(1:m,1:2:n-1)=X(2:m+1,1:2:n-1)-X(1:m,1:2:n-1);
DxY1(1:m,1:2:n-1)=Y(2:m+1,1:2:n-1)-Y(1:m,1:2:n-1);
DxX1(1:m,2:2:n)=X(2:m+1,3:2:n+1)-X(1:m,3:2:n+1);
DxY1(1:m,2:2:n)=Y(2:m+1,3:2:n+1)-Y(1:m,3:2:n+1);

DxX2(1:m,1:2:n-1)=X(2:m+1,2:2:n)-X(1:m,2:2:n);
DxY2(1:m,1:2:n-1)=Y(2:m+1,2:2:n)-Y(1:m,2:2:n);
DxX2(1:m,2:2:n)=X(2:m+1,2:2:n)-X(1:m,2:2:n);
DxY2(1:m,2:2:n)=Y(2:m+1,2:2:n)-Y(1:m,2:2:n);

DyX1(2:2:m,1:n)=X(2:2:m,2:n+1)-X(2:2:m,1:n);
DyY1(2:2:m,1:n)=Y(2:2:m,2:n+1)-Y(2:2:m,1:n);
DyX1(1:2:m-1,1:n)=X(2:2:m,2:n+1)-X(2:2:m,1:n);
DyY1(1:2:m-1,1:n)=Y(2:2:m,2:n+1)-Y(2:2:m,1:n);

DyX2(1:2:m-1,1:n)=X(1:2:m-1,2:n+1)-X(1:2:m-1,1:n);
DyY2(1:2:m-1,1:n)=Y(1:2:m-1,2:n+1)-Y(1:2:m-1,1:n);

DyX2(2:2:m,1:n)=X(3:2:m+1,2:n+1)-X(3:2:m+1,1:n);
DyY2(2:2:m,1:n)=Y(3:2:m+1,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+1,:)-(V2uyy(2:2:m,:)-V2dyy(2:2:m,:));

VVy(2:2:m,:)=VVy(2:2:m,:)-(V1uyy(2:2:m,:)-V1dyy(2:2:m,:));
VVy(2:2:m,:)=VVy(2:2:m,:)-(V1uyy(1:2:m-1,:)-V1dyy(1:2:m-1,:));

% this concludes viscous stress computation

%%  Computation of x and y Forces

Fx=PPx+VVx;
Fy=PPy+VVy;


% this concludes the force computation

%%  Velocity update

u=(1-a*dt)*u+(Fx./M-dt*(X-b*v));
v=(1-a*dt)*v+(Fy./M-dt*(Y+b*u));


%% Leap Frog

X=X+dt*u;
Y=Y+dt*v;


%% Store data to pass to next step
%update some data
A1=(DxX1.*DyY1-DyX1.*DxY1)/2;
A2=(DxX2.*DyY2-DyX2.*DxY2)/2;


%  only store data that has been changed
data.X = X; % matrix of x-coordinate values
data.Y = Y; % matrix of y-coordinate values
data.u = u; % matrix of x-components of velocity
data.v = v; % matrix of y-components of velocity

data.A1 = A1;
data.A2 = A2;

% This data is stored for plotting - DEPRECATED FOR NOW
%SS = s1.*s1+T1.*T1+s2.^2 +T2.^2;
%data.SS1_1 = max(max(SS));
%data.SS1_2 = max(max(max(A1)),max(max(A2)))/dx/dx;
%data.SS1_3 = min(min(A2))/dx/dx;

end
