#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

#define MAXLINE 100
#define MAX 100

char *cmdarg[];
char cmdbuf[MAX];

/* 
 * parseline - Parse the command line and build the argv array.
 * 
 * Characters enclosed in single quotes are treated as a single argument.  
 */

void parseline(const char *cmdline, char **argv) 
{
    static char array[MAXLINE]; /* holds local copy of command line */
    char *buf = array;          /* ptr that traverses command line */
    char *delim;                /* points to first space delimiter */
    int argc;                   /* number of args */

    strcpy(buf, cmdline);
    buf[strlen(buf)-1] = ' ';  /* replace trailing '\n' with space */
    while (*buf && (*buf == ' ')) /* ignore leading spaces */
	buf++;

    /* Build the argv list */
    argc = 0;
    if (*buf == '\'') {
	buf++;
	delim = strchr(buf, '\'');
    }
    else {
	delim = strchr(buf, ' ');
    }

    while (delim) {
	argv[argc++] = buf;
	*delim = '\0';
	buf = delim + 1;
	while (*buf && (*buf == ' ')) /* ignore spaces */
	       buf++;

	if (*buf == '\'') {
	    buf++;
	    delim = strchr(buf, '\'');
	}
	else {
	    delim = strchr(buf, ' ');
	}
    }
    argv[argc] = NULL;
}


int main()
{
	int ret;
	while(1)
	{
		// Print Prompt
		printf("\ntsh> ");
		fflush(stdout);

		// Obtain Input
		fgets(cmdbuf, MAX, stdin);
		if((strcmp("quit\n", cmdbuf) == 0))
			exit(0);
		// Parse
		parseline(cmdbuf, cmdarg);
		// Create Process and Execute
		ret = fork();
		if(ret == 0)
		{
			execvp(*cmdarg, cmdarg);
			printf("\nChild Process Completed\n");
		}
		else
		{
			wait(0);
			printf("\nParent Process Completed\n");
		}
	}
}
