/* ===== COUNTER: A program to count events ===== */


/* ===== DEFINEs ===== */
#define  DOS					 /* for C-Index */
#define  MSC					 /* for C-Index too */
#define  NEW_FLDTYPES  /* for C-index too */


/* ===== INCLUDEs ===== */
#include <cndx.h>
#include <stdio.h>


/* ===== MAIN MODULE ===== */
main(int argc, char *argv[])
{
	CFILE  data_file;
	char	 filename[90];
	int		 ret, num, len;


	/* bark at the user if nothing on the command line */
	if(argc==1){
		printf("COUNTER v1.0:  By Greg Wishart, Hamilton, Ontario Canada\n");
		printf("Usage: Specify the module name on the command line, and ");
		printf("I'll increment the\ncounter for that module.\n\nOther options:\n");
		printf("counter set pgmname 5   - sets count of pgmname to 5\n");
		printf("counter display_counts  - displays counts\n");
		exit(0);
	}


	/* set filename of datafile to that of the program, include the directory */
	/* path the program was loaded from */
	strcpy(filename, argv[0]);
	len=strlen(filename);
	filename[len-3]='D';
	filename[len-2]='A';
	filename[len-1]='T';


	/* open data file */
	ret=copen(&data_file, filename);
	if(ret==FAIL){
		ret=ccreate(&data_file, filename);
		if(ret!=CCOK){
			printf("Error creating %s.\n", filename);
			exit(1);
		}
	}


	/* display counts? */
	if(strcmp(argv[1], "display_counts")==0){
		ret=cfirst(&data_file, 1, &num, sizeof(num));
		if(ret==CCOK){
			printf("Count: Counter name:\n----------------------------------------\n");
		}else{
			printf("No counters in %s.\n", filename);
			cclose(&data_file);
			exit(0);
		}

		while(ret==CCOK){
			if(num) printf("%5d: %s\n", num, data_file.key);
			ret=cnext(&data_file, 1, &num, sizeof(num));
		}

		cclose(&data_file);
		exit(0);
	}


	/* set count? */
	if(strcmp(argv[1], "set")==0){
		ret=cfind(&data_file, 1, argv[2], 0L, &num, sizeof(num));
		if(ret!=CCOK && ret!=KEYMATCH){
			num=atoi(argv[3]);
			cnextrec(&data_file);
			ret=cunqadd(&data_file, 1, argv[2], data_file.rec, &num, sizeof(num));
		}else{
			num=atoi(argv[3]);
			cchgcur(&data_file, 1, &num, sizeof(num));
		}

		cclose(&data_file);
		exit(0);
	}


	/* increment count */
	ret=cfind(&data_file, 1, argv[1], 0L, &num, sizeof(num));
	if(ret!=CCOK && ret!=KEYMATCH){
		num=1;
		cnextrec(&data_file);
		ret=cunqadd(&data_file, 1, argv[1], data_file.rec, &num, sizeof(num));
	}else{
		num++;
		cchgcur(&data_file, 1, &num, sizeof(num));
	}

	cclose(&data_file);
}
