% The program implement the viterbi algoritmen. 

% Implements the viterbi-algorithm, which should recognise the correct model
% for the generated observation sequences. This is done be finding the best 
% state sequence given a observations sequence.

function speech_mm3_viterbi(filename)

% Loads the variabels generated by file speeh_mm3_model.

load(filename);
load model.mat;

% Run though the three models to find the model which fits the observation
% sequence best.

for modelnumber = 1:3,
  if modelnumber == 1,
    A = A1;
    B = B1;
    PI = PI1;
  elseif modelnumber == 2,
    A = A2;
    B = B2;
    PI = PI2;
  elseif modelnumber == 3,
    A = A3;
    B = B3;
    PI = PI3;
  end
  
  % Initialisation of the best score (highest probability).
  delta = zeros(T,N);
  delta(1,:) = PI .* B(O(1),:);
  
  % To retrieve the state sequence, we keep track of the argument which 
  % maximise delta() for each T and j by the array psi[]. 
  psi = zeros(T,N);

  % Recursion 
  for t = 2:T,
    for j = 1:N,
      for i = 1:N,
			temp(i) = delta(t-1,i)*A(i,j)*B(O(t),j);
			temp2(i)= delta(t-1,i)*A(i,j);
      end
      delta(t,j) = max(temp);
      [temp,psi(t,j)] = max(temp2);
    end
  end

  % Termination:
  [Probability(modelnumber), q(T)] = max(delta(T,:));
  
  % Path (state sequence) backtracking;
  for t = T-1:-1:1,
    q(t) = psi(t+1, q(t+1));
  end
  
  figure(modelnumber)
  subplot(2,1,1);
  plot(q);
  title('Estimeret sti');
  subplot(2,1,2);
  plot(statevector);
  title('Real sti');
end
disp('  ')
disp('Figure 1 corresponds to model 1; figure 2 to model 2 a.s.o')
disp('The model with the least likely probability is placed first!!')
Probability
[SortProbability,Model]=sort(Probability)

