/*******************************  regendrv.c  ********************************

  Purpose:	A program to test regenerating and using a precomputed hashing
  		function.

  Provenance:	Written and tested by Q. Chen and E. Fox, April 1991.
  		Edited and tested by S. Wartik, April 1991.

  Notes:	The program is used as follows:

  			regen_driver mphf-file keyword-file

		The result is a set of lines, written to stdout, indicating
		the bucket of each keyword in the keyword file.
**/

#include <stdio.h>
#include <string.h>
#include <math.h>

#include "types.h"
#include "rantab.h"
#include "regenphf.h"	

#ifdef __STDC__

extern void	retrieveAll ( mphfType *mphf, char *key_file );

extern void	exit( int status );

#else

extern void	retrieveAll ();

extern void	exit();

#endif

/**************************************************************************

	   main( int, char** )

   Return:	Nothing.

   Purpose:	See the header for this file.
**/

main( argc, argv )
   int argc;
   char *argv[];            /* arg1: mphf file;  arg2: key file */ 
{
    mphfType mphf;

    if ( argc != 3 ) {
	fprintf(stderr, "Usage: %s mphf-file key-file\n", argv[0]);
	exit(1);
    }

    if ( regen_mphf ( &mphf, argv[1] ) == NORM ) 
	retrieveAll ( &mphf, argv[2] );
    else {
	fprintf(stderr, "Can't regenerate hashing function from \"%s\".\n",
		argv[1]);
	exit(1);
    }

    release_mphf ( &mphf );
    exit(0);
}

/**************************************************************************

	   retrieveAll( mphfType*, char* )

   Return:	void

   Purpose:	Given a file of keys and a structure describing a
   		MPHF previously computed for those keys, print
		each key's location on the standard output stream.
**/

void retrieveAll( mphf, key_file )
    mphfType	*mphf;			/* in: mphf specification.      */
    char	*key_file;		/* in: the key file.		*/
{
    FILE	*fp;                  	/* Handle for specification file. */
    char	string[MAX_KEY_LENG]; 	/* Key string. 	         	*/
    int		hash;                  	/* Computed hash value.         */
    int		max_bucket_length;	/* The maximum number of chars  */
    					/* needed to represent a bucket */
    					/* index as a string.		*/

    if ( (fp = fopen(key_file, "r")) == 0 ) {
	fprintf(stderr, "Can't read file \"%s\".\n", key_file);
	exit(1);
    }

    max_bucket_length = (int)log10((double)mphf->no_arcs) + 1;
    while ( fgets( string, MAX_KEY_LENG, fp ) != 0 ) {
	string[strlen(string)-1] = '\0';
	hash = retrieve( mphf, string );
	printf("Bucket %*d: %s\n", max_bucket_length, hash, string);
    }

    fclose(fp);
}
