#include <stdio.h>
#include <string.h>
#include <direct.h>
#include <process.h>
#include <io.h>

#define BUFSIZE 133

int main(int argc, char** argv)
{
	char *ptr;
	char filename[80];
	char ifilename[80] = { 0, 0};
	char ofilename[80];
	FILE *ifile, *ofile;
	char inbuf[BUFSIZE];
	char outbuf[BUFSIZE];
	char command[BUFSIZE];
	extern char* basename();

	long findout;
	struct _finddata_t fileinfo;
	findout = _findfirst("*.elf", &fileinfo);
	strcpy(filename, fileinfo.name);
	ptr = filename;
	while(*ptr++ != '.');
	*--ptr = (char)NULL;
	sprintf(command, "c:\\usr\\bin\\m6811-elf-nm.exe %s.elf > %s.sss", filename, filename);
	system(command);

	strcpy(ifilename, filename);
	strcpy(ofilename, ifilename);
	strcat(ifilename, ".sss");
	strcat(ofilename, ".sym");

	if ((ifile = fopen(ifilename, "r")) == NULL) {
		fprintf(stderr, "%s [%d]: Can not open file %s for read", basename(__FILE__), __LINE__, ifilename);
		perror(" ");
		exit(2);
	};

	if ((ofile = fopen(ofilename, "w")) == NULL) {
		fprintf(stderr, "%s[%d]: Can not open file %s for write", basename(__FILE__), __LINE__, ofilename);
		perror(" ");
		exit(3);
	};

	if (fgets(inbuf, BUFSIZE, ifile) != NULL) /* skip first line */
		while (fgets(inbuf, BUFSIZE, ifile) != NULL)
		{
			strtok(inbuf, " ");		// skip addr
			strtok(NULL, " ");		// skip type
			ptr = strtok(NULL, " \n");	// get name
			strcpy(outbuf, ptr);	// copy name to output buffer
//			strcat(outbuf, "   ");	// add spaces as delimiter
			strcat(outbuf, " ");	// add space as delimiter
			strcat(outbuf, &inbuf[4]);	// copy address
			strcat(outbuf, "\n");	// append newline	

			if (fputs(outbuf, ofile) == EOF)	// write the line
			{
				fprintf(stderr, "%s[%d]: Can not write to file %s", basename(__FILE__), __LINE__, ofilename);
				perror(" ");
				fclose(ifile);
				fclose(ofile);
				exit(5);
			}
		}

		if (ferror(ifile))
		{
			fprintf(stderr, "%s [%d]: Can not read file %s", basename(__FILE__), __LINE__, ifilename);
			perror(" ");
			fclose(ifile);
			fclose(ofile);
			exit(7);
		}
		
		fclose(ifile);
		fclose(ofile);

		if( _unlink(ifilename) == -1 ) {
			sprintf(outbuf, "Could not delete %s", ifilename);
			perror(outbuf);
			exit(9);
		}

		strcpy(ofilename, "Ep2IDE.txt");

		if ((ofile = fopen(ofilename, "w")) == NULL) {
			fprintf(stderr, "%s [%d]: Can not open file %s for write", basename(__FILE__), __LINE__, ofilename);
			perror(" ");
			exit(2);
		};

		fprintf(ofile, "%s\n", _getcwd(ifilename, sizeof(ifilename)));
		fprintf(ofile, "%s\n", filename);
		fprintf(ofile, "COM1\n2 = 68HC11E0,E1,E9,E20\nEVBplus2jr\n");
		fclose(ofile);
		system("copy Ep2IDE.txt C:\\Ep2IDE");
		_unlink("Ep2IDE.txt");

	return 0;
}


