/******************************************************************************
 *    GetParamObject.cpp
 *
 *    This file is part of Object Script Library
 *    Copyright (C) 2005-2009 Tom N Harris <telliamed@whoopdedo.org>
 *
 *    Permission is hereby granted, free of charge, to any person obtaining
 *    a copy of this software and associated documentation files (the 
 *    "Software"), to deal in the Software without restriction, including 
 *    without limitation the rights to use, copy, modify, merge, publish, 
 *    distribute, sublicense, and/or sell copies of the Software, and to 
 *    permit persons to whom the Software is furnished to do so.
 *    
 *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
 *    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
 *    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-
 *    INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 
 *    BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN 
 *    AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
 *    IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *    THE SOFTWARE.
 *
 *****************************************************************************/

#include "ScriptLib.h"

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

extern const char* g_pszParamDelim;
extern const char* g_pszQuotes;

int GetParamObject(const char* pszString, const char* pszParam, int iDefault)
{
	if (!pszString || !pszParam)
		return iDefault;
	char* pszRet = NULL;
	char* pszTemp = reinterpret_cast<char*>(alloca(strlen(pszString)+1));
	if (!pszTemp)
		return 0;
	strcpy(pszTemp, pszString);
	char* pszSep, *pszToken;
	for (pszSep = pszTemp, pszToken = strqsep(&pszSep, g_pszParamDelim, g_pszQuotes); 
	     pszToken; pszToken = strqsep(&pszSep, g_pszParamDelim, g_pszQuotes))
	{
		while (isspace(*pszToken)) ++pszToken;
		char* pszStart = strchr(pszToken, '=');
		if (pszStart)
			*pszStart++ = '\0';
		if (!stricmp(pszToken, pszParam))
		{
			if (!pszStart)
				break;
			while (isspace(*pszStart)) ++pszStart;
			if (*pszStart == '"' || *pszStart == '\'')
			{
				char quote = *pszStart++;
				char* pszEnd = strrchr(pszStart, quote);
				if (!pszEnd)
					pszEnd = pszStart + strlen(pszStart);
				char* pszChar = pszRet = pszStart;
				while (pszStart < pszEnd)
				{
					if (*pszStart == '\\' && 
					    (pszStart[1] == '\\' || pszStart[1] == quote))
					{
						++pszStart;
					}
					*pszChar++ = *pszStart++;
				}
				*pszChar = '\0';
			}
			else
			{
				int iLen = strlen(pszStart);
				pszRet = pszStart;
				pszRet[iLen] = '\0';
			}
			break;
		}
	}
	int iRet = (pszRet) ? StrToObject(pszRet) : iDefault;
	return iRet;
}
