% get_perm( L, zz, vp, cur, next, col, el) - find lowest cost permutation
%
% Note: vp isn't used here because the kalman results
% are already stored in permuted form.
%
function [cost, i_cost] = get_perm( L, zz, vp, cur, next, col, el)

global DEBUG;
global HUGE_VAL;
global combos;
global perms;
global unique_perms;
global perm_offset;
global M;
global MP;
global K;
global MM;
global MM_max;
global kxv;
global XY;
global XY_offset;
global missed_cost;
global log2pi;
global Kv;

global Cmiss;
global Cfalse;
global tr_period;

global Winc;			% precomputed incremental costs

if( DEBUG>2) disp('get_perm:'), cur, next, end;

% need to return all possibilities if L > 1
%
if( L > 1)
  cost = HUGE_VAL * ones(MP,1);
  i_cost = [1:MP]';
else
  cost = HUGE_VAL;
  i_cost = 1;
end

% handle dummy initial state
%
% change from this:
%  if( col == 1)
% to following, for PKKwindow, 20 April 1999:
if( mod(col,tr_period) == 1)
  if( cur == next & all(combos(:,next) <= MM(1)))
    cost(1) = Cmiss(K+1,K) + Cfalse(MM(1)-K+1);
  end
  return;
end

% next combinations
%
s_next = combos(:,next);

% s_next contains non-existant measurement indices
%
if( any( (s_next > MM(col)) & (s_next <= MM_max)))
  return;
end

n = sum(s_next <= MM(col));		% number of measurements used for tracks
m = MM(col) - n;			% number of false detections

apriori = Cmiss(n+1,K) + Cfalse(m+1) + (MM(col) - K)*missed_cost;

Winc_rows = [1:K] + ((el-1)*M + (cur-1))*K;	% row indices for Winc

% reset cost array size if L==1
%
if( L == 1)
  cost = HUGE_VAL * ones(MP,1);
end

%% for each permutation
%%
%for i = 1:MP
%
%  up = unique_perms(i,next);
%
%  if( up == 0)	% no more unique permutations
%    break;
%  end
%
%  s_tmp = s_next(perms(:,up));
%
%  cost(i) = apriori + sum( diag( Winc( Winc_rows, s_tmp)));
%
%  if( DEBUG>2) s_tmp, cost(i), end;
%
%end
%
% vectorized replacement for above loop:
%
up = unique_perms(:,next);
up = up(find(up>0));
nup = size(up,1);
%
% The following two reshapes are needed for octave
%
s_tmp = reshape(s_next(perms(:,up)),K,nup) + perm_offset(:,1:nup);
w = Winc( Winc_rows, :)';
w = w(:);
cost(1:nup) = apriori + sum( reshape(w(s_tmp),K,nup));


% return only the lowest cost result if L == 1
%
if( L == 1)
  [cost i_cost] = sort(cost);
  cost = cost(1);
  i_cost = i_cost(1);
end
