/****************************************/
/* check.c: Prints a checkbook balance. */
/* author: aedinius ~ date: 12/12/2002  */
/****************************************/

/* 
	Here's an example of string tokenizing without the use of strtok() or 
	strsep(). This is done pretty much on the fly, but with a little
	rearranging it can be made into two (or better yet one) function. The idea 
	is to take the string, and then use strcspn() to find the location of the 
	next token. Set that to null, return the shortened string. Then increment
	to one past that (the beginning on the next string) and repeat. 

	Keep in mind this method will modify the string, so if you need to preserve
	the original string, you will need to make a copy. A malloc()/strncpy() 
	pair will suffice, or if you have it use strdup(). 

	Manual pages for all the functions used here can be found at: 
		http://www.openbsd.org/cgi-bin/man.cgi
*/


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

void advancePastNull(char **tmp)
/*
	Adance to '\0', and then one past.
*/
{
	while(**tmp)
		(*tmp)++;
	(*tmp)++;
}

void parseAndPrint(FILE *fp, double *value)
/*
	Read each file from the file, print the details of the transaction,
	and the amount to value.
*/
{
	char buf[80], *tmp;
	tmp = buf;

	if(!fgets(buf, 80, fp)) {
		return;
	}

	tmp[strcspn(tmp, ",:")] = '\0';
	printf("%-15s", tmp);
	advancePastNull(&tmp);

	tmp[strcspn(tmp, ",:")] = '\0';
	(*value) -= atof(tmp);
	printf("$%10.2f", atof(tmp));
	advancePastNull(&tmp);

	tmp[strcspn(tmp, ",:")] = '\0';
	printf("  %-20s", tmp);
	advancePastNull(&tmp);

	tmp[strcspn(tmp, ",:")] = '\0';
	printf("%s", tmp);
}

int main(int argc, char **argv)
{
	FILE *fp;
	double value = 0.0;
	int i=0;
	if(argc<2) {
		printf("usage: %s <file>\n", argv[0]);
		return 0;
	}
	if(!(fp = fopen(argv[1], "r"))) {
		perror("error opening file");
		return 1;
	}
	for(i=0;i<70;i++) fputc('=', stdout); fputc('\n', stdout);
	printf("%-15s%-14s%-20s%s\n", "Date", "Amount", "Place", "For");
	for(i=0;i<70;i++) fputc('-', stdout); fputc('\n', stdout);
	while(!feof(fp)) {
		parseAndPrint(fp, &value);
	}
	for(i=0;i<70;i++) fputc('-', stdout); fputc('\n', stdout);
	printf("Your balance is currently $%.2f\n",value);
	for(i=0;i<70;i++) fputc('=', stdout); fputc('\n', stdout);
	fclose(fp);
	return 0;
}
