eval('correspondance');
load('bigramenglish');

%% 2.a Matrice de transitions
mostProbableNext = '';
for i = 1 : 26
    [a, m] = max(matrice_trans(i+1,:));
    mostProbableNext(i) = corresp{m, 2};
    disp([corresp{i+1,2} ':' corresp{m, 2}]);
end;

%% 2.b Générer un mot

states = zeros(1, 28);
for i = 1 : 28
    states(i) = next_state(i, matrice_trans);
end;

plot(cumsum(matrice_trans(2,:)));

state = 1;
word = '';
i = 1;
while state ~= 28
    state = next_state(state, matrice_trans);
    word(i) = corresp{state, 2};
    i = i + 1;
end;

disp(word);

%% 3. Générer une phrase
for i = 1 : 28
    matrice_trans(29, i) = 0;
end;
matrice_trans(29, 29) = 1;
matrice_trans(28, 1) = 0.9;
matrice_trans(28, 28) = 0;
matrice_trans(28, 29) = 0.1;

state = 1;
word = '';
i = 1;
while state ~= 29
    state = next_state(state, matrice_trans);
    if state < 29
        word(i) = corresp{state, 2};
    end;
    i = i + 1;
end;

disp(word);

%% 4. Reconnaissance de la langue

% load('bigramfrancais');
load('bigramenglish');
eval('correspondance');

for i = 1 : 28
    matrice_trans(29, i) = 0;
end;
matrice_trans(29, 29) = 1;
matrice_trans(28, 1) = 0.9;
matrice_trans(28, 28) = 0;
matrice_trans(28, 29) = 0.1;

sentence = 'etre ou ne pas etre';
prob = 1;
preindex = 1;

for i = 1 : length(sentence)
    c = sentence(i);
    if c == ' '
        prob = prob * matrice_trans(preindex, 28) * matrice_trans(28, 1);
        index = 1;
    else
        index = find(char(corresp(:,2)) == c);
        prob = prob * matrice_trans(preindex, index);
    end;
    preindex = index;
end;
prob * matrice_trans(preindex, 28) * matrice_trans(28, 29)