#include <stdio.h>
#if defined(macintosh)||defined(WIN32)
#	include <io.h>
#endif
#include <fcntl.h>
#include <stdlib.h>
#ifdef macintosh
#	include <console.h>
#	define MAIN_T int
#endif
#if defined(WIN32)
#	define WIN32_LEAN_AND_MEAN
#	include <windows.h>
#	define IMPORT(typ,fnc,arg) __declspec(dllimport) typ fnc arg
#	define MAIN_T void
#endif
#ifndef IMPORT
#	define IMPORT(typ,fnc,arg) typ fnc arg
#endif
#ifndef MAIN_T
#	define MAIN_T int
#endif
#ifndef	NO_MEMORY_TTFONTS
static	void	*_read_file(char* fn, int *plen)
{
	char	*buf=NULL;
	size_t	len;
	int		n;
	FILE	*f = fopen(fn,"rb");
	if(!f || fseek(f,0,SEEK_END)){
fail:	fprintf(stderr,"failed to readfile %s\n", fn);
		if(f) fclose(f);
		if(buf) free(buf);
		exit(1);
		}
	len = ftell(f);
	fseek(f,0,SEEK_SET);
	if(!(buf=malloc(len))) goto fail;

	n = fread(buf,(int)len,1,f);
	if(n!=1) goto fail;
	fclose(f);
	*plen = (int)len;
	return (void*)buf;
}
#endif

typedef struct {
		char*	errorString;
		int		resultStringLength;
		char*	resultString;
		int		uncaughtError;
		} rl_embed_rt;
IMPORT(rl_embed_rt, rl_run_file,(char*));
IMPORT(rl_embed_rt,rl_run_string,(char*));
#ifndef	NO_MEMORY_TTFONTS
IMPORT(rl_embed_rt,rl_register_ttfont,(char*,char*,int));
#endif
MAIN_T main(int argc, char** argv)
{
	rl_embed_rt r;
#ifndef	NO_MEMORY_TTFONTS
	char	**ARGV = (char**)malloc(argc*sizeof(char*));
	int		ARGC, i, buflen;
	char	*ttfname, *ttfpath;
	void	*buf;
#else
#	define ARGV argv
#	define ARGC	argc
#endif
#ifdef macintosh
	argc = ccommand(&argv);
#endif
#ifndef	NO_MEMORY_TTFONTS
	ARGV[0] = argv[0];
	for(ARGC=i=1;i<argc;i++){
		if(!strncmp(argv[i],"-ttf=",5)){
			ttfname = argv[i]+5;
			ttfpath = strchr(ttfname,',');
			if(!ttfname || !ttfpath){
				fprintf(stderr,"Bad ttf specification \"%s\"\n", argv[i]);
				goto fail;
				}
			*ttfpath++ = 0;
			buf = _read_file(ttfpath,&buflen);
			r = rl_register_ttfont(ttfname, (char*)buf, buflen);
			free(buf);
			if(r.errorString){
				fprintf(stderr,"Uncaught=%d\nERROR: %s\n",r.uncaughtError,r.errorString);
				exit(1);
				}
			fprintf(stderr,"rl_register_ttfont(\"%s\",FILE(\"%s\"), %d)\n", ttfname, ttfpath, buflen);
			fwrite( r.resultString, 1, r.resultStringLength, stdout);
			}
		else{
			ARGV[ARGC++] = argv[i];
			}
		}
#endif

#ifdef macintosh
	if(ARGC < 3) {
#ifndef	NO_MEMORY_TTFONTS
fail:	fprintf(stderr, "Use %s [-ttf=name,path] script out.eps\n", ARGV[0]);
#else
fail:	fprintf(stderr, "Use %s script out.eps\n", ARGV[0]);
#endif
		exit(1);
		}
	freopen(argv[2], "wb", stdout);
#else
#	ifdef WIN32
	_setmode(_fileno(stdout),_O_BINARY);
#	endif
	if(ARGC<2){
#ifndef	NO_MEMORY_TTFONTS
fail:	fprintf(stderr,"Use %s [-ttf=name,path] script >out.eps\n", ARGV[0]);
#else
fail:	fprintf(stderr,"Use %s script >out.eps\n", ARGV[0]);
#endif
		exit(1);
		}
#endif
	r = rl_run_file(ARGV[1]);
	if(r.errorString){
		fprintf(stderr,"ERROR: %s\n",r.errorString);
		exit(1);
		}
	fwrite( r.resultString, 1, r.resultStringLength, stdout);
}
