#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)
{
  
  args.char_opt = 0;
  args.line_opt = 0;  /*initialize default values*/
  args.fp = stdin;
  
  args.arg0 = argc; 
  
  switch (argc)
    {
    case 1:
      readCharacter(args);
      break;
      
    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:
      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:
      return ARG_LIMIT_EXCEEDED;
      break;
    }

  return 0;
}
