//	GenLib.C
//
//	By : Brian Lee
//  Date : 1999/12/22

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<process.h>

int nextchar(char);
int getpara(FILE *, char *);

int main()
{
	FILE *in, *out, *func;
	char ini_entry[200], member[20];
	unsigned int member_count, end = 0;

	if ((in = fopen("syscall.ini", "rt")) == NULL) {
		fprintf(stderr, "\nCannot open input file syscall.ini");
		return 1;
	}
	if ((func = fopen("scfunc.s", "w+t")) == NULL) {
		fprintf(stderr, "\nCannot open output file scfunc.c");
		return 1;
	}

	fprintf(func, "/* ScFunc.S \n   Generated by GENLIB.EXE */");
	fprintf(func, "\n\n\t.rdata\n\t.globl\tSysCallFptr");
	fprintf(func, "\nSysCallFptr:");
	member_count = 0;

	while(!feof(in))
	{
		if(!getpara(in, ini_entry)) break;

		sprintf(member, ".\\SRC\\SC%06d.S", member_count);
		if ((out = fopen(member, "w+t")) == NULL) {
			fprintf(stderr, "\nCannot open file %s", member);
			return 1;
		}

		fprintf(out, "/* Function %s()", ini_entry);
		fprintf(out, "\n   Generated by GENLIB.EXE */");
		fprintf(out, "\n\n#include \"include\\pr3910.h\"");
		fprintf(out, "\n#include \"include\\syscall.h\"");
		fprintf(out, "\n\n\n\t\t.text");

		fprintf(out, "\n\nSYSCALL(%s, %d)", ini_entry, member_count);
		fprintf(func, "\n.word\t%s", ini_entry);

		if(!getpara(in, ini_entry)) end = 1;
		else {
		    fprintf(out, "\nSYSCALL(%s, %d)", ini_entry, member_count+1);
			fprintf(func, "\n.word\t%s", ini_entry);
			if(!getpara(in, ini_entry)) end = 1;
			 else {
			    fprintf(out, "\nSYSCALL(%s, %d)", ini_entry, member_count+2);
				fprintf(func, "\n.word\t%s", ini_entry);
				if(!getpara(in, ini_entry)) end = 1;
				else {
				    fprintf(out, "\nSYSCALL(%s, %d)", ini_entry, member_count+3);
					fprintf(func, "\n.word\t%s", ini_entry);
				}
			}
		}
		fprintf(out, "\n");
		fclose(out);

		sprintf(ini_entry, "%s", member);
		sprintf(&ini_entry[100], ".\\OBJ\\SC%06d.O", member_count);
		spawnlp(P_WAIT, "gcc.exe", "gcc.exe", "-g", "-O2", "-G0", "-c", "-EL", "-o", &ini_entry[100], ini_entry, NULL);
		member_count+=4;
		if(end == 1) break;
	}

	printf("\n\nGenerating Library...");
	system("cd obj");
	spawnlp(P_WAIT, "ar.exe", "ar.exe", "-r", "..\\syscall.a", "*.o", NULL);
	system("cd..");
	printf("\nDone!\07\n\n");
	fcloseall();
	return 0;
}

int nextchar(char n)
{
    return(n==0x20 || n==0x09 || n==0x0d || n==0x0a);
}

int getpara(FILE *in, char *ini_entry)
{
    char *end = "#end";

	fscanf(in, "%s", ini_entry);
	if(!stricmp(ini_entry, end)) return 0;
    printf("\nProcessing function %s()", ini_entry);
    return 1;
}

