#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <process.h>
#include "basics.h"

main(int argc, char *argv[]) {
   int emx_system(char *cmd);
   char line[128];

   printf("give a command: ");
   fgets(line, 128, stdin);
   if (emx_system(line) == -1)
      fatal("execution error\n");

   exit(0);
}

/*
 * Next function tries to emulate UNIX system()
 */
int emx_system(char *cmd) {
   int cnt, count; char *argv[10], *p, *q, *outname = NULL;
   
   p = cmd; count = 0;
   while (isspace(*p)) p++;
   while (*p != '\0') {
      cnt = 0;
      if (*p == '"') {
         p++; q = p;
         while (*q != '"') {
            if (*q == '\0') fatal("emx_run: invalid cmd\n");
            cnt++; q++;
         }
         q++;
      }
      else if (*p == '>') {
      	 p++;
         while (isspace(*p)) p++;
         q = p;
         while (!isspace(*q) && *q != '\0') {
      	    cnt++; q++;
         }
         if ((outname = malloc(cnt+1)) == NULL)
            fatal("Out of memory\n");
         strncpy(outname, p, cnt);
         *(outname+cnt) = '\0';
         p = q;
         continue;
      }
      else {
      	 q = p;
         while (!isspace(*q) && *q != '\0') {
      	    cnt++; q++;
         }
      }
      if (count == 9) fatal("More than ten arguments\n");
      if ((argv[count] = malloc(cnt+1)) == NULL)
         fatal("Out of memory\n");
      strncpy(argv[count], p, cnt);
      argv[count][cnt] = '\0';
      count++; p = q; 
      while (isspace(*p)) p++;
   }

   argv[count] = NULL;
   if (outname != NULL)
      (void) freopen(outname, "w", stdout);
   return spawnvp(P_WAIT, argv[0], argv);
}
