/* ***************************************************************************
 File	    : redirect_stdin.c
 Module     : redirect_stdin()
 Purpose    : make all scanf's and gets's read from a file named on the 
 Purpose    :   command line.  The last two arguments must be "<" and filename
		or the last argument must be "<filename".
 Purpose    :   If file doesn't exist, it calls perror() and exit()
 Library    : ??
 *--------------------------------------------------------------------------*
	This is free software protected under the DECUS and Free Software
	Foundation tenents.
 *--------------------------------------------------------------------------*
 Parameters   : int *argc - number of parameters passed to the program from
 Parameters   :	  the C rtl.  If redirection is found, this is decremented
 Parameters   :   by 2 or 1 depending on whether redirection is specified in
 Parameters   :   1 or 2 arguments.
 Parameters   : char *argv[] - parameter tokens passed to the program from
 Parameters   :		the C rtl.

 Returns      : void
 Side effects : stdin comes from a named file if specified.  Global file pointer
 Side effects :   named stdin can be modified.
 *--------------------------------------------------------------------------*
 Ver.Mod    : 1.0    Date: 19-feb-91
 Author: rob riepel rob@ssvax1.dnet.loral.com
 Description:

*---------------------------------------------------------------------------*
 Ver.Mod    : 1.1    Date: 19-feb-91   Author: RTGregory
 Description: made into callable routine

 *--------------------------------------------------------------------------*/

#include <stdio.h>

void  redirect_stdin( int *argc, char *argv[])
{

int carg;

    /*  check for redirection of input  (<[ ]string)  */    

    carg = *argc;

    /*******************************************************
    ** handles "< filename" as last two arguments
    *******************************************************/
    if (strcmp(argv[carg-2],"<") == 0) {                    
        if (freopen(argv[carg-1],"r",stdin) == NULL) {
            perror(argv[carg-1]);
            exit(1);
        }
        else carg -= 2;
    }
    /*******************************************************
    ** handles "<filename" as last argument
    *******************************************************/
    else if (argv[carg-1][0] == '<') {
        if (freopen(&argv[carg-1][1],"r",stdin) == NULL) {
            perror(&argv[carg-1][1]);
            exit(1);
        }
        else carg--;
    }

    *argc = carg;

} /* redirect_stdin() */

#ifdef TESTING

main( int argc, char *argv[])
{
char str[200];

	printf( "found %d arguments\nEnter text.", argc);
	if( argc > 1)
	{
	  redirect_stdin( &argc, argv);
	  gets( str);
	  printf( "found %d arguments\nText was %s.\n", argc, str);
	  scanf( "%s72", str);
	  printf( "2nd line of text was %s.\n", str);
	}
}

#endif /* testing */
