/* Copyright (C) 1997 DJ Delorie, see COPYING.DJ for details */
/* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

static FILE *
sfopen(const char *c, const char *m)
{
  FILE *rv = fopen(c, m);
  if (rv == 0)
  {
    fprintf(stderr, "Error: cannot open file %s in mode %s\n", c, m);
    exit(1);
  }
  return rv;
}

int
main(int argc, char **argv)
{
  char buf[1000];
  char name[1000], type[1000];
  int addr, tag=0;
  FILE *inf = sfopen(argv[1], "r");
  FILE *sf = sfopen(argv[2], "r");
  FILE *outf = sfopen(argv[3], "w");
  fprintf(outf, "/* Generated by stub2inf - DO NOT EDIT */\n");
  fprintf(outf, "#ifndef __dj_include_stub_h__\n#define __dj_include_stub_h__\n\n");
  while (1)
  {
    if (fgets(buf, 1000, inf) == 0)
      break;
    if (strstr(buf, "by Value"))
      tag = 1;
    if (strstr(buf, "by Name"))
      tag = 0;
    name[0] = 0;
    sscanf(buf, "0000:%x %s", &addr, name);
    if (strncmp(name, "stubinfo", 8) == 0 && tag)
    {
      char *n;
      for (n=name; *n; n++)
	*n = toupper(*n);
      fprintf(outf, "#define %s %#x\n", name, addr);
    }
  }
  fprintf(outf, "#ifndef __ASSEMBLER__\n");
  fprintf(outf, "typedef struct {\n");
  while (1)
  {
    if (fgets(buf, 1000, sf) == 0)
      break;
    if (strncmp(buf, "stubinfo_end", 12) == 0)
      break;
    if (strncmp(buf, "stubinfo_", 9) != 0)
      continue;
    name[0] = 0;
    sscanf(buf, "%[^:]: ; %[^\n]", name, type);
    if (strncmp(type, "char", 4) == 0)
      fprintf(outf, "  char %s%s;\n", name+9, type+5);
    else
      fprintf(outf, "  %s %s;\n", type, name+9);
  }
  fprintf(outf, "} _GO32_StubInfo;\n");
  fprintf(outf, "extern _GO32_StubInfo *_stubinfo;\n");
  fprintf(outf, "#endif\n");
  fprintf(outf, "\n#endif /* __dj_include_stub_h__ */\n");
  fclose(inf);
  fclose(sf);
  fclose(outf);
  return 0;
}
