/*
 * UNICODE support for Screws.
 * - $FILE
 */

#include "modskel.h"
MODULE_TYPE(MTYPE_EXEC)
MODULE_NAME("Unicode");
MODULE_VERS("0.4");

#define INITSTR " -> Unicode support by pancake - 20/08/2003.\n"

/* code from http://howstuffworks.lycoszone.com/survey.c */
char upcase(char c)
{
	if (c >= 'a' && c <= 'z') c -= 32;
	return c;
}
int hex2dec(char c)
{
	if (c >= '0' && c <= '9')
		return (int) c - '0';
	c = upcase(c);
	if (c >= 'A' && c <= 'F')
			return (int) (10 + c - 'A');
	else	return 0;
}
void ParseUnicode(char *s)
{
	char *t;
	int i=0, j=0;
	
	t=(char *)malloc(strlen(s)+1);
	while(s[i] != '\0')
	{
		if (s[i] == '+')
		{	t[j++] = ' '; i++; }
		else if (s[i] != '%')
			t[j++] = s[i++];
		else
		{
			t[j] = hex2dec(s[i+1]) * 16 + hex2dec(s[i+2]);
			if (t[j] == 10 || t[j]==13) t[j]=' ';
			j++; i+=3;
		}
	}
	t[j++] = '\0';
	strcpy(s,t);
}

/* Screws CODE */

bool init() 
{ 
	MODULE_INIT();
	return true;
}

bool exec(char **opts)
{
	char *argv,*arg;
	char *str;
	int i=0,j;

	str=(char *)getenv("FILE");
	if (!str) return false; /* FILE not defined */
	ParseUnicode(str);

	argv=(char *)getenv("ARGV");
	if (!str) return false; /* ARGV not defined */

	while(argv[i])
	{
		if (argv[i]!=' ')
		{
		  for(j=i;argv[j]!=' '&&argv[j];j++); argv[j]=0;
		  arg=(char *)getenv(argv+i);
			argv[j]=' ';
		  if (!arg) return false; /* ARG_XXX not defined */
		  ParseUnicode(arg);
		  i=j+1; /* jump next word */
		} else
		  i++;
	}

	ParseUnicode(str);
	return false;
}
