// This code sample is execerpted from P. Wang's Intro to ANSI C on UNIX
// and partially modified for  CSC345 class
#include <stream.h>
#include <stdio.h>
#include <string>
//#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
typedef char *String;
#define MAXLINE 80
#define CHUNK 10
#define WHITE "\t \n"
#define MAXARG 20
using namespace std;
main()
{
  int fds[2]; // an array of 2 file descriptors fpr a pipe

  int i, j, pid1, pid2, status, ip;
  // string::size_type len;
  int len;
  char cmd[MAXLINE], subcmd1[MAXLINE], subcmd2[MAXLINE];
  String argl[MAXARG];

  cout << "enter your command % ";
  cin.getline(cmd, MAXLINE);

  string cmdstr(cmd), substr1, substr2;
  ip = cmdstr.find("|");
  len = strlen(cmd);
  //cmdstr[ip] = '\0';

  for ( i = 0; i < ip; i++ ) {
    
    subcmd1[i] = cmdstr[i];
  }
  subcmd1[i] = '\0';
  cout << "1st i is " << i << endl;
  for ( j=0, i = ++ip; i < len; i++, j++ ) {
    
    subcmd2[j] = cmdstr[i];
  }
  cout << "2nd i is " << i << endl;
  cout << "j is " << j << endl;
  subcmd2[j] = '\0';
    //substr1 = cmdstr.substr(0, ip - 1);

  //  substr2 = cmdstr.substr(ip + 1, cmdstr.length());

  cout << "sub string1 is " << subcmd1 << " sub string2 " << subcmd2 << endl;

  

  pipe(fds);			// create a pipe

  if ((pid1=fork()) == 0)			// child process
    {
      i = 0;
      argl[i++] = strtok(subcmd2, WHITE);
      while ( i < MAXARG && 
	      (argl[i++] = strtok(NULL, WHITE)) != NULL); 


      close (fds[1]);		// close a write descriptor
      dup2(fds[0], 0); 
      close(fds[0]);
      execvp( argl[0], argl);
      _exit(1);
    }

  if ((pid2=fork()) == 0)			// child process
    {
      i = 0;
      argl[i++] = strtok(subcmd1, WHITE);
      while ( i < MAXARG && 
	      (argl[i++] = strtok(NULL, WHITE)) != NULL); 

      close (fds[0]);		// close a write descriptor
      dup2(fds[1], 1); 
      close(fds[1]);
      execvp( argl[0], argl);
      _exit(1);
    }


      close(fds[0]);
      close(fds[1]);
      while (wait(&status) != pid2) ;
      cout << "a child has finished" << endl;
}
