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

#include "parser.h"

int
parser (int argc, char **argv)
{
  int i;
  int j;
  int MULTIPLE_PERIOD_FLAG = 0;

  /* If-statements to exit with an error on invalid number of arguments */
  if (argc < 4)
    {
      fprintf(stderr, "Missing arguments\n");
      exit(2);
    }
  else if (argc > 4)
    {
      fprintf(stderr, "Too many arguments\n");
      exit(2);
    }


  
  /* If statement to check whether the operand is a valid character, AND that it is not multiple characters in length */
  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");
      exit(1); 
    }


  
  /* This nested loop reads each char in the strings argv[1] and argv[3], and tests them in three phases */
/*   1 - detects and handles multiple minus signs */
/*   2 - filters for any forbidden characters (anything not a number, minus sign or period) */
/*   3 - detects multiple periods in a string */
  for (i = 1; i < argc; i += 2)
    {

      MULTIPLE_PERIOD_FLAG = 0; /* reinitialize period(.) counter for each new string  */

      for (j = 0; j < strlen(argv[i]); j++)
	{
	  if (argv[i][0] == '-' /* EXITS if the first character is a minus sign */
	     && (argv[i][1] != '.' 
		 && (argv[i][1] < '0' || '9' < argv[i][1]))) /* AND that the second character is NEITHER a number (0-9) NOR a period (.)*/
	    {
	      fprintf(stderr, "Syntax error in sign %s\n", argv[i]); /*prevents cases such as {'1 + ----1'} being allowed*/
	      exit(1);
	    } 
	  
	  else if (((argv[i][j] < '0' || '9' < argv[i][j]) /* EXITS if current character is NEITHER a number [0-9] */
		   && argv[i][j] != '.') /* NOR a period (.) */ 
		  && argv[i][j] != '-')  /* NOR a minus sign(-) */
	    /* This effectively excludes all other characters */
	    {
	      fprintf(stderr, "Syntax error in %s\n", argv[i]);
	      exit(1);
	    }
	  
	  if (argv[i][j] == '.') /* Detects and EXITS on multiple periods(.) in the same string */
	    {
	      MULTIPLE_PERIOD_FLAG++;
	    if (MULTIPLE_PERIOD_FLAG > 1)
	      {
		fprintf(stderr, "Too many decimal points\n");
		exit(1);
	      }
	    }
	}
    }
  
  return 0;
}




