% function to break the rs_codeby trying all seeds seedmax

function break_rs(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 1000 characters
short_text=input_text;
short_text=input_text(1:100);

for seed=1:seedmax
seed;
rng('default');
rng(seed);
new_text=short_text;
for k=1:length(new_text)
letter=new_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);
% test text by counting common words
%total_words(seed)=count_common_words(word_list,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

% figure; hold on; grid on;
% title('Number of common words found in kth shift');
% plot([1:seedmax],total_words);
% [m,best_seed]=max(total_words);
%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)

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