function vit_update( vnum)
%
% update routine for generalized Viterbi algorithm
%
% R. Perry, June 2001
%
% Advances to the next data point.
%
% Usage:
%
%   vit_init( vnum)
%
%     vnum - Viterbi instance number
%
% If vnum is not specified, it defaults to 1.
%
% vit_init() must be called first before invoking vit_update()
%
% Functions called from here, to be supplied by the user for
% a particular problem type:
%
%   cost_init()
%
%       To initialize the cost function parameters.
%
%   get_cost()
%
%       To get the cost value for a state transition.
%
%   cost_update()
%
%       To allow the cost function to update itself
%       based on the Viterbi decisions.
%
% See also:
%
%   vit_init, vit_paths

% global variables
%
global HUGE_VAL; % 1e99
global DEBUG;    % for debugging
global V;        % main state array
global Vl;       % array for L-best indices
global Vw;       % cost array
global Vparam;   % parameters
global Vprev;    % previous state indices
global Vlprev;   % previous state el indices

% vnum set to 1 if not specified
%
if( nargin < 1)
  vnum = 1;
end

% get parameters
%
L  = Vparam(1);
M  = Vparam(2);
N  = Vparam(3);
Nv = Vparam(4);

% check vnum
%
if( vnum < 1 | vnum > Nv)
  error('vnum out of bounds');
end

% get/update time index
%
t  = Vparam( 4 + vnum);
t = t + 1;

if( t < 1 | t > N)
  error( 'time index is out of bounds');
end

if( t == 1)
  cost_init( vnum);
end

Vparam( 4 + vnum) = t;

% update the trellis
%
w_new = HUGE_VAL*ones(L,M); % new cumulative costs

for next = 1:M % for each next state

  if( DEBUG > 1) next, end;

  w1 = HUGE_VAL*ones(L*M,1);

  i = 0;  % for indexing w1

  for prev = 1:M % for each previous state

    for el = 1:L %  and el value
  
      i = i + 1;

      if( Vw(el,prev,vnum) < HUGE_VAL) % reachable state

        if( DEBUG > 1) prev, el, end;

        p = get_cost( t, prev, next, el, vnum);

        if( DEBUG > 1) p, end;

        if( p < HUGE_VAL)
          w1(i) = p + Vw(el,prev,vnum);
        end

      end % reachable state

    end % el

  end % prev

  % keep L best paths
  %
  [s1 s2] = sort(w1);
  w_new(:,next) = s1(1:L);
  s2 = s2(1:L);
  V(:,next,t,vnum) = Vprev(s2);
  Vl(:,next,t,vnum) = Vlprev(s2);

end % next

Vw(:,:,vnum) = w_new;

cost_update( t, vnum);
