/* 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.92.1, February 1994
 * (C) 1991-94 by Thomas Hadig
 * may be distributed unchanged ! (see copyright notes)
 */

char pipetemp[] = "T:ORIGXXXXXXXX";

#define MAX_PIPES 10 /* change number of init values at struct pipemode, too */
#include <h/envvar_str.h>
/*{{{}}}*/
/*{{{  includes*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define AMIGAFILEIO_C

#include <amiga/h/getopt.h>
/*}}}  */
/*{{{  variables*/
extern char base_name[];

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

/*{{{  get_next_name*/
private int get_next_name (char *from)
 {
  int i=0;

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

  while ((*p)&&(!isspace(*p))) p++;
  if (*p) *p++=0;
  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*/
public FILE *popen(char *command, char *mode)
 {
  int i;

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

  while ((stream!=streams[i])&&(i<MAX_PIPES)&&(pipemode[i])) i++;
  if (i==MAX_PIPES) return -1;
  if (pipemode[i] == 1) /* read from pipe */
   /*{{{  READ*/
   {
    int result;

    pipemode[i] = 0;
    result = fclose(stream);
    unlink(pipeakt[i]);
    return (result);
   }
   /*}}}  */
  if (pipemode[i] == 2) /* write to pipe */
   /*{{{  WRITE*/
   {
    int result;

    pipemode[i] = 0;
    if (!(result = fclose(stream))) system(pipecmd[i]);
    unlink(pipeakt[i]);
    return (result);
   }
   /*}}}  */
  return -1; /* no pipe open */
 }
/*}}}  */

/*{{{  home_expand*/
public char *home_expand (char *s) { return s; }
/*}}}  */
