/*
 * (c) 2005 Research Group Dr. Fuhrmann, University of Karlsruhe, Germany
 * All rights reserved.
 *
 * Author:
 *         Stefan Denk <denk@ira.uka.de>
 *
 * $Id: findhash.c,v 1.3 2005/11/21 09:39:01 kutzner Exp $
 *
 */

/*************************************************************
 *
 * code to find the corresponding filename and offset for a 
 * given hashvalue
 *
 * remove // comments to get function to standalone (main)
 *
 *************************************************************/

#include "hashdef.h"

// int main(int argc, char **argv) 
uint32_t findhash(int vidfp, uint32_t searchedhash) 	
{
//	int vidfp;
	int found = 0;
	int counter = 0;
	int viddataentries = 0;
	ssize_t filesize = 0;
	struct stat fileinfo;
//	uint32_t searchedhash = 1579774270;
	
	bzero(&fileinfo, sizeof(fileinfo));
//	vidfp = open(argv[1], O_RDONLY);
	fstat(vidfp, &fileinfo);
	filesize = fileinfo.st_size;
//	printf("filesize: %d\n", filesize);
	viddataentries = filesize / sizeof(vid);		
	
	viddata = (vid*) mmap(0, filesize, PROT_READ, MAP_PRIVATE, vidfp, 0);

	while (counter < viddataentries)
	{
		if(viddata[counter].hash == searchedhash)
		{  
			found = 1;
//			close(vidfp);
//			printf("found hash at offset %u\n", viddata[counter].offset);
//			return 0;
			return viddata[counter].offset;
		}
		counter++;
	}
	close(vidfp);

	if (found == 0)	return 1;		// offset 1 is not expected to be a valid result => error indicator
	return 1;
}

