% perm_update( col, v, vl, vp) - update predicted values and gain for K>1
%
% v comes from the v array in viterbi and specifies
% the indices of the previous states representing the
% lowest cost paths.
% 
% vl comes from the vl array in viterbi and specifies
% the "l" values associated with the previous states.
% 
% vp comes from the vp array in viterbi and specifies
% the permutation values associated with the current states.
%
function perm_update( col, v, vl, vp)

global DEBUG;
global N;
global M;
global K;
global L;
global combos;
global perms;
global kxv;
global XY_offset;
global XY;
global MM;
global MM_max;
global G;

global Winc;
global Wtot;

global tr_period;

% replace this:
%  if( col == 1)	% cost_init() already handled this case
% with the following for PKKwindow, 20 April 2000
%
if( mod(col,tr_period) == 1)
  return;
end

if(DEBUG>2) disp( 'perm_update'); v, vl, vp, end;

MK = M*K;

kk = (col-1)*MK + [1:MK];		% indices for kxv
if( MM(col) > 0)
  ii = XY_offset(col) + [1:MM(col)];	% indices for XY
end

k1 = kxv(:,kk);
k2 = k1;

Wtot_new = zeros(size(Wtot));		% new total costs for each track

for j = 1:M

  combo = combos(:,j);

  w2 = (j-1)*K;			% row offset for Wtot_new

  j2 = [1:K] + w2;		% index range for k2

  for i = 1:L

    vij = v(i,j);

    if( vij ~= 0)

      w1 = (vij-1)*K;		% row offset for Wtot

      j1 = [1:K] + w1;  	% index range for k1

      perm = perms(:,vp(i,j));

      cperm = combo(perm);

      el = vl(i,j);

      el14 = [1:4] + (el-1)*4;
      i14  = [1:4] + (i-1)*4;

      if( DEBUG>2) j1, j2, el14, i14, end;

      txv = zeros(4,K);

      kel_offset = ((el-1)*M + (vij-1))*K;

      for k = 1:K	% only update for non-missed target events
	ki = cperm(k);
	Cinc = 0;
	if( ki <= MM_max)
	  kii = ii(ki);
	  txv(1:2,k) = G * (XY(1,kii) - k1(el14(1),j1(k)));
	  txv(3:4,k) = G * (XY(2,kii) - k1(el14(3),j1(k)));
	  Cinc = Winc(k+kel_offset,ki);
        end
%	Wtot_new(k+w2,i) = Wtot(perm(k)+w1,el) + Cinc;	% wrong
	Wtot_new(k+w2,i) = Wtot(k+w1,el) + Cinc;
      end

      k2(i14,j2) = k1(el14,j1) + txv;		% update x,y positions and velocities

    end

  end
end

kxv(:,kk) = k2;		% update kxv

Wtot = Wtot_new;	% update Wtot

if( col < N)
  kalman_gain_update;
  kalman_predict(col);
end
