/*
 *	$Source$
 *	$Author$
 *	$Header$
 */

#ifndef lint
static char *rcsid_makeidx_c = "$Header$";
#endif lint

#include <stdio.h>
#include <sys/types.h>
#include "bible.h"

main (argc, argv)
	int argc;
	char **argv;
{
	int	i;
	
	init_booktab();
	for (i = 0; i < NUMBOOKS; i++)
		buildindex(&booktab[i]);
}

buildindex(b)
	BOOK	*b;
{
	FILE	*fx, *f;
	char	line[256];
	long	position;
	struct verse_idx index;
	int	count;
	VERSE	*v;
	
	printf("Building table for %s....\n", b->name);
	strcpy(tmp, LIBDIR);
	if (!(f = fopen(strcat(tmp, b->filename), "r"))) {
		perror(tmp);
		fprintf(stderr, "Cannot open text file!\n");
		exit(1);
	}
	strcpy(tmp, LIBDIR);
	strcat(tmp, b->filename);
	if (!(fx = fopen(frob_ext(tmp, ".idx"), "w"))) {
		perror(tmp);
		exit(1);
	}
	while (!feof(f)) {
		position = ftell(f);
		fgets(line, sizeof(line), f);
		if (line[0] == '\037') {
			v = parse_verse(line+1);
			if (!v)
				printf("Bad format in input file:\n%s\n",
				       line);
			else {
				index.pos = position;
				index.chapter = v->c;
				index.verse = v->v;
				fwrite(&index, sizeof(index), 1, fx);
				if (count++ > 20) {
					count = 0;
					print_verse_cite(v);
					printf("\r");
					fflush(stdout);
				}
			}
			free_verse(v);
		}
	}
	fclose(f);
	fclose(fx);
}
