/*
* This file is part of SkunkDB
* Copyright (c) 2001 Gianni Tedesco
*
*    SkunkDB 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.
*
*    SkunkDB 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 SkunkDB; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/


#include <skunk_app.h>
#include <skunk.h>
#include <skunk_query.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

#define BENCH_MODE

#ifdef BENCH_MODE
static inline int itoa(char *buf, int d)
{
	char *p = buf;
	char *p1, *p2;
	unsigned long ud = d;
	int ret=0;
  
	/* Divide UD by DIVISOR until UD == 0.  */
	do
	{
		int remainder = ud % 10;
		*p++ = remainder + '0';
	}while (ud /= 10);

	/* Terminate BUF.  */
	*p = 0;
  
	/* Reverse BUF.  */
	p1 = buf;
	p2 = p - 1;
	while (p1 < p2)
	{
		char tmp = *p1;
		*p1 = *p2;
		*p2 = tmp;
		p1++;
		p2--;
		ret++;
	}
	return ret;
}

void do_benchmark(p_sdbq q)
{
	char b[128];
	int i,f=0;
	int ret,x;

	for ( i=0; i<1000000; i++ ) {
		x=itoa(b, i);
		if ( !(ret=sdbq_query(q, b, x) ) ) {
			f++;
		}else if ( ret==-1 ) {
			printf("DB is corrupt! %i failed\n", f);
			return;
		}
	}
	printf("%i failed\n", f);
}
#endif

int main(int argc, char **argv)
{
	sdbq_t q;
	int fd;
#ifndef BENCH_MODE
	char *x;
	int ret;
#endif

	if ( argc < 3 ) {
		fprintf(stderr, "usage: %s <sdb_file> <key>\n", argv[0]);
		return SKUNK_ERR;
	}

	if ( (fd=open(argv[1], O_RDONLY)) < 0 ) {
		perror("open()");
		return SKUNK_ERR;
	}
	
	memset(&q, 0, sizeof(q));
	if ( !sdbq_init(&q, fd) ) {
		fprintf(stderr, "sdbq_init() failed\n");
		close(fd);
		return SKUNK_ERR;
	}
	
#ifdef BENCH_MODE
	do_benchmark(&q);
#else
	if ( (ret=sdbq_query(&q, argv[2], strlen(argv[2]))) ) {
		if ( !(x=malloc(q.item.val_len+1)) ) {
			perror("malloc()");
			sdbq_close(&q);
			return SKUNK_ERR;
		}
		memset(x, 0, q.item.val_len+1);
		memcpy(x, q.item.val, q.item.val_len);
		printf("%s\n", x);
		free(x);
	}else{
		fprintf(stderr, "record not found (%i)\n", ret);
		sdbq_close(&q);
		close(fd);
		return SKUNK_ERR;
	}
#endif	
	sdbq_close(&q);
	close(fd);
	return SKUNK_OK;
}
