
first = 1;
last = 256;

inputs = D;
inputs = double(inputs);
b=1;
inputs=inputs(:,b);

% predict the SubBytes output: SubBytes(XOR(key,data))

disp('Predicting intermediate values ...');
[m,n] = size(traces);

key = [0:255];
after_sbox = zeros(m,256);

for i=1:m
    after_sbox(i,:) = SubBytes(bitxor(inputs(i),key)+1);
end


key_trace = zeros(256,n);
   
    % predict the power consumption

    disp('Predicting the instantaneous power consumption ...');
    power_consumption = bitget(after_sbox,1);
    
    % correlate the predicted power consumption with the real power 
    % consumption
    disp('Generating the difference traces ...');

    for i=first:last

        key_trace(i,:) = sum(traces(find(power_consumption(:,i)==1),:)) - sum(traces(find(power_consumption(:,i)==0),:));

    end
	

