/* This program takes as an argument a file containing bills.  It adds
 * up and prints the total amount of money spent in each category
 * The format of the file containing bills: <item> <category> <price>
 * There may be more than one space between each field.
 */

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

#define MAXLINE 256
#define NUMCATEGORIES 4

float get_price(char *line);
int match(char *line, char *category);


int
main(int argc, char *argv[]) 
{
    FILE *fp;
    char line[MAXLINE];
    char *categories[] = {"food", "clothes", "entertainment", "other"};
    float sum[] = {0.0, 0.0, 0.0, 0.0};
    int found, i;

    if(argc != 2) {
	fprintf(stderr, "Usage: expenses <file>\n");
	exit(1);
    }

    if( (fp = fopen(argv[1], "r")) == NULL ) {
	fprintf(stderr, "Error: Could not open %s\n", argv[1]);
	exit(1);
    }

    /* For each line of the bills file figure out which category it
       belongs to, and add the item's price to the sum for that cateogry */

    while(fgets(line,sizeof(line),fp)!=NULL) {

	found = 0;
	for(i = 0; i < NUMCATEGORIES; i++) {
	    if(match(line, categories[i])) {
		found = 1;
		sum[i] += get_price(line);
		break;
	    }
	}
	
	if(!found) {
	    sum[NUMCATEGORIES - 1] += get_price(line);
	}

    }

    for(i = 0; i < NUMCATEGORIES; i++) {
	fprintf(stdout, "%s\t%.2f\n", categories[i], sum[i]);
    }
}

/* match finds the category as the second word in line and returns
 * 1 if the category in line is the same as category, or 0 otherwise
 */

/* Challenge: How would you change this code to allow a variable number
 * of words before the category in line?
 */

int
match(char *line, char *category) {
    char *ptr  = index(line, ' ');
    
    while(*ptr == ' ' || *ptr == '\t') 
	ptr++;
    /* ptr now points to the beginning of the category part of the line*/

    if((strncmp(ptr, category, strlen(category))) == 0) {
	return 1;
    } else {
	return 0;
    }
}

/* get_price returns the price found at the end of line */

float
get_price(char *line) 
{
    char *ptr = rindex(line, ' ');
    
    if(ptr != NULL) {
	return(strtod(ptr, NULL));
    } else {
	return(-1.0);
    }
}
/********************************
 * This is the file. You may test
 * on it.
 ********************************
 *burger  food           5.50
 *movie   entertainment 12.00
 *milk    food           3.99
 *jacket  clothes       50.00
 *t-shirt clothes       10.00
 ********************************/
