/*
Take an error message log on stdin with lines of the form

Warning file linenumber : error message
Error file linenumber : error message

and display on stdout the error message followed by the offending
source lines.

Turbo C uses this format for its messages.

Usage:
	terrshow <error_log_file >merged_source_and_error_file

[27-Feb-88]
*/

/* This version works with Turbo C Version 1.5 or later */

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

#include "elefunt.h"

#define MAXLINE 255
#define MAXFNAME 63	/* PC DOS has short names */

#define SUCCESS 0
#define FAILURE 1

char errmsg[MAXLINE];
char line[MAXLINE];
char fname[MAXFNAME] = "";
FILE *fp = (FILE *)NULL;
int lno = 0;
int errlno = 0;

void cleanup ARGS((void));
void display ARGS((void));
int getfile ARGS((char *errmsg));
int
main(VOID_ARG)
{
	while (fgets(errmsg,MAXLINE,stdin) != (char *)NULL)
		(void)display();
	(void)cleanup();
	return (EXIT_SUCCESS);
}

void
cleanup(VOID_ARG)	/* clean up and exit */
{
	if (fp != (FILE *)NULL)
		(void)fclose(fp);
	exit(0);
}

void
display(VOID_ARG)	/* display source line matching errmsg[] */
{
	char *p;
	char *plno;
	char *perr;
	
	if ((strncmp(errmsg,"Warning ",8) != 0) &&
		(strncmp(errmsg,"Error ",6) != 0))
		return;	/* not an error message line */
	p = strchr(errmsg,' ');
	*p++ = '\0';	/* clobber ' '; p points now to file name */
	plno = strchr(p,' ');
	*plno++ = '\0';		/* point to line number */
	perr = strchr(plno,':');
	if (perr == (char*)NULL)
		return;			/* should never happen */
	*perr = '\0';			/* terminate line number */
	perr += 2;		     /* point to error message text */
	if ((errlno = atoi(plno)) <= 0)	/* error line number in source file */
		return;			/* not an error message line */
	if (getfile(p) != SUCCESS)
		return;
	if (lno > errlno)	/* cannot happen */
	{
		(void)printf("\n?Line number backed up: %s(%s\n",errmsg,p);
		rewind(fp);
		lno = 0;
	}
	while (lno < errlno)
	{
		if (fgets(line,MAXLINE,fp) == (char *)NULL)
		{
			(void)printf("\n?Unexpected EOF before finding line: %s(%s\n",
				errmsg,p);
			return;
		}
		lno++;
	}
	(void)printf("\n%s(%s:%7d)%s",perr,p,lno,line);
}

#if STDC
int
getfile(char *error_msg)	/* return SUCCESS on success, FAILURE on error */
#else /* NOT STDC */
int
getfile(error_msg)
char *error_msg;
#endif /* STDC */
{
	if (strcmp(fname,error_msg) != 0)
	{
		if (fp != (FILE *)NULL)
			(void)fclose(fp);
		(void)strncpy(fname,error_msg,MAXFNAME);
		fname[MAXFNAME-1] = '\0';
		if ((fp = fopen(fname,"r")) == (FILE *)NULL)
		{
			(void)printf("\n?Cannot open file [%s]\n",fname);
			return(FAILURE);
		}
		lno = 0;		
	}
	return(SUCCESS);
}
