/* redir.c (emx+gcc) -- Copyright (c) 1994-1996 by Eberhard Mattes */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "redirlib.h"


static void usage (void)
{
  puts ("Usage: redir \"<redirections>\" \"<program>\"\n\n"
        "Redirections (separate them with spaces):\n"
        "  <file      Redirect standard input from FILE\n"
        "  >file      Redirect standard output to FILE\n"
        "  >>file     Redirect standard output to FILE, appending\n"
        "  n<file     Redirect file descriptor N from FILE\n"
        "  n>file     Redirect file descriptor N to FILE\n"
        "  n<>file    Redirect file descriptor N from and to FILE\n"
        "  <&m        Redirect standard input from file descriptor M\n"
        "  >&m        Redirect standard output to file descriptor M\n"
        "  n<&m       Redirect file descriptor N from file descriptor M\n"
        "  n>&m       Redirect file descriptor N to file descriptor M\n"
        "  <&-        Close standard input\n\n"
        "Example:\n\n"
        "  redir \">output 2>&1\" \"make\"");
  exit (1);
}


int main (int argc, char *argv[])
{
  struct redir_save save;
  int r, e;

  if (argc != 3)
    usage ();
  r = redir_redirect (&save, argv[1]);
  if (r > 0)
    usage ();
  if (r < 0)
    exit (2);
  r = system (argv[2]);
  e = errno;
  redir_restore (&save);
  errno = e;
  if (r == -1)
    {
      perror ("system()");
      exit (2);
    }
  return r;
}
