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

#include "math.h"

double
math(int argc, char **argv)
{
  /* Converts the input values from string to double */
  double val1 = atof(argv[1]);
  double val2 = atof(argv[3]);
   
  switch (argv[2][0])  /* switch to select the appropriate math function based on the operator */
    {
      
    case('+'):
      return val1 + val2;
      break;
      
    case('-'):
      return val1 - val2;
      break;
      
    case ('/'):
      float_zero_check(val2); /* calls function below to check if the float equivalent of the second input value is equal to zero */
      return val1 / val2;
      break;
      
    case ('x'):
      return val1 * val2;
      break;
      
    case('%'):
      
      int_zero_check((int)val2); /* checks if the newly converted value is inadvertently rounded down to zero */
      
      /* printf("%d\n", (int)val2); */
      return (int)val1 %  (int)val2;
      break;
    } 
  
  

   return 0;
}




int
int_zero_check(int val2)
{
  if (val2 == 0) 
    {
      fprintf(stderr, "Math error (division by zero) in modulo operation\n");
      exit(3); /* gives a math error (3) */
    }
  else
    {
      return 0;
    }
}

int 
float_zero_check (double val2)
{
  if ((val2) == 0.0)   
    {
      fprintf(stderr, "Math error (division by zero)\n");
      exit(3); /* exits immediately with a math error value (3) */
    }
  else
    {
      return 0;
    }
}




