#! /usr/bin/env perl
use strict;
use Cwd;

if ($#ARGV == -1) {
    die " ERROR rtm.buildnml: must specify a caseroot input argument";
}
my ($CASEROOT) = @ARGV;
chdir "${CASEROOT}";

my @dirs = ("$CASEROOT/Tools");
unshift @INC, @dirs;
require SetupTools;
my $sysmod; 

my $CASEBUILD		= `./xmlquery  CASEBUILD	 -value`;
my $CASEROOT		= `./xmlquery  CASEROOT		 -value`;
my $CCSMROOT		= `./xmlquery  CCSMROOT		 -value`;
my $DIN_LOC_ROOT	= `./xmlquery  DIN_LOC_ROOT	 -value`;
my $NINST_ROF		= `./xmlquery  NINST_ROF	 -value`;
my $GET_REFCASE		= `./xmlquery  GET_REFCASE	 -value`;
my $ROF_GRID		= `./xmlquery  ROF_GRID     	 -value`;
my $RTM_BLDNML_OPTS     = `./xmlquery  RTM_BLDNML_OPTS 	 -value`;
my $RTM_NAMELIST_OPTS   = `./xmlquery  RTM_NAMELIST_OPTS -value`;
my $RUNDIR		= `./xmlquery  RUNDIR     	 -value`;
my $RUN_TYPE		= `./xmlquery  RUN_TYPE		 -value`;
my $RUN_STARTDATE	= `./xmlquery  RUN_STARTDATE	 -value`;
my $RUN_REFCASE	        = `./xmlquery  RUN_REFCASE 	 -value`;
my $RUN_REFDATE	        = `./xmlquery  RUN_REFDATE	 -value`;
my $RUN_REFTOD	        = `./xmlquery  RUN_REFTOD 	 -value`;
my $SCRIPTSROOT		= `./xmlquery  SCRIPTSROOT	 -value`;
my $UTILROOT		= `./xmlquery  UTILROOT		 -value`;

if (! -d "$CASEBUILD/rtmconf" ) {
    $sysmod = "mkdir $CASEBUILD/rtmconf";
    system($sysmod) == 0 or die "ERROR rtm.buildnml: $sysmod failed: $?\n";
}
chdir "$CASEBUILD/rtmconf";

#--------------------------------------------------------------------
# Verify rof grid is supported
#--------------------------------------------------------------------

my $check_grid = "fail";
my @rof_grid_supported = ("null", "r05", "r01");
foreach my $grid (@rof_grid_supported) {
    if (${ROF_GRID} eq $grid) {
	$check_grid = "OK";
    }
}
if (${check_grid} ne "OK") {
    print " ROF_GRID=${ROF_GRID} not supported in rtm";
    die " rtm only support on null (for single point runs), r05 and r01 ROF_GRIDs only \n";
}

#--------------------------------------------------------------------
# Invoke rtm build-namelist - output will go in $CASEBUILD/rtmconf
#--------------------------------------------------------------------

my $inst_string;
my $inst_counter = 1;
while ($inst_counter <= $NINST_ROF) {
    
    # -----------------------------------------------------
    # determine instance string 
    # -----------------------------------------------------

    $inst_string = "";
    if ($NINST_ROF > 1) {
	$inst_string = `printf _%04d $inst_counter`;

	# If multi-instance case does not have restart file, use single-case restart
	# for each instance
	if ( (! -e "$RUNDIR/rpointer.rof${inst_string}") && (-e "$RUNDIR/rpointer.rof") ) {
	    $sysmod = "cp -v $RUNDIR/rpointer.rof $RUNDIR/rpointer.rof${inst_string}";
	    system($sysmod) == 0 or die "ERROR rtm.buildnml: $sysmod failed: $?\n";
	}
    }

    # -----------------------------------------------------
    # create rtmconf/cesm_namelist
    # -----------------------------------------------------

    if (-e "$CASEBUILD/rtm.input_data_list") {
	$sysmod = "rm $CASEBUILD/rtm.input_data_list";
	system($sysmod) == 0 or die "ERROR rtm.buildnml: $sysmod failed: $?\n";
    }
    
    # The following is for backwards compatibility when runoff restart data was on clm restart files
    my $infile_text = "";
    if (${ROF_GRID} ne "null") {

	my $refdir;
	my $fncheck;
	if (($RUN_TYPE eq'hybrid') || ($RUN_TYPE eq "branch")) {
	    # set search directory
	    $refdir = "$RUNDIR";
	    if ($GET_REFCASE eq 'TRUE') {
		$refdir = "$DIN_LOC_ROOT/ccsm4_init/$RUN_REFCASE/$RUN_REFDATE";
	    }

	    # search for clm or rtm files with instance or not
	    $fncheck = "${RUN_REFCASE}.rtm${inst_string}.r.${RUN_REFDATE}-${RUN_REFTOD}.nc";
	    if (! -e "$refdir/$fncheck") {
		$fncheck = "${RUN_REFCASE}.rtm.r.${RUN_REFDATE}-${RUN_REFTOD}.nc";
		if (! -e "$refdir/$fncheck") {
		    $fncheck = "${RUN_REFCASE}.clm2${inst_string}.r.${RUN_REFDATE}-${RUN_REFTOD}.nc";
		    if (! -e "$refdir/$fncheck") {
			$fncheck = "${RUN_REFCASE}.clm2.r.${RUN_REFDATE}-${RUN_REFTOD}.nc";
			if (! -e "$refdir/$fncheck") {
			    print "WARNING:: rtm.buildnml could not find restart file for branch or hybrid start \n";
			    if ($GET_REFCASE eq 'TRUE') {
				die "ERROR rtm.buildnml: GET_REFASE is TRUE, so aborting because couldn't find files";
			    }
			}
		    }
		}
	    }
	}

	if ($RUN_TYPE eq "hybrid") {$infile_text .= "finidat_rtm = \'$fncheck\'\n";}
	if ($RUN_TYPE eq "branch") {$infile_text .= "nrevsn_rtm  = \'$refdir/$fncheck\'\n";}

    }

    SetupTools::create_namelist_infile("$CASEROOT", 
				       "$CASEROOT/user_nl_rtm${inst_string}", 
				       "$CASEBUILD/rtmconf/cesm_namelist", 
				       "$infile_text");

    # -----------------------------------------------------
    # call build-namelist
    # -----------------------------------------------------
    
    $sysmod = "$CCSMROOT/components/rtm/bld/build-namelist ";
    $sysmod = "$sysmod -infile $CASEBUILD/rtmconf/cesm_namelist";
    $sysmod = "$sysmod -caseroot $CASEROOT";
    $sysmod = "$sysmod -scriptsroot $SCRIPTSROOT";  
    $sysmod = "$sysmod -namelist \" \&rtmexp $RTM_NAMELIST_OPTS \/\" ";
    $sysmod = "$sysmod -inst_string \"$inst_string\" $RTM_BLDNML_OPTS";
    system($sysmod) == 0 or die "ERROR rtm.buildnml: $sysmod failed: $?\n";
    
    # -----------------------------------------------------
    # move rof_in to $RUNDIR
    # -----------------------------------------------------
    
    if (-d ${RUNDIR}) {
	$sysmod = "cp $CASEBUILD/rtmconf/rof_in ${RUNDIR}/rof_in${inst_string}";
	system($sysmod) == 0 or die "ERROR rtm.buildnml: $sysmod failed: $?\n";
    }
    
    # -----------------------------------------------------
    # increment instance counter
    # -----------------------------------------------------

    $inst_counter = $inst_counter + 1;
}

exit (0);



