% function to read in a  file that is a differenc
% of two  English plain texts (27 characters) and 
% and a string. It uses the string as a guess for 
% the second text in all possible positions and 
% reports the best position based on pair matching.

function   test_word(filename,word)
   % read in file to be encrypted/decrypted
   fileID=fopen(filename);
   input_text=fread(fileID)';
   fclose(fileID);
   cypher=input_text(1:1000);
   text1=input_text(1001:2000);
   text2=input_text(2001:3000);
   t1=char(text1);
   t2=char(text2);
   % throw away all entries  excepts letters and spaces
   % convert all letters to uppercase
   counter=0;
   for k=1:length(word)
       letter=word(k);
       if letter ==32
           counter=counter+1;
           word2(counter)=91;
       elseif (65<=letter)&&(letter<=90)
           counter=counter+1;
           word2(counter)=letter;
       elseif (97<=letter)&&(letter<=122)
           counter=counter+1;
           word2(counter)=letter-32;
       end
   end
   matrix=pair_freq('ppall.txt');
   for k=1:length(cypher)-length(word2)
       for j=1:length(word2)
           word3(j)= mod((cypher(k+j)-65)+(word2(j)-65),27);
       end
         total(k)=count_pairs(matrix, word3+1);
   end
   figure
   hold on
   title('Plot of COUNT-PAIR score for different positions');
   plot(total)

   [m,pos]=sort(total,'descend');

   t=[20:-1:1];
   for k=t
       best_pos=pos(k);
       for j=1:length(word2)
           word4(k,j)= mod((input_text(best_pos+j)-65)+(word2(j)-65),27);
       end
      end
   [t',pos(t)']
   char(word4(t,:)+65)
   % cheat
   t1
   t2
   char(word2)

   list=strfind(t2,word2)
   for k=1:length(list)
       char(t1(list(k):list(k)+length(word)))
       char(t2(list(k):list(k)+length(word)))
   end
   return


