/*
 * Copyright (c) 1998-2005 Servertec. All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * THIS NOTICE MUST NOT BE ALTERED NOR REMOVED.
 *
 * CopyrightVersion 1.0
 */

#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;
}