% function to break the rs_codeby trying all seeds seedmax
% This is a faster version that only uses letter pairs test
% and just checks a short initial segment of text

function break_rs2(filename,seedmax)
tic;
% read in the encrypted file
fileID=fopen(filename);
input_text=fread(fileID)';
fclose(fileID);
% try all seeds up to seedmax
clear total_words;
clear total_pairs;
word_list=words;
matrix=pair_freq('ppall.txt');

% to speed up code, just look at 100 characters
text_length=100;
short_text=input_text;
short_text=input_text(1:text_length);

% Try all seeds up to seedmax and check how close
% decrypts are to looking like English
for seed=1:seedmax
seed;
%rng('default');
rng(seed);
shifts=randi(26,1,text_length);
new_text=short_text;
new_text=65+mod(-shifts+new_text-65,26);
char(new_text);
% text text by counting common pairs
simple_text=simplify_text(new_text);
total_pairs(seed)=count_pairs(matrix,simple_text);
end % for seed

% Plot the result and display decoded message
figure; hold on; grid on;
title('Matrix sum for common letter pairs');
plot([1:seedmax],total_pairs);
[m,best_seed]=max(total_pairs);
rng('default');
rng(best_seed);
for k=1:length(input_text)
letter=input_text(k);
if (65 <= letter)&&(letter <= 90)
new_text(k) = 65+mod(-randi(26)+letter-65,26);
end % end if
end % for k
char(new_text)

toc
return