/* ******************************************************************************************************* */
/* parser funktionen returnerar olika värden beroende på vilka fel som inträffar. */
/* 0 - Success */
/* 1 - Syntax error */
/* 2 - wrong no. of arguments */
/* ***************************************************************************************************** */

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

#include "parser.h"
#include "../math/math.h"


int
parser (int argc, char **argv)
{
  int i;
  int j;
  int flag = 0;
  double val2 = atof(argv[3]);
  /* If-statements to return an error on invalid number of arguments */
  if (argc < 4)
    {
      fprintf(stderr, "Missing arguments\n");
      return 2;
    }
  else if (argc > 4)
    {
      fprintf(stderr, "Too many arguments\n");
      return 2;
    }
  
  /* If statment to check whether the operand is a valid character, AND that it is not comprised of multiple characters */
  if((argv[2][0] != '+' 
      && argv[2][0] != '-' 
      && argv[2][0] != 'x' 
      && argv[2][0] != '/' 
      && argv[2][0] != '%') 
     || strlen(argv[2]) > 1)
    {
      fprintf(stderr, "Invalid operator\n");
      return 1;
    }
  
  /* This nested loop reads each char in the strings argv[1] and argv[3], and throws an error on detection of a non-number char */
  for (i = 1; i < 4; i += 2)
    {
      flag = 0;

      for(j = 0; j < strlen(argv[i]); j++)
	{
	  if(argv[i][0] == '-' && argv[i][1] != '.' &&(argv[i][1] < '0' || '9' < argv[i][1])) /*checks whether the first character is a sign indicator AND if the second character is NOT a number*/
	    {
	      fprintf(stderr, "Syntax error in sign %s\n", argv[i]); /*throws a syntax error as it would imply a case such as {'1 + ----1'} being allowed*/
	      return 1;
	    } 
	  else if(((argv[i][j] < '0' || '9' < argv[i][j]) /* checks if current character in string is outside range [0-9] */
		   && argv[i][j] != '.') /* AND NOT A PERIOD (.) [this is to allow floating point numbers]*/ 
		  && argv[i][0] != '-')  /* but the first characteris NOT minus sign(-) */
	    {
	      fprintf(stderr, "Syntax error in %s\n", argv[i]);
	      return 1;
	    }
	  
	  if(argv[i][j] == '.')
	    {
	      flag++;
	    if (flag > 1)
	      {
		fprintf(stderr, "Too many decimal points!\n");
		return 1;
	      }
	    }
	}
      
    }

  if (zero_check(val2) == 1)
    {
      return 1;
    }
  
   /* if (atoi(argv[3]) == 0 && (argv[2][0] == '/' || argv[2][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 *\/ */
   /*  } */
  
  return 0;
}
