/*This line lets emacs recognize this as -*- C -*- Code
 *-----------------------------------------------------------------------------
 *
 * Project:	Tcl Modules
 * Created:	91/10/22
 * Author:	John L. Furlani<john.furlani@East.Sun.COM>
 *
 * Description:
 *      Contains assorted Tcl command routines.
 *	
 * $Log: cmdMisc.c,v $
 *
 *
 *---------------------------------------------------------------------------*/
static char Id[] =
    "$Id: cmdMisc.c,v 2.0 1993/02/21 00:00:45 jlf Exp jlf $";

#include "global.h"

/*
  The Following code was written by Don Libes, NIST
  It was taken from his tool, 'expect'
  I have edited parts of it...
*/

int
cmdSystem(ClientData clientData, 
	  Tcl_Interp* interp, 
	  int argc, 
	  char* argv[])
{
#define MAX_ARGLIST 10240
    int i;
    int saved_stdout;
    char buf[MAX_ARGLIST];
    char *bufp = buf;
    int total_len = 0, arg_len;

    for (i = 1;i<argc;i++) {
        total_len += (1 + (arg_len = strlen(argv[i])));
        if (total_len > MAX_ARGLIST) {
            Tcl_AppendResult(interp, argv[0], ": args too long (>=", total_len,
                             " chars)", (char *) NULL);
            return(TCL_ERROR);
        }
        memcpy(bufp,argv[i],arg_len);
        bufp += arg_len;
        /* no need to check bounds, we accted for it earlier */
        memcpy(bufp," ",1);
        bufp += 1;
    }

    /* For Modules, stdout must be directed to stderr so it
     *  isn't parsed by the evaluating shell.  We also must save it here so it
     *  can be restored after this command has been executed.
     */
    saved_stdout = dup(1);
    close(1);
    dup(2);

    *(bufp-1) = '\0';
    i = system(buf);

    /*
     *  Following the style of Tcl_ExecCmd, we can just return the
     *  raw result (appropriately shifted and masked) to Tcl
     */

    sprintf(buf, "%d", (0xff & (i >> 8)));
    Tcl_SetResult(interp, buf, TCL_VOLATILE);

    /*
     *  Restore stdout.
     */
    close(1);
    dup(saved_stdout);
    
    return TCL_OK;
}
