#include "main.h"

char *b; /* global variable */

int
main(int argc, char *argv[])
{
	long len;
	FILE *fd;
	char *file=0;
	int i;
	bool donotchdir=0;
	bool standard=0;

	extern void hsml_init();
	hsml_init();

	for(i=1;i<argc;i++)
	{
		if (!strcmp(argv[i],"-x"))
		{	donotexec=1;         }
		else
		if (!strcmp(argv[i],"-h"))
		{   file=0; break;       }
		else
		if (!strcmp(argv[i],"-n"))
		{   donotchdir=1;        }
		else
		if (!strcmp(argv[i],"-s"))
		{   standard=1;			}
		if (!strcmp(argv[i],"-l"))
		{
			extern void show_lang_config();
			show_lang_config();
			exit(0);
		}
		else
		if (!strcmp(argv[i],"-I"))
		{	if (++i==argc) 
			{ file=0; break;     }
			dip=argv[i];		 }
		else file=argv[i];
	}

	/* ShowUsage */
	if (!file)
	{ 
		printf( "HSML v%s - HyperScriptMarkupLanguage.\n"
			"> Usage '%s' [ -h | [-x] filename ]\n"
			"  -h        - help\n"
			"  -I [path] - Specify another include path\n"
			"  -x        - Do not exec, only stdout (debug?)\n"
			"  -n        - Do not chdir to the file path\n"
			"  -l        - List all bin paths\n"
			"  -s        - Use stdxxx instead of pipe everything to stdout\n"
			"  => for '.xx.html' uses the new parser.\n"
			"  => DefaultIncludePath: %s[include.xx]\n"
			"  => DefaultExecutionPath: %s\n",VERSION, argv[0],DIP,DEP);
		return 1; 
	}

	if (!standard) // default option
	{
		close(2);
		dup2(1,2);
	}

	/* Fopen file */
	if (strcmp(file,"-"))
	{
		fd=fopen(file,"r");
		if (!fd) { perror("fopen"); return(1); }
	} else {
		printf("TODO: stdin reading not yet supported.\n");
		fd = stdin;
	}

	/* Get File Size */
	fseek(fd,0,SEEK_END);
	len=ftell(fd);
	fseek(fd,0,SEEK_SET);

	/* Map on memory */
	b=(char *)calloc(1,len+1);
	fread(b,len,1,fd);

	for(i=strlen(file);i&&file[i]!='/';i--);
	if (i) 
	{
		file[i]=0;
		if (!donotchdir)
		{
			chdir(file);
		}
		file[i]='/';
		file=file+i+1;
	}

	/* Show */
	setenv("TMP",".",0);

	if (!subLang(file,len)) /* new release */
	{
		printHeaders();
		execHsml(&b,len);
	}

	/* End Of Life */
	//free(b); /* some freedom is perjudicial. Not needed */
	fclose(fd);
	return (0);
}
