/*mkmk.c
  Eric Pepke
  Takes as input a series of programs and produces bits of the makefile 
  including the .h files.  Writes output to standard output.
*/

#include <stdio.h>

char *pn;		/*Program name*/

#define MINTAB	24
#define MAXLINE	77

MakeDepend(fn)
char *fn;
/*Emits a series of make dependencies for file fn*/
{
    FILE *inFile;
    char line[401];
    char incFile[401];
    char ccLine[401];
    int ccLineSet = 0;

    inFile = fopen(fn, "r");

    if (inFile)
    {
	int nc;
	strcpy(incFile, fn);
	incFile[strlen(incFile) - 1] = 'o';
	printf("%s:", incFile);
	nc = strlen(fn) + 1;
	do
	{
	    putchar('\t');
	    nc /= 8;
	    ++nc;
	    nc *= 8;
	} while (nc < MINTAB);
	incFile[strlen(incFile) - 1] = 'c';
	printf("%s", incFile);
	nc += strlen(incFile);

	/*Depend on $(HFILES)*/
	printf(" $(HFILES)");
	nc += 10;
		

	while (fgets(line, 400, inFile))
	{
	    if (1 == sscanf(line, "#include %s", incFile))
	    {
		if (incFile[0] == '"')
		{
		    char *s;
		    s = &(incFile[1]);

		    while (*s)
		    {
			if (*s == '"')
			{
			    *s = 0;
			}
			else
			{
			    ++s;
			}

		    }
		    if (nc + strlen(&(incFile[1])) > MAXLINE)
		    {
			printf("\\\n");
			nc = 0;
			do
			{
			    putchar('\t');
			    nc /= 8;
			    ++nc;
			    nc *= 8;
			}
			while (nc < MINTAB);
		    }
		    else
		    {
			putchar(' ');
			++nc;
		    }
		    printf("%s", &(incFile[1]));
		    nc += strlen(&(incFile[1]));
		}
	    }
	    else if (1 == sscanf(line, "/*$%s", ccLine))
	    {
		strcpy(ccLine, line + 3);
		ccLineSet = 1;
	    }
	}
	printf("\n");
	nc = 0;
	do
	{
	    putchar('\t');
	    nc /= 8;
	    ++nc;
	    nc *= 8;
	}
	while (nc < MINTAB);
	if (ccLineSet)
	{
	    printf("%s", ccLine);
	}
	else
	{
	    printf("$(CC) $(CFLAGS) %s -c\n", fn);
	}
    }
    else
    {
	fprintf(stderr, "%s: Cannot open file %s\n", pn, fn);
    }
}

main(argc, argv)
int argc;
char *argv[];
{
    int k;
    
    pn = argv[0];

    for (k = 1; k < argc; ++k)
    {
	MakeDepend(argv[k]);
    }
}
