% function to break the Caesar code by trying all possible shifts

function break_caesar2(filename)
% read in the encrypted file
fileID=fopen(filename);
input_text=fread(fileID)';
fclose(fileID);
% try all 26 possible shifts
clear total_words;
clear total_pairs;
word_list=words;
matrix=pair_freq('ppall.txt');
for shift=1:26
new_text = input_text;
for k=1:length(new_text)
letter=new_text(k);
if (65 <= letter)&&(letter <= 90)
new_text(k) = 65+mod(shift+letter-65,26);
end % end if
end % for k
char(new_text);
% test text by counting common words
total_words(shift)=count_common_words(word_list,new_text);
% text text by counting common pairs
simple_text=simplify_text(new_text);
total_pairs(shift)=count_pairs(matrix,simple_text);
end % for shift

figure; hold on; grid on;
title('Number of common words found in kth shift');
plot([1:26],total_words);
[m,best_shift]=max(total_words);
for k=1:length(input_text)
letter=input_text(k);
if (65 <= letter)&&(letter <= 90)
new_text(k) = 65+mod(best_shift+letter-65,26);
end % end if
end % for k

char(new_text(1:100))
figure; hold on; grid on;
title('Score using 2-gram counts');
plot([1:26],total_pairs);
[m,best_shift]=max(total_pairs);
for k=1:length(input_text)
letter=input_text(k);
if (65 <= letter)&&(letter <= 90)
new_text(k) = 65+mod(best_shift+letter-65,26);
end % end if
end % for k
char(new_text(1:100))

return