/**********************************************************************
 *
 * gdbmget -- retrieve a single value from the GDBM database
 * Copyright (C) 1999  The New Zealand Digital Library Project
 *
 * A component of the Greenstone digital library software
 * from the New Zealand Digital Library Project at the
 * University of Waikato, New Zealand.
 *
 * 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.
 *
 *********************************************************************/

#ifdef _MSC_VER
#include "autoconf.h"
#include "systems.h"
#include "gdbmconst.h"
#include "gdbm.h"

#else
#include <gdbm.h>
#endif

#include "gsdlconf.h"
#include <stdlib.h>
#include <cstring>

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

// 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 
print_usage (char *program_name) 
{
  cerr << "usage: " << program_name << " <database_path> <key>" << endl;
  cerr << endl;
}


int main (int argc, char *argv[]) 
{
  int block_size = 0;
  GDBM_FILE dbf;
  datum key, value;
  
  // sanity check
  if (argc != 3) 
    {
      print_usage (argv[0]);
      exit (-1);
    }
  
  // open the database
#ifdef _MSC_VER
  dbf = gdbm_open (argv[1], block_size, GDBM_READER, 00664, NULL, 0);
#else
  dbf = gdbm_open  (argv[1], block_size, GDBM_READER, 00664, NULL);
#endif
  if (dbf == NULL) 
    {
      cerr << argv[0] << ": couldn't open " << argv[1] << endl;
      exit (-1);
    }
  
  key.dsize = strlen(argv[2]);
  key.dptr = argv[2];
  value = gdbm_fetch (dbf, key);
  if (value.dsize > 0) 
    {
      for (int i = 0; i < value.dsize; i++)
        {
          cout << value.dptr[i];
        }
      cout << endl; // used to be printf("\n");
      // ?? free(value.dptri);
    } 
  else 
    {
      cout << endl; // used to be printf("\n");
    }
  
  gdbm_close (dbf);
  return 0;
}

