#include <sys/types.h>
#include <sys/time.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "db.h"

#define DATABASE "access.db"

DB *dbp;
int n;
int t;
char *datum;
char buffer[20];
static char timebuf[512];
time_t ds;
time_t du;
struct timeval s, f;

void start()
{
    gettimeofday(&s, NULL);
}


void stop()
{
    gettimeofday(&f, NULL);
    ds = f.tv_sec - s.tv_sec;
    du = f.tv_usec - s.tv_usec;
    if (du < 0) {
      ds -= 1;
      du += 1000000;
    }
    sprintf(timebuf, "%d.%06d", ds, du);
}


void fill ()
{
  DBT key, data;
  int k;
  int ret;

  for (k = 0; k < t; k++) {
    memset (&key, 0, sizeof(key));
    memset (&data, 0, sizeof(data));
    data.data = datum;
    data.size = n;
    sprintf (buffer, "%d", k);
    key.data = buffer;
    key.size = strlen(buffer) + 1;

    if ((ret = dbp->put(dbp, NULL, &key, &data, 0)) == 0) {
      // printf("db: %s: key stored.\n", (char *)key.data);
    } else {
      dbp->err(dbp, ret, "DB->put");
      exit(1);
    }
  }
}


void
measure ()
{
  DBT key, data;
  int k;
  int ret;

  start();
  for (k = 0; k < t; k++) {
    memset (&key, 0, sizeof(key));
    memset (&data, 0, sizeof(data));
    sprintf (buffer, "%d", k);
    key.data = buffer;
    key.size = strlen(buffer) + 1;

    if ((ret = dbp->get(dbp, NULL, &key, &data, 0)) == 0) {
      // printf("db: %s: key retrieved.\n", (char *)key.data);
    } else {
      dbp->err(dbp, ret, "DB->get");
      exit(1);
    }
  }

  stop();

  printf("lookup: %s sec\n", timebuf);
}


int
main (int argc, char **argv)
{
  int ret, t_ret;

  if (argc < 3 || argc > 3) {
    fprintf(stderr, "%s: size total\n", argv[0]);
    exit (1);
  }

  n = atoi (argv[1]);
  t = atoi (argv[2]);
  datum = malloc (n);
  memset (datum, 0, n);
  datum[0] = 'c';

  if (db_create (&dbp, NULL, 0) != 0) {
    fprintf(stderr, "db_create: %s\n", db_strerror(ret));
    exit (1);
  }

  if (dbp->open (dbp, argv[1], NULL,
		 DB_BTREE, DB_CREATE, 0664) !=0) {
    dbp->err(dbp, ret, "%s", DATABASE);
    exit (1);
  }

  fill ();

  if ((t_ret = dbp->close(dbp, 0)) != 0 && ret == 0)
         ret = t_ret; 

  if (db_create (&dbp, NULL, 0) != 0) {
    fprintf(stderr, "db_create: %s\n", db_strerror(ret));
    exit (1);
  }

  if (dbp->open (dbp, argv[1], NULL,
		 DB_BTREE, DB_RDONLY, 0664) !=0) {
    dbp->err(dbp, ret, "%s", DATABASE);
    exit (1);
  }

  measure ();
}
