// sort a DBf table


#include <stdio.h>
#include <string.h>
#include "dbftable.h"

static char HELP[] =
  "\n"
  "  DBFSORT  inputfile outputfile  key1 key2 key3 ... keyn\n"
  "\n"
  "  sorts the records in the specified table according to the\n"
  "  specified key(s).";

int main(int argc, char **argv)
{
  if (argc < 4)
  {
    puts(HELP);
    return 1;
  }
  char *keys;
  int n = 0;
  for (int i = 3; i < argc; i++) n += strlen(argv[i]) + 1;
  keys = new char[n];
  keys[0] = 0;
  for (int i = 3; i < argc; i++)
  {
    strcat(keys, argv[i]);
    if (i+1 < argc) strcat(keys, " ");
  }
//   printf("keys [%s]\n", keys);
  dbf_table t;
  if (!t.open(argv[1], DBF_READ))
  {
    printf("Couldn't open %s\n", argv[1]);
    delete keys;
    return 1;
  }
  if (!t.sort(argv[2], keys))
  {
    printf("error in sorting %s", argv[1]);
    delete keys;
    return 1;
  }
  delete keys;
  return 0;
}


