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

#include "parser.h"
#include "../readCharacter/readCharacter.h"
#include "../openFile/openFile.h"

int 
parser (cmd_args args, int argc, char **argv)
{
   /*initialize default values*/ 
  args.char_opt = 0;
  args.line_opt = 0;
  args.fp = stdin;
  
  args.arg0 = argc; 
  
  /* Switch-case begins here */
  switch (argc)
    {
    case 1:
      readCharacter(args);
      break;
      /***************************************************     Case 2     *************************/   
    case 2:
      if (strlen(argv[1]) > 255)
	{
	  return ERR_CHAR_LENGTH;
	}
      
      strcpy(args.arg1, argv[1]);
      
      if (!strcmp(args.arg1, "-"))
	{	
	  strcpy(args.filename, args.arg1);
	  readCharacter (args);
	}	
      
      else if (!strcmp(args.arg1, "-l") || (!strcmp(args.arg1, "--lines")))
	{
	  args.line_opt = 1;
	  readCharacter (args);
	}
      else if (!strcmp(args.arg1, "-c") || (!strcmp(args.arg1, "--chars")))
	{
	  args.char_opt = 1;
	  readCharacter (args);
	}
      else 
	{
	  openFile(args);
      	}
      break;
      /*************************************************      Case 3      ******************************/
    case 3:
      if (strlen(argv[1]) > 255 || strlen(argv[2]) > 255)
	{
	  return ERR_CHAR_LENGTH;
	}
      
      strcpy(args.arg1, argv[1]);
      strcpy(args.arg2, argv[2]);
      
      if (!strcmp(args.arg1, "-c") || 
	  !strcmp(args.arg1, "--chars") )
	{
	  args.char_opt = 1;
	  
	  if (!strcmp(args.arg2, "-"))
	    {
	      strcpy(args.filename, args.arg2); 
	      readCharacter(args);
	    }
	  else
	    openFile(args);
	}
      else if (!strcmp(args.arg1, "-l") 
	       || !strcmp(args.arg1, "--lines" ))
	{
	  args.line_opt = 1;
	  
	  if (!strcmp(args.arg2, "-"))
	    {
	      strcpy(args.filename, args.arg2); 
	      readCharacter(args);
	    }
	  else
	    openFile(args);
	}
      else
	return INVALID_FILE_OR_ARG;	
	
      break;
      /*****************************************************     Default          *****************************/
    default:
      return ARG_LIMIT_EXCEEDED;
      break;
    }

  return 0;
}
