if ( ! exists $ENV{'ENVI_HOME'} || ! exists $ARGV[0] ) {
	die "please run 'envi', not 'rt.pl'\n";
}

use File::Spec::Functions qw(rel2abs);

do "$ENV{'ENVI_HOME'}/lib/util.pl";
our $bitness;
my $task = $ARGV[0]; shift(@ARGV);

if ($task =~ /-x64$/) {
    envi_message("64bit version");
    $bitness = "64";
}
#if ($task =~ /diffcol/) {
#    envi_message("running diffcol - assuming 64bit version");
#    $bitness = "64";
#}
else { # task could be 'release' or 'diffcol' and will not indicate bitness, as that is decided by the env
    my $os_name = $^O;
    $bitness = "64"; # default is true for darwin
    if ($os_name =~ "MSWin32") {
	$bitness = "32"; # assume 32 bit for windows unless determined to be otherwise
	my $curr_dir = $ENV{'ENVI_HOME'}; #dirname(rel2abs($0));
	while($curr_dir =~ m/envi/) { # test the folder name when we're one level above the envi folder
	    #print STDERR "**** Current dir is now $curr_dir\n";
	    $curr_dir = dirname(rel2abs($curr_dir));
	}
	#print STDERR "**** Current dir is now $curr_dir\n";
	if($curr_dir =~ m/-64bit$/) {
	    $bitness = "64";
	}

    } elsif ($os_name =~ "linux") {
	$bitness = `getconf LONG_BIT`;
    }
}


my $task_executable = task_location($task) . "/task.pl";
my $task_options = task_location($task) . "/options.txt";

#set task home and name for the benefit of the task
$ENV{'TASK_HOME'} = task_location($task);
$ENV{'TASK_NAME'} = $task;

#setup the task environment
if ( -f system_task_environment_script($task) ) {
	envi_message( "getting $task system env");
	my $v = system_task_environment_script($task);
	do $v;
}
if ( -f user_task_environment_script($task) ) {
	envi_message( "getting $task user env");
	my $v = user_task_environment_script($task);
	do $v;
}

#do what they asked:
if ( $ARGV[0] eq "env" ) {

	shift(@ARGV);
	
	# - run something in the task environment
	if ( exists $ARGV[0] ) {
		my $command = $ARGV[0] . " ";
		shift(@ARGV);
		for my $a ( @ARGV ) {
			$command .= " \"$a\"";
		}
		system( $command );

	# - show task environment
	} else {
		foreach my $key (keys %ENV) {
			print "$key=$ENV{$key}\n";
		}
	}

# - show task options
} elsif ( $ARGV[0] eq "options" ) {
	if ( -f "$task_options" ) {
	    open( FILE, "< $task_options" ) or die "Can't open $filename : $!";
	    while( <FILE> ) {
	        print;
    	}
	    close FILE;
	}

# - run the task
} else {
	my $command = "perl \"$task_executable\"";
	for my $a ( @ARGV ) {
		$command .= " \"$a\"";
	}

	envi_message( "task command: $command" );
	system( $command );
}
