#include <extcdecl.h>
#include <isam.h>
#include <sort.h>

TSort::TSort(int len)
{
  _sortvar = new s_prm;
  _sortvar->rc_len = len;
  nsortkey = 0;
  for (int i = 0; i < NOFLDS; i++)
  {
    _sortvar->s_fld[i].f_pos = 0;
    _sortvar->s_fld[i].f_len = 0;
    _sortvar->s_fld[i].ad = ' ';
  }
}


TSort::~TSort()
  
{
  delete _sortvar;
}


void TSort::init()
  
{
  CHECK(_sortvar->rc_len && nsortkey, "Attempt to initialize undefined sort");
  while (retrieve() != NULL);
  init_sort(_sortvar);
}


void TSort::sort(const char* record)
  
{
  CHECK(record != NULL, "Bad record to sort");
  ::sort((char*)record);
}


void TSort::endsort()
  
{
  ::sort(NULL);
}


const char* TSort::retrieve()
  
{
  return (const char *) sort_op();
}


void TSort::stats()
  
{
  sort_stats();
}


int TSort::length() const

{
  return _sortvar->rc_len ;
}


void TSort::reset(int len)

{
  _sortvar->rc_len = len ;
  nsortkey = 0;
}


// @doc EXTERNAL

// @mfunc Inizializza una chiave di ordinamento per il sort
void TSort::addsortkey(
  int pos,               // @parm Posizione di inizio
  int len,        // @parm Lunghezza della chiave
  char direction) // @parm Direzione di ordinamento ('a'= ascendente, 'd'=discendente)
  // @parm TRecfield& | f | Campo di file da utilizzare come criterio di ordinamento
  
  // @syntax addsortkey(int pos, int len, char direction = 'a');  
  // @syntax addsortkey(TRecfield& f, char direction = 'a');     
  
  // @comm Nel secondo caso viene ordinato il sort utilizzando il campo di un file       
  
{
  CHECK(pos >= 0 && pos+len <= _sortvar->rc_len, "Invalid sort key");
  _sortvar->s_fld[nsortkey].f_pos = pos + 1;
  _sortvar->s_fld[nsortkey].f_len = len;
  _sortvar->s_fld[nsortkey++].ad = direction;
}


void TSort::addsortkey(TRecfield& f, char direction)
  
{
  CHECK(f.pos() != NULL, "Invalid sort key");
  _sortvar->s_fld[nsortkey].f_pos = (f.pos() - f.record().string()) + 1;
  _sortvar->s_fld[nsortkey].f_len = f.len();
  _sortvar->s_fld[nsortkey++].ad = direction;
}
