
/*
   Util program for making makefiles.  Drives CC with -M, and frobs
   results into something suitable for including in a makefile
   for an OLB.
*/

#include <stdio.h>
#include <ctype.h>
#include <osbind.h>

int gettok(f, b)
FILE * f;
char * b;
{
  int ch;
  char * p = b;
  
  while (((ch = fgetc(f)) != EOF) && (isspace(ch))) ;
  if (ch == EOF)
	return(0);
  *p++ = ch;
  while (((ch = fgetc(f)) != EOF) && (!isspace(ch)))
	*p++ = ch;
  *p = '\0';
  return(1);
}

FILE * fopen_carefully(name, mode)
char * name;
char * mode;
{
  FILE * f;
  
  if ((f = fopen(name, mode)))
	return(f);
  fprintf(stderr, "Can't open '%s'\n", name);
  exit(-1);
}

main(argc, argv)
int argc;
char ** argv;
{
  FILE * inf;
  FILE * depf;
  FILE * input_makefile;
  FILE * output_makefile;
  char buf[80], line[80];
  char * compiler = "cc";
  char * fname = "files.lst";
  char * base_makefile = "makefile.0";
  char * target_makefile = "makefile";
  int ch;
  int eol_p;

  if (argc > 1)
	compiler = argv[1];
  if (argc > 2)
	fname = argv[2];
  if (argc > 3)
	base_makefile = argv[3];
  if (argc > 4)
	target_makefile = argv[4];
  inf = fopen_carefully(fname, "r");
  input_makefile = fopen_carefully(base_makefile, "r");
  output_makefile = fopen_carefully(target_makefile, "w");
/*
   Copy base makefile to target
*/
  while ((ch = fgetc(input_makefile)) != EOF)
	fputc(ch, output_makefile);
  fprintf(output_makefile, "\n#\n# Machine generated part starts here.\n#\n");
  fclose(input_makefile);

  while (gettok(inf, buf))
	{
	strcpy(line, compiler);
	strcat(line, " -M ");
	strcat(line, buf);
	strcat(line, " -o makedeps.tmp");
	system(line);
	depf = fopen_carefully("makedeps.tmp", "r");
	if (gettok(depf, buf))
		{
		fprintf(output_makefile, "$(OLB)(%s) ", buf);
		while ((ch = fgetc(depf)) != EOF)
			{
			if (ch == '\\')
				{
				fputc(ch, output_makefile);
				ch = fgetc(depf);
				if (ch != '\n')
					fputc('\\', output_makefile);
				}
			fputc(ch, output_makefile);
			eol_p = (ch == '\n');
			}
		if (!eol_p)
			fputc('\n', output_makefile);
		}
	fclose(depf);
	unlink("makedeps.tmp");
	}
  fclose(output_makefile);
  fclose(inf);
  exit(0);
}

