% kaleh_init - initialization for the Kaleh/Vallet algorithm
%
% Assumes (-1,1) symbol values.
%
% \bibitem{kaleh}
% G. K. Kaleh and R. Vallet,
% ``Joint Parameter Estimation and Symbol Detection for Linear or Nonlinear Unknown Channels,''
% {\em IEEE Trans. on Communications,} Vol. 42, No. 7, pp. 2406-2413, July 1994.
%
function kaleh_init

global states;	% standard Viterbi globals
global N;	% number of samples
global M;	% number of states

global PS;	% state transition probability matrix
global Xt;	% X(t) vector values
global Nij;	% used to get i and j given n
global IJn;	% used to get n given i and j
global gamma;   % array for forward recursion
global beta;    % array for backward recursion
global LY;      % array for likelihood values

global gamma_scale;     % normalization for columns of gamma and beta

[r c] = size(states);	% c == M

% set sizes of PS, Xt, Nij, IJn
%
PS  = zeros( c,   c);
Xt  = zeros( r+1, 2*c);
Nij = zeros( 2,   2*c);
IJn = zeros( c,   c);

p = 1/2;	% 1/|A|

n = 0;		% counter for Xt

% setup PS, Xt, Nij, IJn
%
for i = 1:c
  for j = 1:c
    if( r > 1)
      a = all( states(1:r-1,i) == states(2:r,j));
    else
      a = 0;
    end
    if( (r == 1) | (a ~= 0))
      PS(i,j) = p;
      n = n + 1;
      Nij(:,n) = [i j]';
      IJn(i,j) = n;
      Xt(:,n) = [states(:,j); states(r,i)];
    end
  end
end

% set sizes of gamma, beta, LY, gamma_scale
%
gamma = zeros( M, N+1);
beta  = zeros( M, N+1);

LY    = zeros( 2*M, N);

gamma_scale = ones(1,N+1);

% unknown initial state
%
% gamma(:,1)=(1/M)*ones(M,1);
%
% initial state all -1's (state 1)
%
gamma(1,1) = 1;

beta(:,N+1)=ones(M,1);
