#include <sort.h>

#ifndef __EXTCDECL_H
#include <extcdecl.h>
#endif

#ifndef __CHECKS_H
#include <checks.h>
#endif

//#include <ccommon.h>
//#include <ccustio.h>
//#include <cfiles.h>
//#include <cbpltree.h>
//#include <cisam.h>
//#include <csort.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;
}


void TSort::addsortkey(int pos, int len, char direction)
  
{
  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;
}
