/**********************************************************************
 *
 * tdb2txt.cpp -- A utility to retrieve the entire contents of a TDB
 *                file as text ala buildproc encoded output.
 *
 * A component of the Greenstone digital library software
 * from the New Zealand Digital Library Project at the
 * University of Waikato, New Zealand.
 *
 * Copyright (C) 2011  The New Zealand Digital Library Project
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *********************************************************************/

#if defined(GSDL_USE_OBJECTSPACE)
#include <ospace\std\iostream>
#elif defined(GSDL_USE_IOS_H)
#include <iostream.h>
#else
#include <iostream>
#endif

#include <cstdlib>

#include <fcntl.h>
#include "tdb.h"

// use the standard namespace
#if !defined (GSDL_NAMESPACE_BROKEN)
#if defined(GSDL_USE_OBJECTSPACE)
using namespace ospace::std;
#else
using namespace std;
#endif
#endif

/**
 */
void
printUsage (char *program_name)
{
  cerr << "usage: " << program_name << " database-name" << endl << endl;
}
/** printUsage() **/

/**
 */
int
main (int argc, char *argv[])
{
  // sanity check
  if (argc != 2)
  {
    printUsage(argv[0]);
    exit (0);
  }

  char *dbname = argv[1];

  // open the database
  int hash_size = 0;
  int tdb_flags = TDB_DEFAULT;
  int open_flags = O_RDONLY; 
  TDB_CONTEXT *tdb = tdb_open(dbname, hash_size, tdb_flags, open_flags, 0664);
  if (!tdb)
  {
    cerr << "tdb2txt::main() - couldn't create " << dbname << endl;
    exit (0);
  }

  TDB_DATA key = tdb_firstkey(tdb);
  while (key.dptr != NULL)
  {
    cout << "[";
    for (int i = 0; i < key.dsize; ++i)
    {
      cout << key.dptr[i];
    }
    cout << "]" << endl;
    TDB_DATA value = tdb_fetch (tdb, key);
    for (int i = 0; i < value.dsize; ++i)
    {
      cout << value.dptr[i];
    }
    cout << endl << "----------------------------------------------------------------------" << endl;

    // caller responsible for freeing this memory
    free(value.dptr);

    /* get next key */
    TDB_DATA nextkey = tdb_nextkey (tdb, key);

    /* free old key's dptr, otherwise causes memory leak */
    free(key.dptr);

    /* can now safely copy content of nextkey into key */
    key = nextkey;
  }

  tdb_close(tdb);

  return 0;
}
/** main() **/
