#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 integer */
  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 ('/'):
      /* printf("%f\n", (float)val1/(float)val2); */
      zero_check(val2);
      return val1 / val2;

      break;
      
    case ('x'):
      return val1 * val2;
      break;
      
    case('%'):
      if ((zero_check(val2)) == 1)
	{
	  return 1;
	}
      return (int)val1 %  (int)val2;
      break;
   } 
  
   return 0; /* den här raden ska inte kunna exekveras om allt har gjorts rätt */
             /* men kompilatorn kräver den ändå */
}

int zero_check(double val2)
{
  if ((val2) == 0.0) /*check to see whether we are dividing by zero, by converting the 3rd arg to an int and comparing to zero. We also make sure that this is only checked when the operator is either '/' or '%' */
    {
      printf("Math error (division by zero)\n");
      return 1; /* returns a syntax error */
    }
    else
      {
	return 0;
      }
}


