% vit_back( tr, j, i_min, l_min, v_cur, vl_cur, vp_cur) - backtrack through Viterbi trellis
%
function [path_index, el_index, perm_index] = vit_back( tr, j, i_min, l_min, v_cur, vl_cur, vp_cur)

global DEBUG;

global K;
global M;
global v;
global vl;
global vp;

% path_index, el_index, and perm_index are local variables here

n_tr = j - tr;

LL = length(i_min);

path_index = zeros( LL, n_tr);
el_index = zeros( LL, n_tr);
if( K > 1)
  perm_index = zeros( LL, n_tr);
else
  perm_index = 0;
end

for jj = j:-1:(tr+1)

  if( jj ~= j)
    jM = [1:M] + jj*M;

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

  kk = jj - tr;	% index for path_index, el_index, perm_index

  path_index(:,kk) = i_min;
  el_index(:,kk) = l_min;

  ll_min = zeros(LL,1);
  ii_min = ll_min;

  if( K > 1)
    pp_min = ll_min;
  end

% v_cur, i_min, l_min

  for i = 1:LL
    c = i_min(i);
    if( c ~= 0)
      if( size(v_cur,2) == 1)	% kludge for single-column v_cur when called from vit_merge()
        c = 1;
      end
      ii_min(i) = v_cur( l_min(i), c);
      ll_min(i) = vl_cur( l_min(i), c);
      if( K > 1)
        pp_min(i) = vp_cur( l_min(i), c);
      end
    end
  end

  % eliminate above loop, improvement by Anand Vaddiraju
  %
  % can no longer do this because we might not have L paths,
  % i.e. some of w_min may be HUGE_VAL, so some of l_min and i_min may be 0.
  %
  %  ii_min = diag( v_cur( l_min, i_min));
  %  ll_min = diag( vl_cur( l_min, i_min));
  %
  %  if( K > 1)
  %    pp_min = diag( vp_cur( l_min, i_min));
  %  end

  i_min = ii_min;
  l_min = ll_min;

  if( K > 1)
    perm_index(:,kk) = pp_min;
  end

end % jj
