#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h> /* unlink */
#include <errno.h> /* red hat */
#include <wait.h> /* for runit */

/*----------------------------*/
/*                            */
/* System C commands from Ada */
/*                            */
/*----------------------------*/

// char s[81];                 /* temporary string */

/* CSYNC */

void CSync() {
   sync();
   sync();
   sync();
}

int CRunIt (const char * path,
	    const char * outfile,
	    const char * param1,
	    const char * param2,
	    const char * param3 ) {
  pid_t child, result;
  int fd0, fd1, fd2;
  int status;
  int i;
  
  if ( !(child = fork()) ) {
     /* Redirect stdin, out, err */
     for (i=0; i< FOPEN_MAX; ++i )
         close( i );
     fd0 = open( "/dev/null", O_RDONLY ); 
     if (fd0 < 0 ) exit( 110 );
     fd1 = open( outfile, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
     if (fd1 < 0 ) exit( 111 );
     fd2 = dup( 1 );
     if (param1[0]=='\0') {
         execlp( path, path, NULL );
     } else if (param2[0]=='\0') {
         execlp( path, path, param1, NULL );
     } else if (param3[0]=='\0') {
         execlp( path, path, param1, param2, NULL );
     } else {
         execlp( path, path, param1, param2, param3, NULL );
     }
     /* if we got here, file probably wasn't found */
     exit( errno );
  }
  result = waitpid( child, &status, 0 );
  /* wait( &status ); */
  /* if ( WIFEXITED( status ) != 0 ) */
  /*   status = WEXITSTATUS( status ); */
  status = 112;
  if ( result >= 0 ) {
       status = WIFEXITED( status );
  }
  return status;
}

int CRunItForStdErr (char * path,
		     char * outfile,
		     char * param1,
		     char * param2,
		     char * param3) {
  /* dicard standard out, standard error to outfile */
  /* written for uuchk */
  pid_t child, result;
  int fd0, fd1, fd2;
  int status;
  int i;
  
  if ( !(child = fork()) ) {
     /* Redirect stdin, out, err */
     for (i=0; i< FOPEN_MAX; ++i ) close( i );
     fd0 = open( "/dev/null", O_RDONLY ); 
     if (fd0 < 0 ) exit( 110 );
     fd1 = open( "/dev/null", O_WRONLY );
     if (fd1 < 0 ) exit( 111 );
     fd2 = open( outfile, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
     if (fd2 < 0 ) exit( 111 );
     if (param1[0]=='\0') {
         execlp( path, path, NULL );
     } else if (param2[0]=='\0') {
         execlp( path, path, param1, NULL );
     } else if (param3[0]=='\0') {
         execlp( path, path, param1, param2, NULL );
     } else {
         execlp( path, path, param1, param2, param3, NULL );
     }
     /* if we got here, file probably wasn't found */
     exit( errno );
  }
  status = 112;
  result = waitpid( child, &status, 0 );
  if ( result >= 0 )
     status = WIFEXITED( status );
  return status;
}

