global
#include <stdlib.h>

int icmp( const void *e1, const void *e2 )
{
  int i1 = *(int*) e1;
  int i2 = *(int*) e2;

  return i1 < i2 ? -1 : i1 == i2 ? 0 : 1; 
}

end

local
int got;
size_t irow = 0;
size_t oidx = 0;
size_t* output_irow;
int naxis2;
long int seed = getenv("SEED") ? atoi(getenv("SEED")) : 1 ;

srand48(seed);
end

before

naxis2 = FunParamGeti(fun, "NAXIS", 2, -1, &got);
if ( ! got )
{
  gerror(stderr, "error retrieving naxis2\n" );
  goto error;
}

/* allocate one more than we need.  we stick a sentinel valuethat is
   always greater than the number of rows in the file in the last
   slot.  that way we never fall off the end of output_irow in the
   processing loop below.  */

if ( ! (output_irow = malloc( (naxis2+1) * sizeof(*output_irow) ) ) )
 {
   gerror(stderr, "error allocating index array of size %d\n", naxis2 );
   goto error;
 }

{ size_t i;
  for ( i = 0 ; i < naxis2 ; i++ )
    output_irow[i] = drand48() * naxis2;
  qsort( output_irow, naxis2, sizeof(*output_irow), icmp );
  output_irow[naxis2] = naxis2;
}
  
end


cur->x;

/* if the current row index is the next one to write, write it.
   the row may be used multiple times, so keep incrementing the
   list of rows to write until it doesn't match the current row */

while( irow == output_irow[oidx] )
{
  FunTableRowPut(ofun, (char *)cur, 1, __i, NULL);
  oidx++;
}
irow++;

/* don't let funcalc write anything out; we've handled that */
continue;

