/* x2.m */

void get_x( int _K)
{
/* data setup for symbol values 0, 1 with f(D) = 1 + 0.5D */
/* KB ECE 8770 Spring 1998 Lecture 11 page 6 */

  if( narg == 0) {

    KALMAN=0;	/* don't use Kalman cost function */

    LOADED=2;

    N = 4;	/* N data samples */
    M = 2;	/* M symbol values */
    K = 1;	/* find K best completely unmerged paths */
  
    states = FSM( [ 0 1], 1);
  
    zstate = 1;			/* zero state, states( zstate) == 0 */
  
    x = [ 0 1 0 0];		/* input sequence */
  
    f = [1 0.5]';
  
    trans = FSM_trans( states, f);	/* get state transition matrix */
  
    y = FSM_out( x, states, zstate, f);	/* get FSM output */
  
    noise = [ 0.2 -0.4 0.4 0.1];	/* "random" noise */
  
    z = y + noise;			/* signal plus noise */

    return;
  }

  /* narg > 0 */

  if( LOADED != 2) {
    print( "get_x: call get_x with no args first.");
    return;
  }

  M = rows(states);

  if( _K > M) {
    printf( "get_x: K > M not allowed!");
    return;
  }

  K = _K;
  combos = combinations( 1:M, K);
  perms = permutations( 1:K);
  M = rows(combos);

  zstate = 0;
}


double get_yval( int _cur, int _next)
{
  return trans(_cur,_next);
}


double get_cost( double _zz, int _cur, int _next, int _j)
{
  double yval = get_yval( _cur, _next);

  if( yval == HUGE_VAL)
    return yval;

  return pn( _zz - yval);
}

vector get_ex( vector _index)
{
  vector t = states(:,1)';

  return t( _index);
}


matrix get_paths( vector _index, vector _perm, int _el)
{
  int j, c;
  matrix xex;
  vector combo;
  vector ii;

  c = cols(_index);
  xex = zeros( K, c);

  for( j = 1; j <= c; ++j) {

    if( VIT_NEW) {
      combo = combos(_index(_el,j),:);
      ii = perms( _perm(_el,j), :);
/*
      ii = perms( _vp(_index(_el,j)+j*M, _el), :); -- wrong
*/
    } else {
      combo = combos(_index(j),:);
      ii = perms( _vp(_index(j),j+1), :);
    }

    xex(:,j) = states( combo(ii), :);
  }

  return xex;
}
