% 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.

% This version takes a filename as an argument, and 
% reads in the string as keyboard input


function   test_word(filename)
   % 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);
   decrypt1=46*ones(1,length(cypher));
   decrypt2=46*ones(1,length(cypher));
   char(decrypt1)
   char(decrypt2)
   % create matrix to use in count_pairs test
   matrix=pair_freq('ppall.txt');
   % throw away all entries  excepts letters and spaces
   % convert all letters to uppercase
   flag=0;
   while flag==0
       clear word;
       clear word2;
       clear word3;
       clear word4;
       clear word5;
       word=input('input word to test in quotes (enter 0 to exit): ');
       if word == 0
            return
       end
       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
      clear total;
      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=[1:9];
      for k=t
          best_pos=pos(k);
          for j=1:length(word2)
              word5(k,1)=48+k;
              word5(k,2)=32;
              word5(k,3)=32;
              word5(k,j+3)=65+mod((input_text(best_pos+j)-65)+(word2(j)-65),27);
              word4(k,j)=65+mod((input_text(best_pos+j)-65)+(word2(j)-65),27);
          end
      end
      char(word5)
      yesno=input('Which one to accept (none = 0)? ');
      if yesno>0  % update decrypt
          yesno
          bp=pos(yesno)
          char(word2)
          char(word4(1,:))
          length(word2)
          decrypt1(bp:bp+length(word2)-1)=word4(yesno,:) ;
          decrypt2(bp:bp+length(word2)-1)=word2 ;
          char(decrypt1)
          %t1
          char(decrypt2)
          %t2
      end
      % 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
   end % while
   return 
