// prestep-cs.cs
//

// C# Prestep app for the MPIPiCalcCS diagnostic test
// aka "MPI Pi Calculation with C# PreStep"

// Sample code reference:
// http://msdn.microsoft.com/en-us/library/ee795941%28VS.85%29.aspx

// The modified prestep code below adds a task to the diagnostic run job
// with the *NumberOfCores values of both the job and the task
// set to the number of nodes in the test run.
// This better suits executing and testing an MPI job on your HPC cluster.

using System ;
using System.Text ;
using Microsoft.Hpc.Scheduler ;

namespace prestep_cs
{
//
//
class Program
{
const char PRESTEP_CS_DBLQT_C = '\"' ;
//
//
public static int Main(string[] args)
{
	if (null == args || args.Length < 8)
	{
		return 1 ;
	}

	IScheduler scheduler = new Scheduler() ;
	scheduler.Connect(args[0]) ; // Name of the cluster's head node

	int jobid = Int32.Parse(args[1]) ; // RunStep job id number

	ISchedulerJob job = scheduler.OpenJob(jobid) ;
	job.AutoCalculateMax = false ;
	job.AutoCalculateMin = false ;

	string nodelist = args[2] ; // hpcHead,hpcNode01,hpcNode02
	int nodecount = 0 ;
	IStringCollection nodes = scheduler.CreateStringCollection() ;
	foreach (string node in nodelist.Split(','))
	{
		nodes.Add(node) ;
		nodecount++ ;
	}

	job.MinimumNumberOfNodes = nodecount ;
	job.MaximumNumberOfNodes = nodecount ;

	ISchedulerTask task = job.CreateTask() ;

	task.RequiredNodes = nodes ;

	task.WorkDirectory = args[3] ; // \\hpcHead\C$\Diag\MPIPiCalcuation It's OK if path has spaces in it here.

	string cmdline = args[4] ; // {0} {1} {2}
	string fmtstr0 = PRESTEP_CS_DBLQT_C + args[5] + PRESTEP_CS_DBLQT_C ; // "mpiexec.exe" Prepend and postpend double quotes in case the filename has spaces in it.
	string fmtstr1 = PRESTEP_CS_DBLQT_C + args[6] + PRESTEP_CS_DBLQT_C ; // "picalc-cs-mpi.exe" Prepend and postpend double quotes in case the filename has spaces in it.
	string NumIntervals = "10E6" ; // Default value of 10E6.
	if (args.Length >= 8)
	{
		NumIntervals = args[7].Substring(6) ; // -sn01:1000000 ---> 1000000 Keep it as a string in case it was specified in scientific format e.g. 1E9, or as a number bigger than 2 billion, e.g. 5000000000.
	}
	task.CommandLine = String.Format(cmdline,fmtstr0,fmtstr1,NumIntervals) ; // "mpiexec.exe" "picalc-cs-mpi.exe" 1000000

	task.MinimumNumberOfNodes = nodecount ;
	task.MaximumNumberOfNodes = nodecount ;

	job.AddTask(task) ;

	job.Commit() ;

	return 0 ;
}

} // class Program
} // namespace prestep_cs

