#include <stdio.h>
#include <stdlib.h>

#define STRLEN 1000
#define LSRID "% This is file ls-R. Maintained by texhash and append_db.\n"

extern char *kpse_var_expand();
extern void kpse_set_progname();

main(argc, argv)
  int argc;
  char *argv[];
{
	FILE *f;
	char db_name[STRLEN], *line[STRLEN];
	if (argc != 3) {
		fprintf(stderr, "Usage: %s dir file\n", argv[0]);
		exit(0);
	}
	kpse_set_progname(argv[0]);
	strncpy(db_name, kpse_var_expand("$TEXMF/ls-R"), STRLEN-1);
	if ((f = fopen(db_name, "r")) == NULL) {
		fprintf(stderr, "%s: cannot read %s.\n", argv[0], db_name);
		exit(1);
	}
	if (fgets((char *)line, strlen(LSRID)+1, f) == NULL) {
		fprintf(stderr, "%s: error reading %s.\n", argv[0], db_name);
		exit(1);
	}
	if (strncmp((char *)line, LSRID, strlen(LSRID)) == 0) {
		close(f);
		if ((f = fopen(db_name, "a")) == NULL) {
			fprintf(stderr, "%s: cannot write %s.\n", argv[0], db_name);
			exit(1);
		}
		fprintf(f, "%s:\n%s\n", argv[1], argv[2]);
		fclose(f);
	} else {
		fprintf(stderr, "%s: not a db file: %s.\n", argv[0], db_name);
		fprintf(stderr, "To create a db file, you may use texhash.\n");
		exit(1);
	}
	exit(0);
}
