// ex_ch7_8.c
#include <stdio.h>
#include <stdbool.h>

const float PAY_FIRST = 300.0;
const float PAY_SECOND = 150.0;
const float TAX_FIRST = 0.15;
const float TAX_SECOND = 0.20;
const float TAX_REST = 0.25;
const int OVERTIME_START = 40;
const float OVERTIME_MULTI = 1.5;
const char* STARS = "******************************" \
"***********************************\n";

char get_selection(void);
char get_first(void);
int get_int(void);

int main(void)
{
	float base_rate;
	int hours_worked;
	int overtime = 0;
	float overtime_hours, overall_hours, gross_pay;
	float taxes = 0;
	float rest;
	char selection;

	while (true)
	{
		printf("%s", STARS);
		printf("Enter the number corresponding to the desired pay rate or action:\n");
		printf("a) $8.75/hr\t\t\tb) $9.33/hr\n");
		printf("c) $10.00/hr\t\t\td) $11.20/hr\n");
		printf("q) quit\n");
		printf("%s", STARS);
		selection = get_selection();
		
		switch (selection)
		{
		case 'a':
			base_rate = 8.75;
			break;
		case 'b':
			base_rate = 9.33;
			break;
		case 'c':
			base_rate = 10.00;
			break;
		case 'd':
			base_rate = 11.20;
			break;
		case 'q':
			return 0;
		}
		
		printf("Enter the number of hours you worked: ");
		hours_worked = get_int();

		if (hours_worked >= OVERTIME_START)
		{
			overtime = hours_worked - OVERTIME_START;
		}
		overtime_hours = overtime * OVERTIME_MULTI;
		// all what should be paid
		overall_hours = hours_worked + overtime_hours;

		gross_pay = overall_hours * base_rate;
		printf("Gross pay $%.2f\n", gross_pay);

		if (gross_pay <= PAY_FIRST)
		{
			taxes = gross_pay * TAX_FIRST;
		}
		else if (gross_pay > PAY_FIRST && gross_pay <= PAY_FIRST + PAY_SECOND)
		{
			taxes = PAY_FIRST * TAX_FIRST;
			rest = gross_pay - PAY_FIRST;
			taxes += rest * TAX_SECOND;
		}
		else
		{
			// calculate the base tax
			taxes = PAY_FIRST * TAX_FIRST;
			// add the secondary tax which is always 150
			taxes += PAY_SECOND * TAX_SECOND;
			// calculate the rest, which is over 450 and get the tax
			rest = gross_pay - (PAY_FIRST + PAY_SECOND);
			taxes += rest * TAX_REST;
		}
		// output what we got
		printf("Taxes $%.2f\n", taxes);
		printf("Net pay $%.2f\n", gross_pay - taxes);
	}

	return 0;
}

char get_selection(void)
{
	char ch;
	while (true)
	{
		ch = get_first();
		if ((ch >= 'a' && ch <= 'd') || ch == 'q')
			return ch;
	}
}

char get_first(void)
{
	int ch;
	// get the first non-newline character, save it in ch
	while ((ch = getchar()) && isspace(ch))
 		continue;
 	
	// skip all the other characters until the newline
	while (getchar() != '\n')
		continue;
	
	// return the first non newline character
	return ch;
}

int get_int(void)
{
	int input;
	char ch;
	
	while (scanf("%d", &input) != 1)
	{
		while ((ch = getchar()) != '\n')
			// dispose of bad input
			putchar(ch);
		printf(" is not an integer.\n"
		       "Please enter an integer value, such as 25, -178, "
		       "or 3: ");
	}
	return input;
}
