/********************************************************************
 *                                                                  *
 *      CRISP - Custom Reduced Instruction Set Programmers Editor   *
 *                                                                  *
 *      (C) Paul Fox, 1989                                          *
 *                                                                  *
 *    Please See COPYRIGHT notice.                                  *
 *                                                                  *
 ********************************************************************/
# include	"crisp.h"
/*************************************************************
 *   Macro to execute a unix command and read the output into
 *   a buffer. The allocated buffer is returned.
 *
 *	perform_unix_command
 *		cmd	- Unix command to execute.
 *		header	- Header to display at top of window.
 *		[buf]	- If specified name of existing buffer to
 *			  apply command to otherwise, create a new one.
 **************************************************************/
int
perform_unix_command(string cmd, string header)
{
	string	file;
	int	tmp_buf, curbuf;
	string	sh = getenv("SHELL");
	
	curbuf = inq_buffer();
	sprintf(file, "/tmp/GR.%d", getpid());

	/***********************************************/
	/*   We  want  to  redirect stderr, but doing  */
	/*   this  is  shell  dependent. We'll assume  */
	/*   that  unless  $SHELL  ends in 'csh' that  */
	/*   we   have  a  Bourne  shell  derivative,  */
	/*   i.e. /bin/sh, bash, ksh.		       */
	/***********************************************/
	if (index(sh, "/"))
		sh = substr(sh, rindex(sh, "/") + 1);
	if (sh == "csh" || sh == "tcsh")
		cmd += ">&" + file;
	else
		cmd += ">" + file + " 2>&1";

	shell(cmd, 1);

	if (get_parm(2, tmp_buf) > 0) {
		set_buffer(tmp_buf);
		clear_buffer();
		read_file(file);
		top_of_buffer();
		set_buffer(curbuf);
		}
	else
		tmp_buf = create_buffer(header, file, 1);
	remove(file);
	set_buffer(curbuf);
	return(tmp_buf);
}

