% [r_i_min, r_l_min] = vit_tr( tr, j) - Viterbi trellis truncation
%
function [r_i_min, r_l_min] = vit_tr( tr, j)

global DEBUG;
global HUGE_VAL;

global w;
global w_min;
global K;
global L;
global M;
global v;
global vl;
global vp;
global path_index;
global el_index;
global perm_index;

[tmp ii_min] = sort(w(:));

if( DEBUG > 1) ii_min, end;

ii_min = ii_min(1:L);

i_min = sort_cols(w,ii_min);
l_min = sort_rows(w,ii_min);

w_min = w(:);
w_min = w_min(ii_min);

% return values
%
r_i_min = i_min;
r_l_min = l_min;

if( any(w_min == HUGE_VAL))
  i_min(find(w_min==HUGE_VAL)) = 0;
end

% w_min, i_min, l_min

jM = [1:M] + j*M;

v_cur = v(:,jM);
vl_cur = vl(:,jM);
if( K > 1)
  vp_cur = vp(:,jM);
else
  vp_cur = 0;
end

[tr_path_index, tr_el_index, tr_perm_index] = vit_back( tr, j, i_min, l_min, v_cur, vl_cur, vp_cur);

jtr = (tr+1):j;

path_index(:,jtr) = tr_path_index;
el_index(:,jtr) = tr_el_index;
if( K > 1)
  perm_index(:,jtr) = tr_perm_index;
end

if( DEBUG)
  path_index, el_index
  if( K > 1)
    perm_index
  end
end
