#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>

int main(int argc, char **argv) {
  FILE *ffe, *ffa;
  char buf[128], *ptr;
  int ipos;

  if (argc < 2 || strcmp(argv[1], "-h") == 0) {
    fprintf(stderr, "Aufruf: %s <Patch-Datei>\n", argv[0]);
    fprintf(stderr, "Schreibt aus Patch-Datei Patch-Header-Datei\n");
    exit(1);
  }

  if ((ffe = fopen(argv[1], "r")) == NULL) {
    fprintf(stderr, "Fehler Lesen %s\n", argv[1]);
    exit(1);
  }

  if ((ptr = strrchr(argv[1], '/')) == NULL) { ptr = argv[1]; } else { ptr++; }
  while (*ptr != '\0' && strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", (int)*ptr) == NULL) { ptr++; }
  if (*ptr == '\0') {
    fprintf(stderr, "Kein vernuenftiger Name: %s\n", argv[1]);
    exit(1);
  }
  snprintf(buf, sizeof(buf) - 16, "%s", ptr);
  for (ptr = buf; *ptr != '\0'; ptr++) {
    if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_", (int)*ptr) == NULL) { *ptr = '_'; }
  }
  if ((ptr = strrchr(buf, '.')) == NULL) { ptr = buf + strlen(buf); }
  strcpy(ptr, ".h");

  ipos = 0;
  while ((ffa = fopen(buf, "r")) != NULL) {
    fclose(ffa);
    sprintf(ptr, "_%d.h", ++ipos);
  }

  if ((ffa = fopen(buf, "w")) == NULL) {
    fprintf(stderr, "Fehler Schreiben %s\n", buf);
    exit(1);
  }

  buf[strlen(buf) - 2] = '\0';
  fprintf(ffa, "static char %s[]=\"\\\n", buf);
  buf[strlen(buf) - 2] = '.';

  ipos = 0;
  while (fread(buf, 1, 1, ffe) > 0) {
    fprintf(ffa, "\\x%02x", (int)(unsigned char)buf[0]);
    if (++ipos == 19) { fprintf(ffa, "\\\n"); ipos = 0; }
  }

  fprintf(ffa, "\";\n");
  fclose(ffa);
  fclose(ffe);

  exit(0);
}
