#include <stdio.h>

#ifdef OS2
#include <io.h>
#include <fcntl.h>
#include <process.h>
#define INCL_DOSPROCESS
#include <os2.h>
#endif

int isZfile(name)
char *name;
{
  int res, file;
  unsigned char magic[2];

#ifdef OS2
  file = open(name, O_RDONLY | O_BINARY);
#else
  file = open(name, O_RDONLY);
#endif
  res = read(file, magic, 2);
  close(file);

  return (res == 2) && (magic[0] == 0x1F) && 
         (magic[1] == 0x9D || magic[1] == 0x8B);
          /* compress */      /* gzip */
}

static int pid[64];

int Zopen(name)
char *name;
{
  int ph[2], file, old0, old1, old2, p;

  if ((file = open(name, O_RDONLY|O_BINARY)) == -1)
    return -1;

  old0 = dup(0);
  fcntl(old0, F_SETFD, 1);
  old1 = dup(1);
  fcntl(old1, F_SETFD, 1);
  old2 = dup(2);
  fcntl(old1, F_SETFD, 2);

  pipe(ph);
  fcntl(ph[0], F_SETFD, 1);
  setmode(ph[0], O_BINARY);
  setmode(ph[1], O_BINARY);

  dup2(file, 0);
  close(file);
  dup2(ph[1], 1);
  dup2(ph[1], 2);
  close(ph[1]);

  if ( (p = spawnlp(P_NOWAIT, "gzip.exe", "gzip", "-d", NULL)) == -1 )
    p = spawnlp(P_NOWAIT, "compress.exe", "compress", "-d", NULL);

  dup2(old0, 0);
  close(old0);
  dup2(old1, 1);
  close(old1);
  dup2(old2, 2);
  close(old2);

  if (p == -1)
  {
    close(ph[0]);
    return -1;
  }

  pid[ph[0]] = p;
  return ph[0];
}

void Zclose(int handle)
{
  RESULTCODES rc;
  PID p;
  close(handle);
  DosWaitChild(0, 0, &rc, &p, pid[handle]);
}
