/* unexecemx.c */

#include "config.h"
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/process.h>

unexec (new_name, a_name, data_start, bss_start, entry_address)
     char *new_name, *a_name;
     unsigned data_start, bss_start, entry_address;
{
  int fd, rc, extract;
  char emxl_path[512];

  if (a_name == 0)
    fatal ("SYMFILE argument of dump-emacs is nil\n");
  fd = open ("emacs.cor", O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, S_IREAD|S_IWRITE);
  if (fd < 0)
    fatal ("Cannot create core dump file\n");
  if (_core (fd) != 0)
    fatal ("Cannot write core dump file\n");
  close (fd);
  extract = 0;
  if (access (a_name, 0) != 0)
    {
      rc = spawnlp (P_WAIT, "emxbind.exe", "emxbind.exe",
                    "-xq", a_name, a_name, 0);
      if (rc == -1)
        fatal ("Cannot run emxbind\n");
      if (rc != 0)
        fatal ("emxbind failed to extract a.out image\n");
      extract = 1;
    }
  if (_path (emxl_path, "emxl.exe") != 0)
    strcpy (emxl_path, "/emx/bin/emxl.exe");
  rc = spawnlp (P_WAIT, "emxbind.exe", "emxbind.exe",
                "-bqs", "-cemacs.cor", emxl_path, a_name, new_name, 0);
  unlink ("emacs.cor");
  if (extract)
    unlink (a_name);
  if (rc == -1)
    fatal ("Cannot run emxbind\n");
  if (rc != 0)
    fatal ("emxbind failed to bind executable\n");
  return 0;
}
