function w = get_cost( t, prev, next, el, vnum)
%
% compute incremental state transition cost from the
% el'th best of prev state, to next state, at time t,
% for Viterbi instance number vnum
%
% R. Perry, Oct. 2001

global USE_GGqq_tmp;
global G;
global q;

global HUGE_VAL;
global TYPE;
global z;

global states;
global Memory;
global Nusers;
global Nchips;
global FIR_save;
global trans;

global GG_tmp;
global qq_tmp;
global GG;
global qq;

global Nsyms;
global FIR_length;
global FIR_0;
global C_inv;
global alpha;
global alpha2;
global var_noise;

global ex_known;
global ex_gm;
global ex_p;

if( TYPE == 30) % multi-user, Gauss-Markov, known channel

  w = HUGE_VAL;

  if( trans(prev,next)) % transition is feasible

    w = 0;

    for j = 1:Nchips
      w1 = z(j,t);
      for u = 1:Nusers
        ui = (u-1)*Memory + [1:Memory];
        us = [states(ui,next)' states(ui(Memory),prev)];
        w1 = w1 - us*FIR_save(:,u,j,t);
      end
      w = w + w1*w1;
    end

  end

elseif( TYPE == 31) % multi-user, Gauss-Markov cost

  w = HUGE_VAL;

  if( trans(prev,next)) % transition is feasible

    % get G and q
    %
    get_Gq(t, prev, next, el, vnum);

    if( USE_GGqq_tmp)
      %
      % store G and q
      %
      GG_tmp(:,:,el,prev,next) = G;
      qq_tmp(:,:,el,prev,next) = q;
    end

    % compute cost
    %
    w = - Nchips * log(det(G));

    for j = 1:Nchips
      w = w - q(:,j)'*G*q(:,j);
    end

  end

elseif( TYPE == 40) % multi-user, Gauss-Markov, known channel, separate trellises

  w = HUGE_VAL;

  if( trans(prev,next)) % transition is feasible

    w = 0;

    for j = 1:Nchips
      w1 = z(j,t);
      for u = 1:Nusers
        if( u == vnum) % that's me
          us = [states(:,next)' states(Memory,prev)];
        else
          u2_ex = ex_known(:,:,u) * diag(ex_p(:,u)); % scale by p
          u2_ex = sum(u2_ex,2);                      %  then marginalize
          us = [flipud(states(:,1)); u2_ex];         % soft estimate
          us = us(t+Memory:-1:t)';
        end
        w1 = w1 - us*FIR_save(:,u,j,t);
      end
      w = w + w1*w1;
    end

  end

elseif( TYPE == 41) % multi-user, Gauss-Markov cost, separate trellises

  w = HUGE_VAL;

  if( trans(prev,next)) % transition is feasible

    % get G and q
    %
    get_Gq(t, prev, next, el, vnum);

    if( USE_GGqq_tmp)
      %
      % store G and q
      %
      GG_tmp(:,:,el,prev,next,vnum) = G;
      qq_tmp(:,:,el,prev,next,vnum) = q;
    end

    % compute cost
    %
    % if( det(G) <= 0)
    %  error( 'det(G) <= 0');
    % end
    %
    % old bug sometimes makes det(G) < 0 in this case
    %
    % detG = det(G);
    %
    % if( detG <= 0) % cost -> HUGE_VAL
    %   return;
    % end
    %
    % w = - Nchips * log(detG);

    w = - Nchips * log(det(G));

    for j = 1:Nchips
      w = w - q(:,j)'*G*q(:,j);
    end

  end

else

  error( 'get_cost: unknown TYPE');

end
