/*{{{  includes*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#include <local/bool.h>

#define FILEIO_C

#ifdef KEYBIND
#include "..\common\keys.h"
#include "..\keybind\keybind.h"
#else
#include "..\origami\origami.h"
#endif
/*}}}  */

#define PIPEMAX 10
 
typedef enum { P_UNOPENED = 0, P_READ, P_WRITE} pipemode;
/*{{{  struct pipeinfo*/
static struct {
  pipemode _pmode;
  char *_pipecmd;
  char *_tmpfile;
  FILE *p_fd;
} pipeinfo[PIPEMAX];
/*}}}  */

static char pipename[] = "opXXXXXX.pip";

/*{{{  FILE *popen(char *command, char *mode)*/
FILE *popen(char *command, char *mode)
{
  FILE *stream;
  int i;
  char tmp[300],tmpname[300];
 
  for(i=0;i<=PIPEMAX;i++)
  {
    if (i == PIPEMAX)
      return (FILE *)0;
    if (pipeinfo[i]._pmode == P_UNOPENED)
      break;
  }
 
  strcpy(tmpname,pipename);
  mktemp(tmpname);
  if (*mode == 'r')
  {
    sprintf(tmp,"%s >%s",command,tmpname);
 
    system(tmp);
#ifndef KEYBIND
    win_changed = TRUE;
#endif
    stream = fopen(tmpname,"r");
    if (stream != NULL)
    {
      pipeinfo[i]._pipecmd = strdup(tmp);
      pipeinfo[i]._tmpfile = strdup(tmpname);
      pipeinfo[i]._pmode = P_READ;
      pipeinfo[i].p_fd = stream;
    }
    return stream;
  } else if (*mode == 'w')
  {
    stream = fopen(tmpname,"w+");
    sprintf(tmp,"%s <%s",command,tmpname);
    if (stream != NULL)
    {
      pipeinfo[i]._pipecmd = strdup(tmp);
      pipeinfo[i]._tmpfile = strdup(tmpname);
      pipeinfo[i]._pmode = P_WRITE;
      pipeinfo[i].p_fd = stream;
    }
    return stream;
  } else
    return NULL; /* unknown mode */
}
/*}}}  */

/*{{{  int pclose (FILE *stream)*/
int pclose (FILE *stream)
{
  int i,result;
 
  for(i=0;i<=PIPEMAX;i++)
  {
    if (i == PIPEMAX)
      return -1;
    if (pipeinfo[i].p_fd == stream)
      break;
  }
 
  result = -1;
  if (pipeinfo[i]._pmode == P_READ) /* read from pipe: simply close it */
    result = fclose(stream);
  else if (pipeinfo[i]._pmode == P_WRITE) /* write to pipe: exec command */
  {
    result = fclose(stream);
    if (result == 0)
    {
      system(pipeinfo[i]._pipecmd);
#ifndef KEYBIND
      win_changed = TRUE;
#endif
    }
  }
  unlink(pipeinfo[i]._tmpfile);
  pipeinfo[i]._pmode = P_UNOPENED;
  free(pipeinfo[i]._pipecmd);
  free(pipeinfo[i]._tmpfile);
  return result;
}
/*}}}  */

