#include "common.h"
#include <vdr/tools.h>
#include <stdlib.h>
#include <string.h>

char *strnadup(const char *str, int len)
{
	char *res = (char*)malloc(len);
	strncpy(res, str, len);
	return res;
}

char **SplitParameters(const char *String, int Count, bool ForceCount)
{
	char **result = new char*[Count + 1];
	const char *ptr = String, *end;
	int cnt = 0;

	memset(result, 0, sizeof(char*) * (Count + 1));

	while (cnt < Count && *ptr != '\0') {
		if (*ptr == '\'') {
			end = ptr + 1;
			while ((end = strchr(end, '\'')) != NULL && *(end - 1) == '\\')
				++end;
			
			if (end == NULL) {
				esyslog("ERROR: Communication with scripting host broken: "
				        "couldn't find matching >'< in '%s'", String); 
				break;
			}
			result[cnt] = strndup(ptr + 1, end - ptr - 1);

			char *tmp = result[cnt];
			while ((tmp = strchr(tmp, '\\')) != NULL) {
				switch (*(tmp + 1)) {
				case 'n': *(tmp + 1) = '\n'; // fall through
				default:  memmove(tmp, tmp + 1, strlen(tmp) + 1);
				}
				++tmp;
			}
				
			if (*(end + 1) == ' ') ++end;
			ptr = end + 1;
		} else if (strn2cmp(ptr, "(nil)") == 0) {
			result[cnt] = NULL;
			ptr += strlenc("(nil)");
			if (*ptr == ' ') ++ptr;
		} else if ((end = strchr(ptr, ' ')) != NULL) {
			result[cnt] = strndup(ptr, end - ptr);
			ptr = end + 1;
		} else {
			result[cnt] = strdup(ptr);
			ptr += strlen(ptr);
		}
		++cnt;
	}
	if (*ptr != '\0') {
		result[cnt] = strdup(ptr);
	}
	if (ForceCount && cnt != Count) {
		esyslog("ERROR: Communication with scripting host broken: "
		        "Too few parameters, expected %d in '%s'", Count, String);
		FreeParameters(result, Count);
		return NULL;
	}
	return result;
}

void FreeParameters(char **Array, int Count) 
{
	for (int i = 0; i < Count + 1; ++i)
		free(Array[i]);
	delete[] Array;
}
