/*
 * Sara Sprenkle  10/13/04
 * example.c
 *
 * Example program: calculates the weekly salary for employees, given
 * a file of employee ids, payrate, and hours worked 
 *
 * Step 4: doing input/output, complete main function
 */

#include<stdio.h>

/* 
   Constants for overtime: 
   Get paid time and a half for working more than 40 hours
 */
#define OVERTIME_HOURS 40
#define OVERTIME_RATE 1.5

/* 
   Constants for double overtime:
   Get paid double for working more than 60 hours
*/
#define DOUBLE_OVERTIME_HOURS 60
#define DOUBLE_OVERTIME_RATE 2

/*
 * This function calculates and returns the salary for an employee.
 */
double calculateSalary( float pay_rate, float hours ) {
  int overtime_hours;
  // don't expect hours to be less than 0, but just in case...
  if( hours < 0 ) {
    return 0;
  }
  // handles the normal case
  if( hours <= OVERTIME_HOURS ) {
    return hours * pay_rate;
  }

  // at this point, we know that we must deal with overtime
  if( hours <= DOUBLE_OVERTIME_HOURS ) {
    overtime_hours = hours - OVERTIME_HOURS;
    return OVERTIME_RATE * pay_rate * overtime_hours + pay_rate * OVERTIME_HOURS;
  }
  
  // we're in the case with double overtime
  overtime_hours = hours - OVERTIME_HOURS;
  return DOUBLE_OVERTIME_RATE * pay_rate * overtime_hours + pay_rate * OVERTIME_HOURS;
}

int main() {
  FILE *inptr;
  double pay_rate, hours;
  int employee_id;
  /* value returned by fscanf, catch end of file */
  int error;
  double salary;

  /* open input file */
  inptr = fopen( "employee.dat", "r");
  
  if( inptr == NULL ) {
    fprintf( stderr, "Error opening file 'employee.dat'\n");
    exit(-1);
  }

  /* print header */
  printf("EMPLOYEE PAY\n\n");
  printf("Employee_ID  Pay Rate  Hours     Salary\n");
  printf("-----------  --------  -----  ------------\n");

  /* read data from input file (employee_id, pay_rate, hours_worked) */
  error = fscanf( inptr, "%d %lf %lf", &employee_id, &pay_rate, &hours);
  
  while( error != EOF ) {
    
    /* calculate the salary for the employee */
    salary = calculateSalary( pay_rate, hours );

    /* print the output for the employee */
    printf("%11d   $%5.2lf %7.2lf  $%10.2lf\n", employee_id, pay_rate, hours, salary);

    /* read in the next value */
    error = fscanf( inptr, "%d %lf %lf", &employee_id, &pay_rate, &hours);
  }

  /* close the file */
  fclose(inptr);

  return 0;

}