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

int count_args(char *args)
{
	int i;
	int count = 0;
	int length = strlen(args);
	int in_quote = 0;
	char chr;

	if(length > 0)
	{
		count ++;

		for(i = 0; i < length; i++)
		{
			chr = args[i];

			if(chr == '"')
			{
				if(in_quote == 0)
				{
					in_quote = 1;
				}
				else
				{
					in_quote = 0;
				}
			}
			else if(chr == ' ' && in_quote == 0)
			{
				count++;
			}
		}
	}

	return count;
}

char *extract_arg(char *args, int index)
{
	int i;
	char *sp;
	char *ep;
	char *arg = NULL;
	int in_quote = 0;
	char chr;
	
	int length = strlen(args);

	for(i = 0; i < length; i++)
	{
		if(index < 1)
		{
			break;
		}

		chr = args[i];

		if(chr == '"')
		{
			if(in_quote == 0)
			{
				in_quote = 1;
			}
			else
			{
				in_quote = 0;
			}
		}
		else if(chr == ' ' && in_quote == 0)
		{
			index--;
		}
	}

	sp = args + i;

	for(; i < length; i++)
	{
		chr = args[i];

		if(chr == '"')
		{
			if(in_quote == 0)
			{
				in_quote = 1;
			}
			else
			{
				in_quote = 0;
			}
		}
		else if(chr == ' ' && in_quote == 0)
		{
			index--;
		}

		if(index < 0)
		{
			break;
		}
	}

	ep = args + i;

	length = ep - sp;

	arg = (char *)malloc(sizeof(char) * (length + 1));
	
	strncpy(arg, sp, length);
	
	arg[length] = '\0';

	return arg;
}

char *strip_quotes(char *param)
{
	int length = strlen(param);
	int j = 0;
	int i;

	for(i = 0; i < length; i++)
	{
		if(param[i] != '"')
		{
			param[j++] = param[i];
		}
	}

	param[j] = 0x00;
	
	return param;
}