
% function to decrypt by using letter frequencies and then allow 
% manual correction

function  set_letters(filename)
   % read in file
   base_freq=letter_freq('ppall.txt');
   text_freq=letter_freq(filename);
   list=sortrows([text_freq,base_freq]);
   perm=list(:,2);
 
   % read in the encrypted file
   fileID=fopen(filename);
   input_text=fread(fileID)';
   fclose(fileID); 
   letters={'A','B','C','D','E','F','G','H','I','J','K','L',...
       'M','N','O','P','Q','R', 'S','T','U','V','W','X','Y','Z','_'};
   letters='abcdefghijklmnopqrstuvwxyz_';
   input_text(1:20)
   text=simplify_text(input_text);
   plain=letters(perm(text));
   plain(1:200)
   
   flag=0;
   while flag==0
    letter1=input('replace this letter: ','s');
    if double(letter1)<96
        break;
    end
    letter2=input('by this letter: ','s');
    a=double(letter1)-96;
    b=double(letter2)-96;
    c=find(perm==a)
    d=find(perm==b);
    perm(c)=b;
    perm(d)=a;
    plain=letters(perm(text));
    plain(1:200)
   end
   [plain(1:100);   plain(101:200);   plain(201:300); ...
     plain(301:400);   plain(401:500);plain(501:600);...
     plain(601:700);plain(701:800); plain(801:900);plain(901:1000)]
return
