/* This file is part of the origami distribution. (Amiga Port)
 *
 * original version by M.Schwingen (ST-Port)
 * Changed for multiple files by Thomas Hadig in December 1991
 * Version 1.6.42 alpha, June 1992
 * (C) 1992 by Thomas Hadig
 * may be distributed unchanged ! (see copyright notes)
 */

/*{{{  includes*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#include <local/bool.h>

#define AMIGAFILEIO_C

#ifdef KEYBIND
#include <origami:keybind/keybind.h>

char pipetemp[] = "T:KEYBXXXXXXXX";
#elif defined(ORIGAMI)

#include "origami.h"
char pipetemp[] = "T:ORIGXXXXXXXX";
#else
char pipetemp[] = "T:FOLDXXXXXXXX";

#endif

#include "origami:amiga/getopt/getopt.h"
/*}}}  */
/*{{{  variables*/
extern char base_name[];

static char pipecmd[10][256];
char pipeakt[10][18];
int pipemode[10]={0,0,0,0,0,0,0,0,0,0};
FILE *streams[10];
/*}}}  */

/*{{{  get_next_name*/
int get_next_name (char *from)

 {
  int i=0;

  while ((pipemode[i])&&(i<10)) i++;
  if (i==10) return -1;
  strcpy (pipeakt[i],pipetemp);
  mktemp (pipeakt[i]);
  return i;
 }
/*}}}  */
/*{{{  make_command*/
void make_command (int i,char *c,char mode)

 {
  char *p=c;

  while ((*p)&&(!isspace(*p))) p++;
  if (*p)
  {
    *p=0;
    p++;
    /*while (isspace(*p)) p++;*/
  }
  if (mode == 'r')
    sprintf(pipecmd[i],"%s >%s %s",c,pipeakt[i],p);
  else
    sprintf(pipecmd[i],"%s <%s %s",c,pipeakt[i],p);
 }
/*}}}  */

/*{{{  popen*/
FILE *popen(char *command, char *mode)

 {
  int i;

  if (*mode == 'r')
   /*{{{  READ*/
   {
    if ((i = get_next_name (pipetemp))==-1) return NULL;
    make_command (i,command,*mode);
    system(pipecmd[i]);
    streams[i] = fopen(pipeakt[i],"r");
    if (streams[i] != NULL)
      pipemode[i] = 1;
    return streams[i];
   }
   /*}}}  */
  else if (*mode == 'w')
   /*{{{  WRITE*/
   {
    if ((i = get_next_name (pipetemp))==-1) return NULL;
    streams[i] = fopen(pipeakt[i],"w+");
    make_command (i,command,*mode);
    if (streams[i] != NULL)
      pipemode[i] = 2;
    return streams[i];
   }
   /*}}}  */
  else return NULL; /* unknown mode */
 }
/*}}}  */
/*{{{  pclose*/
int pclose (FILE *stream)

 {
  int result;
  int i=0;

  while ((stream!=streams[i])&&(i<10)&&(pipemode[i])) i++;
  if (i==10) return -1;
  if (pipemode[i] == 1) /* read from pipe */
   /*{{{  READ*/
   {
    pipemode[i] = 0;
    result = fclose(stream);
    unlink(pipeakt[i]);
    return result;
   }
   /*}}}  */
  if (pipemode[i] == 2) /* write to pipe */
   /*{{{  WRITE*/
   {
    pipemode[i] = 0;
    result = fclose(stream);
    if (result == 0)
     {
      system(pipecmd[i]);
     }
    unlink(pipeakt[i]);
    return result;
   }
   /*}}}  */
  return -1; /* no pipe open */
 }
/*}}}  */
