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

if ($#ARGV == -1) {
    die " ERROR docn.buildexe: 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 $CIMEROOT	= `./xmlquery  CIMEROOT	   -value`;
my $NINST_OCN	= `./xmlquery  NINST_OCN   -value`;
my $RUNDIR	= `./xmlquery  RUNDIR      -value`;
my $SCRIPTSROOT	= `./xmlquery  SCRIPTSROOT -value`;

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

my $inst_string;
my $inst_counter = 1;
while ($inst_counter <= $NINST_OCN) {

    # -----------------------------------------------------
    # determine instance string 
    # -----------------------------------------------------

    $inst_string = "";       
    if ($NINST_OCN > 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.ocn${inst_string}") && (-e "$RUNDIR/rpointer.ocn") ) {
	    $sysmod = "cp -v $RUNDIR/rpointer.ocn $RUNDIR/rpointer.ocn${inst_string}";
	    system($sysmod) == 0 or die "ERROR docn.buildnml: $sysmod failed: $?\n";
	}
    }

    # -----------------------------------------------------
    # create docnconf/cesm_namelist
    # -----------------------------------------------------

    SetupTools::create_namelist_infile("$CASEROOT", 
				       "$CASEROOT/user_nl_docn${inst_string}", 
				       "$CASEBUILD/docnconf/cesm_namelist"); 

    # -----------------------------------------------------
    # call build-namelist
    # -----------------------------------------------------

    $sysmod = "$CIMEROOT/components/data_comps/docn/bld/build-namelist";
    $sysmod = "$sysmod -infile $CASEBUILD/docnconf/cesm_namelist";
    $sysmod = "$sysmod -caseroot $CASEROOT";
    $sysmod = "$sysmod -scriptsroot $SCRIPTSROOT";
    $sysmod = "$sysmod -inst_string \"$inst_string\"";
    $sysmod = "$sysmod -user_xml_dir \"$CASEROOT/SourceMods/src.docn\"";
    system($sysmod) == 0 or die "ERROR docn.buildnml: $sysmod failed: $?\n";

    if (-d ${RUNDIR}) {
	$sysmod = "cp $CASEBUILD/docnconf/docn_in     ${RUNDIR}/docn_in${inst_string}";
	system($sysmod) == 0 or die "ERROR docn.buildnml: $sysmod failed: $?\n";

	$sysmod = "cp $CASEBUILD/docnconf/docn_ocn_in ${RUNDIR}/docn_ocn_in${inst_string}";
	system($sysmod) == 0 or die "ERROR docn.buildnml: $sysmod failed: $?\n";

	$sysmod = "cp $CASEBUILD/docnconf/*txt*       ${RUNDIR}/ >& /dev/null";
	system($sysmod) == 0 or die "ERROR docn.buildnml: $sysmod failed: $?\n";
    }

    # -----------------------------------------------------
    # increment instance counter
    # -----------------------------------------------------

    $inst_counter = $inst_counter + 1;

}

exit (0);
