%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Copyright: 2010 Integrated Sytems Laboratory, ETH Zurich
%% http://www.iis.ee.ethz.ch/~sha3
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function S = Step(S, W, phi, r, s, i)
temp = zeros(1,4);
P = zeros(1,4);
perm = [1 0 3 2; 2 3 0 1 ; 3 2 1 0]+1;
% fprintf(['i = %2i, ' phi(1:2) ', r = %2i, s = %2i, Perm = [%i %i %i %i]\n'], i, r, s, perm(mod(i, 3)+1, :)-1);
if phi(1:2) == 'IF',
P(1) = bitor(bitand(S(1,1), S(1,2)), bitand(bitcmp(S(1,1), 32), S(1,3)));
P(2) = bitor(bitand(S(2,1), S(2,2)), bitand(bitcmp(S(2,1), 32), S(2,3)));
P(3) = bitor(bitand(S(3,1), S(3,2)), bitand(bitcmp(S(3,1), 32), S(3,3)));
P(4) = bitor(bitand(S(4,1), S(4,2)), bitand(bitcmp(S(4,1), 32), S(4,3)));
elseif phi == 'MAJ',
P(1) = bitor(bitand(S(1,3), S(1,2)), bitand(bitor(S(1,3), S(1,2)), S(1,1)));
P(2) = bitor(bitand(S(2,3), S(2,2)), bitand(bitor(S(2,3), S(2,2)), S(2,1)));
P(3) = bitor(bitand(S(3,3), S(3,2)), bitand(bitor(S(3,3), S(3,2)), S(3,1)));
P(4) = bitor(bitand(S(4,3), S(4,2)), bitand(bitor(S(4,3), S(4,2)), S(4,1)));
else
dips('ERROR, invalid phi')
end
S(1,1) = bitrot(S(1,1), r);
S(2,1) = bitrot(S(2,1), r);
S(3,1) = bitrot(S(3,1), r);
S(4,1) = bitrot(S(4,1), r);
S(1,4) = mod(S(1,4) + W(1) + P(1), 2^32);
S(2,4) = mod(S(2,4) + W(2) + P(2), 2^32);
S(3,4) = mod(S(3,4) + W(3) + P(3), 2^32);
S(4,4) = mod(S(4,4) + W(4) + P(4), 2^32);
S(1,4) = bitrot(S(1,4), s);
S(2,4) = bitrot(S(2,4), s);
S(3,4) = bitrot(S(3,4), s);
S(4,4) = bitrot(S(4,4), s);
temp(1) = mod(S(1,4) + S(perm(mod(i, 3)+1, 1),1), 2^32);
temp(2) = mod(S(2,4) + S(perm(mod(i, 3)+1, 2),1), 2^32);
temp(3) = mod(S(3,4) + S(perm(mod(i, 3)+1, 3),1), 2^32);
temp(4) = mod(S(4,4) + S(perm(mod(i, 3)+1, 4),1), 2^32);
% Swap
S(1,4) = S(1,3);
S(2,4) = S(2,3);
S(3,4) = S(3,3);
S(4,4) = S(4,3);
S(1,3) = S(1,2);
S(2,3) = S(2,2);
S(3,3) = S(3,2);
S(4,3) = S(4,2);
S(1,2) = S(1,1);
S(2,2) = S(2,1);
S(3,2) = S(3,1);
S(4,2) = S(4,1);
S(1,1) = temp(1);
S(2,1) = temp(2);
S(3,1) = temp(3);
S(4,1) = temp(4);