#include "ObjProGen/cpyrght_exe.h"
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <ctype.h>
#ifdef __NT_VC__
#include <io.h>
#endif

void myexit(int n)
{
	fprintf(stderr,"error %d\n",n);
	exit(n);
}

char * ConvertName (const char * name)
{
	const char * Result;
	const char  * R ;
	char c;
	Result = R = name ;
	while (c= *R++) {
		if (c == '/') Result = R;
	}
	name = Result ;
	char * R1 ;
	char * Result1 ;
	R1 = Result1 = (char *) malloc (strlen(name)+5);
	while (c= *name++) {
		if (!isascii(c)) continue ;
		if (c == '.' ) {
			*R1++ = '_' ;
			*R1++ = 'D' ;
			*R1++ = 'O' ;
			*R1++ = 'T' ;
			*R1++ = '_' ;
		} else {
			if (!islower(c)) *R1++ = c;
			else *R1++ = toupper(c) ;
		}
	}
	*R1++ = '\0' ;
	return Result1 ;
}
#define BUF_SIZE 1024
#define NAM_BUF_SIZE 256

void main(int argc,char ** argv)
{
FILE * in, * out;
char * ConvertedName ;
char buf[BUF_SIZE];
char nambuf[NAM_BUF_SIZE];
char * ExitStatus ;
int DefineNotOut ;
int code ;
int LineCount;

	if (argc != 2) myexit(1);
	if (strlen(argv[1]) > NAM_BUF_SIZE - 32) myexit(2);
	ConvertedName = ConvertName(argv[1]);
	in = fopen(argv[1],"r");
	sprintf(nambuf,"#define %s\n", ConvertedName) ;
	if (!in) {
		perror("nametrans");
		myexit(1);
	}
	while (ExitStatus = fgets(buf,BUF_SIZE,in)) {
		/* fprintf(stderr,"%s",buf); */
		if (!strcmp(buf,nambuf)) break;
	}
	if (ExitStatus) {
		fputs(argv[1],stdout); /* return original file name */
		myexit(0) ;
	}
	sprintf(nambuf,"/tmp/hd.XXXXXX");
	mktemp(nambuf);
	out=fopen(nambuf,"w");
	code=fseek(in,(long) 0, 0);
	if (code) {
		fprintf(stderr,"fseek error %d\n",code);
		myexit(6);
	}
	/* fprintf(stderr,"Done seek\n"); */
	DefineNotOut = 1;
	LineCount=0;
	for(;;) {
		ExitStatus = fgets(buf,BUF_SIZE,in) ;
		LineCount++;
		if (!ExitStatus) break ;
		/* fprintf(stderr,"%s",buf); */
		if (strlen(buf) > NAM_BUF_SIZE -3) myexit(4);
		if (DefineNotOut ) for (;;) {
			if ( (buf[0] == '/') && (buf[1] == '/') ) break ;
			if (!strcmp(buf,"\n")) break;
			DefineNotOut = 0 ;
			fprintf(out,"#ifndef %s\n#define %s\n",ConvertedName,
				ConvertedName);
			/* fprintf(out,"#line %d \"%s\"\n",LineCount,argv[1]);*/
			break;
		}
		fputs(buf,out) ;
	}
	if (DefineNotOut) myexit(5);
	fprintf(out,"#endif /* #ifdef %s */\n",ConvertedName);
	fputs(nambuf,stdout);
}
