#-*- perl -*-
# Copyright (C) 2000 R Development Core Team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the GNU
# General Public License for more details.
#
# A copy of the GNU General Public License is available via WWW at
# http://www.gnu.org/copyleft/gpl.html.	 You can also obtain it by
# writing to the Free Software Foundation, Inc., 59 Temple Place,
# Suite 330, Boston, MA  02111-1307  USA.

# Send any bug reports to r-bugs@r-project.org

use File::Basename;
use R::Utils;


my $revision = ' $Revision: 1.2 $ ';
my $version;
my $name;
$revision =~ / ([\d\.]*) /;
$version = $1;
($name = $0) =~ s|.*/||;

my $R_opts = "--restore --save";

while(defined($arg = shift @ARGV))
{
    if ($arg eq "-h" || $arg eq "--help") {
	usage(); exit 0;
    }
    if ($arg eq "-v" || $arg eq "--version")  {
	R_version($name, $version); exit 0;
    }
    if ($arg eq "--") {
	last;
    }
    if ($arg =~ /^-/)  {
	$R_opts .= " " . $arg;
    } else {
	unshift @ARGV, $arg;
	last;
    }
}


my $infile = shift @ARGV;
usage() unless defined $infile;
my $outfile = shift @ARGV;
$outfile = basename($infile, ".R"). ".Rout"  unless defined $outfile;

die "input file `$infile' cannot be opened\n" unless -f ${infile};

system("Rterm.exe $R_opts < $infile > $outfile");

sub usage {
    print STDERR <<END;
Usage: Rcmd BATCH [options] infile [outfile]

Run R non-interactively with input from infile and place output (stdout
and stderr) to another file.  If not given, the name of the output file
is the one of the input file, with a possible \`.R\' extension stripped,
and \`.Rout\' appended.

Options:
  -h, --help		print short help message and exit
  -v, --version		print version info and exit
  --			end processing of options

Further arguments starting with a \`-\' are considered as options as long
as \`--\' was not encountered, and are passed on to the R process, which
by default is started with \`--restore --save\'.

Report bugs to <r-bugs\@r-project.org>.
END
    exit 0;
}
