/* a simulation for the Unix popen() and pclose() calls on MS-DOS */
/* only one pipe can be open at a time */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>

static char pipename[128], command[128];
static int wrpipe;

static void Mktemp(char *);

FILE *popen(char *cmd, char *flags)
{
  wrpipe = (strchr(flags, 'w') != NULL);

  if ( wrpipe )
  {
    strcpy(command, cmd);
    strcpy(pipename, "~WXXXXXX");
    Mktemp(pipename);
    return fopen(pipename, flags);  /* ordinary file */
  }
  else
  {
    strcpy(pipename, "~RXXXXXX");
    Mktemp(pipename);
    strcpy(command, cmd);
    strcat(command, ">");
    strcat(command, pipename);
    system(command);
    return fopen(pipename, flags);  /* ordinary file */
  }
}

int pclose(FILE *pipe)
{
  int rc;

  if ( fclose(pipe) == EOF )
    return EOF;

  if ( wrpipe )
  {
    if ( command[strlen(command) - 1] == '!' )
      command[strlen(command) - 1] = 0;
    else
      strcat(command, "<");

    strcat(command, pipename);
    rc = system(command);
    unlink(pipename);
    return rc;
  }
  else
  {
    unlink(pipename);
    return 0;
  }
}

static
void Mktemp(char *file)
{
  char fname[32], *tmp, *bsp;

  tmp = getenv("TMP");

  if ( tmp != NULL )
  {
    strcpy(fname, file);
    bsp = strcpy(file, tmp);
    while ((bsp=strchr(bsp, '/')) != NULL)
        *bsp = '\\';

    if ( file[strlen(file) - 1] != '\\' )
      strcat(file, "\\");

    strcat(file, fname);
  }

  mktemp(file);
}
