rocess either doesnt exist or was commanded to stop before it ran 
            NotRequired // For transfer we use this to suggest that no transfer was needed, 
                        // I.E. Exited without transferring anything, although it is only currently implemented in SchedulerBase.
        }

        #region VariableDeclarations

        // A lock that is used only when storing the job id in it's private field and when KillJob needs to get the job id
        private readonly object _jobIdSubmitAndKillSyncLock = new object();

        // These files are the cluster job that is run.  control.txt contains the commands to execute.
        public const string ControlFileName = "control.txt";
        public const string CommandsXmlFileName = "commands.xml";

        // These are files that may be generated during the course of the RSM job execution
        public const string ClusterJobCustomizationFileName = "ClusterJobCustomization.xml";
        public const string HostsFileName = "hosts.dat";
        public const string ExitCodeFileName = "exitcode.rsmout"; // matches ClusterJobs.py
        public const string ClusterStdOutLiveLogFileName = "stdout.live";
        public const string ClusterStdErrLiveLogFileName = "stderr.live";
        public const string ClusterInquireRequestFileName = "inquire.request";  // matches ClusterJobs.py
        public const string ClusterInquireConfirmFileName = "inquire.confirm";  // matches ClusterJobs.py
        private const string PsshRemoteInputCacheFileName = "pssh_remote_input_snapshot_cache.rsm";  // Should always match the same constant in the transfer python script
        private const string RestartFileName = "restart.xml";

        private const string TransferSshDirectorySharedVariableName = "RSM_HPC_DIRECTORY_SHARED";

        // More readonly variables set at construction
        private readonly string _clusterStagingPath;   // cluster-side form of staging path.  maybe same as local form if platforms the same
        private readonly string _clusterLocalScratchPath;

        private readonly bool _usingLocalScatch;
        private readonly bool _allowDistributed;

        private readonly string _fileExclusions;
        private readonly string _inquireExclusions;
        private readonly string _uploadExclusions;

        private readonly ClusterType _clusterType;
        private readonly ITask _task;

        private readonly int _externalCancelFileDownloadTimeout; 

        // Non Readonly/Constant State Variables
        private bool _externalTransferCleanupRequired;
        private bool _repeatMessageDisplayed = false;
        private bool _disposed = false;
        private string _jobId = null;

        private ClusterStatus _finalStatus = ClusterStatus.Unknown;
        
        private ClusterApi _clusterApi;

        #endregion

        #region Constructors

        // Defaults are set here, such as allowLocalScratch = True and AllowDistributed=False
        public SchedulerBase(ITask task)
            : this(task, true, false)
        { }

        public SchedulerBase(ITask task, bool allowLocalScratch, bool allowDistributed)
        {
            // Assign Basic Variables
            this._task = task;
            this._allowDistributed = allowDistributed;
            this._clusterType = task.ClusterType;
            this._externalTransferCleanupRequired = task.CleanProxyPath;  // DE83078 - Need to differentiate between cleaning WorkDir and SSH Proxy in case SMB shared

            // Setup Cluster Staging and Scratch
            this._clusterStagingPath = SchedulerBaseUtilities.DetermineClusterStagingDirectory(task, task.WorkingDirectory);
            if (allowLocalScratch && !string.IsNullOrEmpty(task.ProxySshScratchDir))
            {
                var tmpLocalScratch = SchedulerBaseUtilities.DetermineClusterScratchPath(task, task.WorkingDirectory);
                // If local scratch is determined to be custom, then we are not using local scratch
                if (tmpLocalScratch.Equals("CUSTOM"))
                    this._usingLocalScatch = false; // Don't cache tmp local scratch if we are not using local scratch
                else
                {
                    this._clusterLocalScratchPath = tmpLocalScratch;
                    this._usingLocalScatch = true;
                }
            }

            if (!allowDistributed)
                task.AddMessage(TaskMessageType.Information, TaskMessageSource.Job, 60000/*30023*/, "ID_CannotBeDistributed", true);

            // Create all the different types of files exclusions
            Tuple<string, string, string> exclusions = SetupFileExclusions(task);
            _fileExclusions = exclusions.Item1;
            _inquireExclusions = exclusions.Item2;
            _uploadExclusions = exclusions.Item3;

            // supported clusters using external HPC commands internally behave as custom cluster integrated jobs in the sense that
            // they will honor the RSM_HPC_xxxx variables.

            // TODO: Is this used anymore?
            Environment.SetEnvironmentVariable("RSM_HPC_INTEGRATION", "TRUE", EnvironmentVariableTarget.Process);
            task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "NOTE: Using external HPC commands.");

            ClusterCustomization customization = new ClusterCustomization(task);
            customization.Load();

            _externalCancelFileDownloadTimeout = ApplicationConfiguration.AppSettingsConfiguration.JobScriptSettings.Get<int>(ApplicationSettingsConstants.CancelFileDownloadTimeout);
        }

        /// <summary>
        /// Only Use For Testing.
        /// </summary>
        internal SchedulerBase()
        {
            this._task = null;
            this._allowDistributed = false;
            this._clusterType = ClusterType.NONE;
            this._externalTransferCleanupRequired = true;
        }

        #endregion
                
        #region Properties

        private IEnumerable<string> FilesToUpload
        {
            get
            {
                yield return ControlFileName;
            }
        }

        public bool UsingLocalScratch
        {
            get { return _usingLocalScatch; }
        }

        public bool IsQueueRequired
        {
            get
            { return (this._clusterType != ClusterType.NONE) && this._clusterApi.UsesQueues(); }
        }

        public ClusterStatus FinalStatus
        {
            get { return _finalStatus; }
        }

        public string LocalScratchPath
        {
            get { return this._clusterLocalScratchPath; }
        }

        #endregion

        #region (Public) Job Level Methods

        public string SubmitJob(ITask task, IJobHandle handle)
        {
            // CHECK IF A RESTART FILE EXISTS.  If so, can just load restart file and return job ID
            _jobId = CheckRestartInfo(task);
            if (!string.IsNullOrEmpty(_jobId))
            {
                return _jobId;
            }

            List<string> filesToUpload = new List<string>();

            // If first attempt at a command fails, the rest will likely fail also so Fail the job
            filesToUpload.AddRange(GetFileListByTag(task.InputFiles, "normal"));
            filesToUpload.AddRange(this.FilesToUpload);

            if (handle.HasBeenKilled)
                return null;

            // CWD of submit command needs to be staging path so stdio files are put there. DO NOT use overridden staging path here (RSM_HPC_STAGING) since
            // that may be path on remote cluster.  This process is being started here.
            var clusterJobDefintion = new DefaultClusterJobCommandDefinition(this, filesToUpload.AsReadOnly(), task.WorkingDirectory, this._clusterStagingPath, ControlFileName);
            var submitResults = this._clusterApi.Submit(handle, task.WorkingDirectory, clusterJobDefintion);

            if (submitResults.FailureOccurred)
            {
                task.AddMessage(TaskMessageType.Error, TaskMessageSource.Cluster, 60016, "ID_ClusterFatalSubmissionError", true);
            }

            if (submitResults.RanToSuccessfulCompletion && !handle.HasBeenKilled)
            {
                string tmpJobId = ParseJobID(task, ((IExternalCommandResults)submitResults.PrimaryCommandResults).Stdout, GetClusterTypeFromResults(submitResults), GetParseMarkerFromResults(submitResults));

                // Do not put any logic inside this lock block that could hang.  This locks only purpose is to close
                // a timing vulnerability between when we have the job id and when abort could happen.
                // In order for abort to kill a running job on the cluster it needs the job id.  But abort also needs to be able to clean
                // up a hung submit or kill an in progress submit.

                // NOTE by Mike (3/31/2014) : There is still at least one vulnerability here.  The situation is, what if we kill a submit command while it was submitted the job to the cluster,
                // but then we don't get enough of the stdout to parse the job id.  Then we would leave a job stranded on the cluster.
                // I will address this issue after the initial wave of changes has been made
                lock (this._jobIdSubmitAndKillSyncLock)
                {
                    // Now that we have the lock that syncs with Kill, we need to check one more time to see if
                    // we've been killed before we store the job id
                    if (!handle.HasBeenKilled)
                    {
                        _jobId = tmpJobId;
                    }
                }
            }

            if (!string.IsNullOrEmpty(_jobId))
            {
                // this must be set for cancel command
                SaveRestartInfo(task);
            }

            return _jobId;
        }

        public virtual void InterruptJob(ITask task, IJobHandleForAsyncOperation handle)
        {
            // Transfer "cancel" file(s) to HPC cluster.
            CommandExitStatus commandExitStatus;
            if (TryUploadFileNameCollection(task, handle, GetFileListByTag(task.InputFiles, "cancel"), string.Empty, "CANCEL", "UploadInterruptFiles", out commandExitStatus))
                if (!(commandExitStatus == CommandExitStatus.Success || commandExitStatus == CommandExitStatus.NotRequired))  // These files are supposed to get copied when the job is ending
                    task.AddMessage(TaskMessageType.Warning, TaskMessageSource.Cluster, 60000, "ID_RemoteMachineOperationFailed", true, "Upload", "Interrupt Files");
        }

        public virtual bool InquireJob(ITask task, IJobHandleForAsyncOperation handle, IEnumerable<string> tags)
        {
            // Nothing to do:
            if (tags == null || !tags.Any())
                return true;

            // 1) Create file list for inquire
            if (string.IsNullOrEmpty(_jobId))
            {
                task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "Cluster job has not been submitted.");
                return false;
            }

            HashSet<string> tagList = new HashSet<string> {};
            HashSet<string> fileList = new HashSet<string> {};

            foreach (string tag in tags)
            {
                if (tag.StartsWith("file:"))
                    fileList.Add(tag.Substring(5));
                else
                    tagList.Add(tag);
            }

            // 2) Check to see if we have any valid files
            if (! (tagList.Any() || fileList.Any()))
                return true;

            HashSet<string> inquireList = fileList;
            inquireList.UnionWith(GetFileListByTag(task.OutputFiles, tagList));

            CommandExitStatus commandExitStatus;

            // 3) If using local scratch, create an inquire file for cluster jobs
            // If we are not using local scratch, then there is no reason to use the inquire.request, just skip to download the files from the CS.
            if (this._usingLocalScatch)
            {
                string requestFile = Path.Combine(task.WorkingDirectory, SchedulerBase.ClusterInquireRequestFileName);
                string confirmFilePath = Path.Combine(task.WorkingDirectory, SchedulerBase.ClusterInquireConfirmFileName);

                // We should check that the directory is in the proper state before we start so there are no unexpected results.  
                // Since we have not started the inquire procedure yet, this file should NOT be here.
                if (File.Exists(confirmFilePath))
                {
                    task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Job, 0, "Inquire Confirmation Found before request, trying to remove.");
                    Utilities.TryToDeleteFile(task, confirmFilePath);
                }

                // Place file indicating request for inquire files in the working directory.
                using (StreamWriter file = new StreamWriter(requestFile))
                    foreach (string fileName in inquireList)
                        file.WriteLine(fileName);

                // 4) If using external transfer commands, be sure to upload the files to remote machine
                if (TryUploadFileNameCollection(task, handle, new List<string>() { requestFile }, string.Empty, "INQUIRE", "UploadInquireRequest", out commandExitStatus))
                {
                    // Only delete the file if there was an external command, otherwise we assume clusterjobs is monitoring the workdir so we need to leave it.
                    if (commandExitStatus != CommandExitStatus.NotRequired)  // dont delete if transfer command determined that it didnt need to copy, like SMB case
                        Utilities.TryToDeleteFile(task, requestFile); // this is the local file, a copy should be on the remote machine already 

                    // 5) If upload fails then return false so we dont get stuck in the loop to wait for a reply
                    // (5/2/2014) Jon: Return false now means that the inquire request had an error while running, return true for stopping on request...
                    if (commandExitStatus == CommandExitStatus.NotRun || commandExitStatus == CommandExitStatus.Killed)
                        return true;
                    if (commandExitStatus == CommandExitStatus.Failure)
                        return false;
                }

                // Wait for the inquire.confirm file so that we know the inquire files have been copied from the scratch directory
                // to the staging directory.  During PSSH jobs, transfer_SSH.py will have waited for the confirm file to exist in the staging
                // directory and it will create the confirm file locally for us to find

                task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Job, 0, "Waiting for inquire confirmation from cluster job");
                
                string exitCodeFilePath = Path.Combine(task.WorkingDirectory, SchedulerBase.ExitCodeFileName);

                // 6) Check if the job should be stopped while waiting for the confirmation (Both from handle.shouldstop and ifExists(Clusterjobs Exitcode File))
                while (!(File.Exists(confirmFilePath) || File.Exists(exitCodeFilePath) || handle.ShouldStop))
                    Thread.Sleep(500); // Keep this short, but not so short as to cause file access problems with high job volume...  Up for debate...

                if (File.Exists(confirmFilePath))
                    task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Job, 0, "File copy from cluster job confirmed");

                // If the cancel is called or exitcode is found, We could potentially exit this loop before clusterjobs gets a chance to delete
                // the request file (for the non external commands case). Thus, we should *try to clean up the request file as well as the confirm file
                Utilities.TryToDeleteFile(task, requestFile);
                Utilities.TryToDeleteFile(task, confirmFilePath);
            }

            // 7) If using external transfer commands, be sure to download the inquire files from the remote machine
            if (TryDownloadFileNameCollection(task, handle, inquireList, _inquireExclusions, "INQUIRE", "DownloadInquireFiles:" + FileNameListToStringFormat(inquireList), out commandExitStatus))
                if (commandExitStatus == CommandExitStatus.Failure) // If job is not run or killed, we assume success...
                    return false;

            return true;
        }

        public void KillJob(ITask task)
        {
            _finalStatus = ClusterStatus.Cancelled; // used for cancel during file upload

            // Note by Mike (3/26/2014) : This lock is safe to take because only submit takes it, and it only takes it while it is storing
            // the job id in it's private field
            lock (_jobIdSubmitAndKillSyncLock)
            {
                if (string.IsNullOrEmpty(_jobId))
                {
                    task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "Cluster job has not been submitted.");
                    return;
                }
            }

            // cancel command ignores above terminate event
            // We don't want cancel to take any unnecessary locks because it introduces the possibility of a hang if another operation has a bug and hangs inside the lock.
            // so we'll use the run command helper that doesn't take the external command lock
            if (!this._clusterApi.UsesCancel())
            {
                task.AddMessage(TaskMessageType.Warning, TaskMessageSource.Cluster, 60000, "ID_HpcCommandUndefined", true, "cancel");
                return;
            }

            this._clusterApi.Cancel(task.WorkingDirectory, this._jobId);
        }

        public bool CheckQueue(ITask task, IJobHandle handle, string queue, string nativeSettings)
        {
            // If nativeSettings has -q then just allow job to go.
            if (!string.IsNullOrEmpty(nativeSettings) && nativeSettings.Contains("-q"))
                return true;

            // Any Commands File that does not have Queues Defined will ignore this code (Think, MSCC)
            if (!this._clusterApi.UsesQueues())
                return true;

            task.AddMessage(TaskMessageType.Information, TaskMessageSource.Cluster, 60007, "ID_CheckingQueueExists", true, queue);

            var topLevelCommandResults = this._clusterApi.GetQueues(handle, task.WorkingDirectory, this._jobId);

            // This is a little ugy, casting to process results, but this queues parsing logic shouldn't even be in C#.  It should be defined in hpc_commands some how.
            // Then it would just define and output variable, which is very easy to get to on the top level command results.
            // until then, we have to cast and assume it was a process and get ahold of stdout that way.
            var primaryOperationProcessResults = topLevelCommandResults.PrimaryCommandResults as IExternalCommandResults;
            if (primaryOperationProcessResults == null)
            {
                throw new InvalidOperationException(string.Format(task.GetLocalizedString("ID_CommandExpectedToBeExternal"), HpcCommandsReader.StandardCommandNameQueues));
            }

            if (topLevelCommandResults.FailureOccurred)
            {
                task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 60002, "ID_HpcCommandFailed", true, HpcCommandsReader.StandardCommandNameQueues);
                return false;
            }

            ReadOnlyCollection<string> queues = ParseQueues(task, primaryOperationProcessResults.Stdout, primaryOperationProcessResults.Stderr, GetClusterTypeFromResults(topLevelCommandResults), GetParseMarkerFromResults(topLevelCommandResults));

            if (queues == null)
                return true; // queue command failed.  submit will probably fail also but give it a try

            if (!queues.Contains(queue))
            {
                task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 60002, "ID_NoQueue", true, "Cluster", queue);
                return false;
            }

            return true;
        }

        public bool CheckParallelEnvironment(ITask task, IJobHandle handle, string pe)
        {
            // null pe means pe is not needed or not defined, maybe the cluster type is not UGE so the value will remain to be null.
            if (string.IsNullOrEmpty(pe))
                return true;

            // For non UGE clusters this should not be defined, and for UGE clusters it will be optional just like Queues.
            if (!this._clusterApi.UsesQueryParallelEnvironment())
                return true;

            task.AddMessage(TaskMessageType.Information, TaskMessageSource.Cluster, 60007, "ID_CheckingParallelEnvironment", true, pe);

            ITopLevelCommandResults topLevelCommandResults = this._clusterApi.GetParallelEnvironments(handle, task.WorkingDirectory, this._jobId);

            IExternalCommandResults primaryOperationProcessResults = topLevelCommandResults.PrimaryCommandResults as IExternalCommandResults;
            if (primaryOperationProcessResults == null)
            {
                throw new InvalidOperationException(string.Format(task.GetLocalizedString("ID_CommandExpectedToBeExternal"), "checkPe"));
            }

            if (topLevelCommandResults.FailureOccurred)
            {
                task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 60002, "ID_HpcCommandFailed", true, "checkPe");
                return false;
            }

            ReadOnlyCollection<string> pes = ParseParallelEnviornment(task, primaryOperationProcessResults.Stdout, primaryOperationProcessResults.Stderr, GetClusterTypeFromResults(topLevelCommandResults), GetParseMarkerFromResults(topLevelCommandResults));

            if (pes == null)
                return true; // pe command failed.  submit will probably fail also but give it a try

            if (!pes.Contains(pe))
            {
                task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 60002, "ID_NoParallelEnvironmentDefined", true, pe);
                return false;
            }

            return true;
        }

        public ClusterStatus GetStatus(ITask task, IJobHandle handle, bool showOutput)
        {
            if (string.IsNullOrEmpty(_jobId))
                throw new ApplicationException(task.GetLocalizedString("ID_LSFBSUBFailed"));

            ITopLevelCommandResults topLevelCommandResults;
            if (_clusterType == ClusterType.PBS || _clusterType == ClusterType.NONE)
                topLevelCommandResults = this._clusterApi.GetStatus(handle, task.WorkingDirectory, this._jobId, new JobFinishedOnStatusErrorNotifications(task));
            else
                topLevelCommandResults = this._clusterApi.GetStatus(handle, task.WorkingDirectory, this._jobId, new GenericClusterErrorNotifications(task));

            // Check failed first, it will not be true if the command was stopped.
            if (topLevelCommandResults.FailureOccurred)
            {
                // For PBS we should assume that status (qstat) command failure means this job is finished.
                // TODO: what do we do if qstat accidently fails, like from cluster congestion?  This means job will end early and probably break right now...
                // TODO: Possibly we can check exitcode.rsmout to determine if the status is finished or not, if not maybe we send back Unknown in order to retry.
                if (GetClusterTypeFromResults(topLevelCommandResults) == ClusterType.PBS || GetClusterTypeFromResults(topLevelCommandResults) == ClusterType.NONE)
                {
                    DownloadLiveStdio(handle);  // get the last bit of stdout like other finished jobs would...
                    _finalStatus = ClusterStatus.Finished;
                    return ClusterStatus.Finished;
                }

                // Other Failures Occured just means the Status command didn't respond as expected, we need to give an unknown state to give the retry mechanism a chance...
                return ClusterStatus.Unknown;
            }

            if (topLevelCommandResults.WasStopped || handle.HasBeenKilled)
                return ClusterStatus.Cancelled;

            // This is a little ugy, casting to process results, but this queues parsing logic shouldn't even be in C#.  It should be defined in hpc_commands some how.
            // Then it would just define and output variable, which is very easy to get to on the top level command results.
            // until then, we have to cast and assume it was a process and get ahold of stdout that way.
            var primaryOperationProcessResults = topLevelCommandResults.PrimaryCommandResults as IExternalCommandResults;
            if (primaryOperationProcessResults == null)
                throw new InvalidOperationException(string.Format(task.GetLocalizedString("ID_CommandExpectedToBeExternal"), HpcCommandsReader.StandardCommandNameStatus));

            ClusterStatus status = ParseStatus(task, handle, primaryOperationProcessResults.Stdout, primaryOperationProcessResults.Stderr, GetClusterTypeFromResults(topLevelCommandResults), GetParseMarkerFromResults(topLevelCommandResults));

            // always do some more debugging specially for Unkown status, so that we have more diagnosis info when getting into this status
            // RSM does not parse all the cluster status right now. So based on this info, we may be able to support more status if makes sense.
            if (status == ClusterStatus.Unknown)
            {
                task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "Unknown status parsed from cluster output:");
                Utilities.DisplayOutput(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, task, primaryOperationProcessResults.Stdout);
                return status;
            }

            // Get Stdio for every call of Status when job is running.  If TaskSubstatus is not running, probably interrupt has been called, so dont bother getting output anymore.
            if (status == ClusterStatus.Running && task.TaskSubStatus == TaskSubStatus.Running)
                DownloadLiveStdio(handle);

            if (status == ClusterStatus.Running || status == ClusterStatus.Queued)
                return status;

            // Remote Task should be completely finished done if it gets here.
            DownloadLiveStdio(handle);  // show end of files.
            _finalStatus = status; // Job is Done
            return status;
        }

        public void CleanUp(ITask task)
        {
            // Note by Mike (3/17/2014) : Clean up the proxy path if the flag is set.  But we still need to execute the code below
            // this if block since it is for cleaning up files that are in the local directory
            if (task.CleanProxyPath && this._externalTransferCleanupRequired)
            {
                if (this._clusterApi.UsesCleanup())
                {
                    // cleanup command ignores kill event
                    // Since it ignores the kill event, we don't need a job handle
                    this._clusterApi.Cleanup(task.WorkingDirectory, this._jobId);
                }
            }

            // We always want to clean these files...
            this.CleanUpLocalFiles(task);
        }

        #endregion

        #region Other Public Methods

        public virtual bool PreRun(ITask task, IJobHandle handle, string queue, GenericCommands commandGroup)
        {
            string parallelEnvironment = null;
            // this must be before loading HPC commands since RSM_HPC_SGE_PE may be set
            if (!string.IsNullOrEmpty(task.ProxyKeyword) && task.ProxyKeyword.Contains("SGE"))
                parallelEnvironment = HandleSgeParallelEnvironment(task, commandGroup);

            // Load config file containing HPC commands and set environment variables
            bool isRemotePlatformWindows = (commandGroup.Platform & CommandPlatform.AllWindows) != 0 ? true : false;
            SetupHpcCommands(task, isRemotePlatformWindows, commandGroup.Cores, commandGroup.Memory, commandGroup.NativeSettings, commandGroup.NodeExclusive, parallelEnvironment);

            if (!CheckParallelEnvironment(task, handle, parallelEnvironment))
                return false;

            // This check only fails if we actually get a queue list and the 'queue' argument is not in that list.
            if (!CheckQueue(task, handle, queue, commandGroup.NativeSettings))
                return false;

            GenerateControlFile(task, commandGroup);

            return true;
        }

        public virtual bool PostRun(ITask task, IJobHandle handle, bool aborted, bool failed)
        {
            CommandExitStatus commandExitStatus;
            IJobHandle jobHandlToUseForDownload = handle;
            IEnumerable<string> filesToDownload = null;
            bool jobHandleRequiresDisposing = false;

            try
            {
                // Handle difference between an aborted job and one that finished normally
                if (aborted)
                {
                    // Need to create a new job handle to use.  The one we are passed was cancelled.
                    // We'll create a 'special' one time use JobHandle that will abort itself after a specified timeout.
                    // that way, if for some reaosn, this external command hangs, the Abort is still successful in
                    // stopping the job
                    // We need to use a different job handle in this case because the job handle we are passed is the main handle and it will have already been
                    // aborted, which means any command we run with it will never be ran.
                    jobHandlToUseForDownload = new JobHandleWithTimeout(_externalCancelFileDownloadTimeout);
                    jobHandleRequiresDisposing = true;
                    filesToDownload = GetFileListByTag(task.OutputFiles, "cancel");
                }
                else
                {
                    var tmpFilesToDownload = new List<string>(); 

                    if (failed)
                    {
                        tmpFilesToDownload.AddRange(GetFileListByTag(task.OutputFiles, "failure"));
                    }
                    else
                    {
                        tmpFilesToDownload.AddRange(GetFileListByTag(task.OutputFiles, "normal"));
                    }

                    filesToDownload = tmpFilesToDownload;
                }

                // Check to see if any files were actually copied, if the command returns false because it wasnt run, then thats ok, 
                // just signal that cleanup is not required either and continue
                if (TryDownloadFileNameCollection(task, jobHandlToUseForDownload, filesToDownload, _fileExclusions, "OUTPUTS", "DownloadOutputs", out commandExitStatus))
                {
                    if (commandExitStatus == CommandExitStatus.NotRequired) // If the transfer was not done but the command exists, then it must have been shared
                        _externalTransferCleanupRequired = false;
                    return true;
                }
                else
                    return false;
            }
            finally
            {
                if (jobHandleRequiresDisposing)
                {
                    ((IDisposable)jobHandlToUseForDownload).Dispose();
                }
            }
        }
        
        public virtual bool GetExitCode(ITask task, IJobHandle handle, out int exitCode)
        {
            // If transfer is in use, then we need to give it an opportunity to grab the exit code file.
            if (this._clusterApi.UsesTransfer())
            {
                // Always use new job handle for downloading the exit code file.  This file is critical in determining if the job failed, so it should not be an
                // abortable command.  Instead, it will use a timeout to ensure that it can't run forever.
                CommandExitStatus commandExitStatus;
                using (var jobHandlToUseForDownload = new JobHandleWithTimeout(_externalCancelFileDownloadTimeout))
                {
                    var filesToDownload = new List<string>() { ExitCodeFileName, GenericJobBase.StdOutFileName, GenericJobBase.StdErrFileName };
                    if (TryDownloadFileNameCollection(task, jobHandlToUseForDownload, filesToDownload, string.Empty, "OUTPUTS", "DownloadExitCodeFile", out commandExitStatus))
                    {
                        if (commandExitStatus == CommandExitStatus.Killed || commandExitStatus == CommandExitStatus.Failure)
                        {
                            task.AddMessage(TaskMessageType.DevDebug, TaskMessageSource.Cluster, 60000, "Download of exit code file was not successful.  Reason : {0}", commandExitStatus.ToString());
                        }
                    }
                }
            }

            exitCode = -1;

            string exitCodeFile = Path.Combine(task.WorkingDirectory, ExitCodeFileName);  // Relative working directories are not supported, so this should always be "full path".

            // DE85929 - We will wait for some long time for exitcode to show up in case of slow network shares.  
            // We dont want any job to die just because exitcode was slow to appear in the share directory
            int waitTime = ApplicationConfiguration.AppSettingsConfiguration.JobScriptSettings.Get<int>(ApplicationSettingsConstants.ExitCodeWaitingTimeout); // This can throw an exception...

            // This will check 8 times total, once immediately and then 7 retries over 60 seconds.
            if (!Utilities.WaitForFileToExist(task, exitCodeFile, waitTime, 7, handle) && !handle.ShouldStop)  // Dont throw the exception if the waiting was stopped by a cancel request.
            {
                task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, string.Format(task.GetLocalizedString("ID_ExitCodeNotFound"), exitCodeFile));
                return false;
            }

            StreamReader reader = new StreamReader(exitCodeFile);
            string line = reader.ReadLine();
            reader.Close();
            Utilities.TryToDeleteFile(task, exitCodeFile);

            if (!int.TryParse(line, out exitCode))
            {
                task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "Exitcode file found, but couldn't determine exit code: {0}", line);
                return false;
            }

            task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "Exit code returned from job: {0}", exitCode);

            return true;
        }

        public void DisplayKillWarnings(ITask task)
        {
            if (this._usingLocalScatch)
                task.AddMessage(TaskMessageType.Warning, TaskMessageSource.Job, 30000, "ID_LocalScratchNeedsCleanup", true);
        }

        public static void HandleJobRuntimeError(ITask task, int exitCode)
        {
            switch (exitCode)
            {
                case 1000:
                    task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 30009, "ID_AWPROOTNotSetOnComputeNode", true, ApplicationConfiguration.AwpRootEnvironmentVariableName);
                    break;
                case 1001:
                    task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 30010, "ID_FailedToGetNodeArray", true);
                    break;
                case 1002:
                    task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 30013, "ID_ClusterNodesNotAssigned", true);
                    break;
                case 1003:
                    task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 30014, "ID_FailedToCreateWorkingDirLocallyOnExecutionNode", true);
                    break;
                case 1004:
                    task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 30015, "ID_FailedToCreateWorkingDirFromNodeShare", true);
                    break;
                case 1005:
                    task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 30016, "ID_FailedToLocateClusterShareDirectory", true);
                    break;
                case 1006:
                    task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 30017, "ID_ErrorReadingJobControlFile", true);
                    break;
                case 1007:
                    task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 30018, "ID_FailedToFindPythonExeFromWBInstall", true);
                    break;
                case 1008:
                    task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 30031, "ID_ClusterSharedDirectoryNotFoundOnExecutionNode", true);
                    break;
                case 1009:
                    task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 30032, "ID_AWPROOTNotExistFromExecutionNode", true, ApplicationConfiguration.AwpRootEnvironmentVariableName);
                    break;
                case 1010:
                    task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 30033, "ID_ExitCodeFileNotFoundOnClusterJob", true);
                    break;
                case 9999:
                    task.AddMessage(TaskMessageType.Error, TaskMessageSource.Job, 30027, "ID_FatalErrorRunningClusterJobCommandsAndNoExitCode", true);
                    break;
                default:
                    break;
            }
        }

        public void GenerateControlFile(ITask task, GenericCommands jobCommands)
        {
            string targetCluster = "AutoDetermine";
            /*
             format of the control file, read by ClusterJob.js
            
                  targetCluster     // "LSF" "PBS" "SGE", "MSCC"
                  the headnode
                  job command (e.g. ansys130.exe)
                  job arguments
                  job redirect file or 'null'
                  job command (e.g. ansys130.exe)
                  job arguments
                  job redirect file or 'null'
                  ...
                  done
                  c:\temp\unique_folder
                  \\headnode\temp\unique_folder
                  cleanup           // boolean flag whether to clean up files
                  UseSSHForPeerNode  // boolean flag whether to use SSH (Linux cluser only)
                  cores per node
                  livelog filename
                  stdout live monitor filename
                  stderr live monitor filename
                  file1             // input files
                  ...
                  fileN
                  done
                  file1            // cancel files - periodically pulled from staging
                  ...
                  fileN
                  done
                  file1            // output files
                  ...
                  fileN
                  done
                  file1            // inquire files  - periodically posted back  to staging
                  ...
                  fileN
                  done
                  file1            // exclude files - New In V16
                  ...
                  fileN
                  done
                  NAME            // envrionment vars
                  VALUE
                  NAME
                  VALUE
                  ...
                  done
                  Utilities.AwpRootEnvironmentVariableName
                  (decimal)DiskSpaceLowWarningLimitGb
            */

            string controlFile = Path.Combine(task.WorkingDirectory, SchedulerBase.ControlFileName);

            StreamWriter writer = new StreamWriter(controlFile);

            writer.WriteLine(targetCluster);  // Always passing custom cluster for "Auto Detect"...

            // the headnode to us is the machine we're running on
            // For SSH we are never running on headnode
            writer.WriteLine(System.Net.Dns.GetHostName());

            foreach (GenericCommand jobCommand in jobCommands.Commands)
            {
                task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "ID_ExecuteCommand", true, jobCommand.Application, jobCommand.Arguments, jobCommand.Name);

                if (!jobCommand.WaitForExit)
                    task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "WaitForExit == false is not supported for HPC jobs");

                writer.WriteLine(jobCommand.Application);
                writer.WriteLine(jobCommand.Arguments);
                writer.WriteLine(string.IsNullOrEmpty(jobCommand.RedirectFile) ? "null" : jobCommand.RedirectFile);
            }

            writer.WriteLine("done");

            string localScratchPath;
            if (this._usingLocalScatch)
            {
                localScratchPath = this._clusterLocalScratchPath;
            }
            else
            {
                localScratchPath = "NOSCRATCH";
            }

            writer.WriteLine(localScratchPath);
            if (!localScratchPath.Equals("NOSCRATCH"))
                task.AddMessage(TaskMessageType.Important, TaskMessageSource.Cluster, 60000, "ID_LocalJobPath", true, localScratchPath);

            writer.WriteLine(_clusterStagingPath);
            if (targetCluster != "NONE") // No need for this now, but leave for when we possibly implement the ClusterType again.
            {
                task.AddMessage(TaskMessageType.Important, TaskMessageSource.Cluster, 60000, "ID_NetworkStaginePath", true, _clusterStagingPath);
            }
            writer.WriteLine(task.CleanProxyPath ? "true" : "false");

            bool useSSHOnLinux = task.UseSSHForLinuxMPI;

            writer.WriteLine(useSSHOnLinux ? "SSH" : "RSH");

            writer.WriteLine(string.IsNullOrEmpty(jobCommands.LiveLogFileName) ? "NOLIVELOGFILE" : jobCommands.LiveLogFileName);

            writer.WriteLine(SchedulerBase.ClusterStdOutLiveLogFileName);
            writer.WriteLine(SchedulerBase.ClusterStdErrLiveLogFileName);

            // INPUTS
            foreach (ITaskFile taskFile in task.InputFiles)
            {
                if (taskFile.SpecialTag.Equals("normal"))
                    writer.WriteLine(taskFile.FileName);
            }
            writer.WriteLine("done");

            // CANCEL
            foreach (ITaskFile taskFile in task.InputFiles)
            {
                if (taskFile.SpecialTag.Equals("cancel"))
                    writer.WriteLine(taskFile.FileName);
            }
            writer.WriteLine("done");

            // OUTPUT
            foreach (ITaskFile taskFile in task.OutputFiles)
            {
                // DE10871: include 'failure' files in with normal so they are
                // put where they're supposed to be.
                //
                if (taskFile.SpecialTag.Equals("normal") || taskFile.SpecialTag.Equals("failure"))
                    writer.WriteLine(taskFile.FileName);
            }
            writer.WriteLine("done");

            // INQUIRE (inquire files are all files that arent normal,failure, or exclude types...)
            //
            // DE10871: put 'cancel' files in with inquire files so they are periodically
            // moved to where they can be retrieved.  The clusterjobs.ipy script can't
            // handle these specially in the script because when a cluster job is cancelled the
            // script is immediately killed so nothing further can happen.
            //
            foreach (ITaskFile taskFile in task.OutputFiles)
            {
                if (taskFile.SpecialTag.Equals("normal") ||
                    //taskFile.SpecialTag.Equals("cancel") ||
                    taskFile.SpecialTag.Equals("failure") ||
                    taskFile.SpecialTag.Equals("exclude"))
                    continue;

                writer.WriteLine(taskFile.FileName);
            }

            writer.WriteLine("done");

            // EXCLUDE
            //
            // DE77529 - CFX and other addins can possibly fail with local scratch enabled when the input files are changed
            // by SEC and attempted to copy back to shared cluste directory at the end of the solve, this causes an error in shutil.copy2()
            // because the inputs are owned by rsmadmin in the shared cluster directory and the user does not have access to chmod/utime
            // another persons file.  This particular defect can be fixed by simply passing down the exclude files (which contain the file
            // in question) which would stop cluster jobs from every copying it back from the local scratch.
            foreach (ITaskFile taskFile in task.OutputFiles)
            {
                if (taskFile.SpecialTag.Equals("exclude"))
                    writer.WriteLine(taskFile.FileName);
            }

            List<string> _fileList = _fileExclusions.Split(';').ToList();

            foreach (string file in _fileList)
            {
                writer.WriteLine(file);
            }

            writer.WriteLine("done");

            // environment variables
            foreach (KeyValuePair<string, string> pair in jobCommands.Environment)
            {
                writer.WriteLine(pair.Key);
                writer.WriteLine(pair.Value);
            }

            writer.WriteLine("done");

            writer.WriteLine(ApplicationConfiguration.AwpRootEnvironmentVariableName);

            // Even though this is a decimal, convert it as a string so it is culture invariant.  Python will break with some culture settings, like 2,0 vs 2.0.
            writer.WriteLine(ApplicationConfiguration.AppSettingsConfiguration.GlobalSettings.Get<string>(ApplicationSettingsConstants.DiskSpaceLowWarningLimitGb));

            writer.Close();
        }

        public void Dispose()
        {
            if (!_disposed)
            {
                if (_clusterApi != null)
                    _clusterApi.Dispose();

                _disposed = true;
            }
        }

        #endregion

        #region Private Methods

        private void DownloadLiveStdio(IJobHandle handle)
        {
            CommandExitStatus commandExitStatus;
            List<string> liveOutput = new List<string>() { SchedulerBase.ClusterStdOutLiveLogFileName, SchedulerBase.ClusterStdErrLiveLogFileName };

            if (TryDownloadFileNameCollection(_task, handle, liveOutput, (string)null, "INQUIRE", "DownloadLiveStdOut", out commandExitStatus))
                if (commandExitStatus == CommandExitStatus.Failure)  // Only output warning if it failed, but not if it was stopped intentionally.
                    _task.AddMessage(TaskMessageType.Warning, TaskMessageSource.Cluster, 60000, "ID_LiveLogInquireFailed", true);
        }

        private void SetupHpcCommands(ITask task, bool isRemotePlatformWindows, int coresRequested, long memRequested, string nativeSettings, 
            bool nodeExclusive, string sgePe)
        {
            bool isLocalPlatformWindows = Environment.OSVersion.Platform != PlatformID.Unix;
            var resourceData = new ResourceData(coresRequested, memRequested, this._allowDistributed, nodeExclusive, sgePe);
            var taskData = new TaskData(task, nativeSettings);
            var otherData = new OtherData(isLocalPlatformWindows, isRemotePlatformWindows, GenericJobBase.StdOutFileName, GenericJobBase.StdErrFileName, _clusterStagingPath, _clusterLocalScratchPath);
            
            IDictionary<string, VariableValue> variables;

            if (task.ProxyUseSSH)
            {
                string keypath = string.Empty;
                if (isLocalPlatformWindows)
                {
                    keypath = Environment.GetEnvironmentVariable("KEYPATH");
                }

                var sshProtocolData = new SshProtocolData(task.ProxyAccount, task.ProxyMachine, keypath);
                variables = HpcCommandsUtilities.GetRsmDefinedVariablesWithSsh(resourceData, taskData, otherData, sshProtocolData);
            }
            else
            {
                variables = HpcCommandsUtilities.GetRsmDefinedVariables(resourceData, taskData, otherData);
            }

            this._clusterApi = new ClusterApi(task.ProxyKeyword, task.WorkingDirectory, variables, this, new GenericClusterErrorNotifications(task));
        }

        private Tuple<string,string,string> SetupFileExclusions(ITask task)
        {
            HashSet<string> exclusions = new HashSet<string>() {
                SchedulerBase.ControlFileName,
                SchedulerBase.HostsFileName,
                SchedulerBase.ClusterStdOutLiveLogFileName,
                SchedulerBase.ClusterStdErrLiveLogFileName,
                GenericJobBase.StdOutFileName,
                GenericJobBase.StdErrFileName,
                SchedulerBase.ExitCodeFileName,
                SchedulerBase.ClusterJobCustomizationFileName,
                DefaultClusterJobCommandDefinition.ClusterJobScriptFileName,
                DefaultClusterJobCommandDefinition.ClusterWrapperScriptNameWindows,
                DefaultClusterJobCommandDefinition.ClusterWrapperScriptNameLinux,
                SchedulerBase.ClusterInquireRequestFileName,
                SchedulerBase.ClusterInquireConfirmFileName
            };

            // "Normal" output excludes these internal files so it is not processed as a job output
            task.AddFileExclusions(exclusions);

            // task.AddFileExclusions is for exclusions defined on job side.  
            // These "exclude" files are already known to RSM so add after task.AddFileExclusions 
            exclusions.UnionWith(GetFileListByTag(task.OutputFiles, "exclude"));
            
            // DE93531 We need to omit copying back the Cancel files when they are uploaded.
            exclusions.UnionWith(GetFileListByTag(task.InputFiles, "cancel"));

            // DE80232: task.SupportFiles property added and hardcoded file list removed.
            // RSM already knows about these so added after task.AddFileExclusions call
            exclusions.UnionWith(task.SupportFiles);

            exclusions.RemoveWhere(l => string.IsNullOrWhiteSpace(l));

            // Create a string of ';' delimited names to pass to the methods.
            string fileExclusions = string.Join(";", exclusions.ToArray());

            // Inquire should exclude all the regular excludes as well as these "additional ones" listed below.
            HashSet<string> exclusionsListForInquire = new HashSet<string> {
                GenericJobBase.StdOutFileName,
                GenericJobBase.StdErrFileName,
                SchedulerBase.ExitCodeFileName,
                SchedulerBase.ClusterStdErrLiveLogFileName,
                SchedulerBase.ClusterStdOutLiveLogFileName
            };
            exclusionsListForInquire.UnionWith(exclusions);
            string inquireExclusions = string.Join(";", exclusionsListForInquire.ToArray());

            // Upload only needs to exclude the files listed explicitly
            // These are files that should never be transfered when there is a proxy machine involved
            HashSet<string> exclusionsListForUpload = new HashSet<string> {
                SchedulerBase.CommandsXmlFileName
            };

            exclusionsListForUpload.UnionWith(GetFileListByTag(task.InputFiles, "exclude"));

            string uploadExclusions = string.Join(";", exclusionsListForUpload.ToArray());

            return Tuple.Create(fileExclusions, inquireExclusions, uploadExclusions);
        }

        /// <summary>
        /// Return null if PE is implemented in NativeOptions, otherwise return a string with the PE Name to be used.  
        /// We will add "-pe ... %RSM_HPC_CORES%" in the hpc Commands file for easier customization.
        /// </summary>
        /// <param name="task"></param>
        /// <param name="command"></param>
        /// <returns></returns>
        private string HandleSgeParallelEnvironment(ITask task, GenericCommands command)
        {
            task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "Checking for Parallel Environment");

            // if parallel jobs then needs PE
            string peName = null;

            // if user put -pe in native setting, try to *always* use it, regardless whether job can be distributed
            // or the pe is valid for the job..
            // 1) Check if the -pe command is complete (does it have Cores?  If not attach the correct number of cores)
            // 2) Check is the -pe command is complete (Does it have pe_name?  If not, throw exception.)
            if (!string.IsNullOrEmpty(command.NativeSettings) && command.NativeSettings.Contains("-pe"))
            {
                string[] settings = command.NativeSettings.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < settings.Length; i++)
                {
                    if (!settings[i].Equals("-pe"))
                        continue;

                    if (settings.Length < i + 2) // +2 to go from index to length
                        throw new Exception(task.GetLocalizedString("ID_CustomParallelEnvironmentWithoutPEName"));

                    peName = settings[i + 1];
                    task.AddMessage(TaskMessageType.Information, TaskMessageSource.Cluster, 60000, "ID_CustomParallelEnvironmentRunJob", true, peName);

                    // adjust the nativeSetting to insert # of cores, unless the user specify it
                    List<string> newSettings = new List<string>();

                    // first part of native setting
                    for (int j = 0; j < i + 2; j++)
                        newSettings.Add(settings[j]);

                    if (settings.Length > i + 2)
                    {
                        int cores = command.Cores;
                        bool ok = int.TryParse(settings[i + 2], out cores);
                        if (!ok) // if ok, cores already specified in nativesettings
                        {
                            if (settings[i + 2] != "%RSM_HPC_CORES%") // Check to see if the cores have been "properly assigned", if so, leave them there...
                                newSettings.Add(command.Cores.ToString());  // If the value isnt an "int" and its not RSM_HPC_CORES, then assume that it 
                        }                                                   // is simply the next argument and that it was left for us to fill in with the correct number of cores
                        // add the rest of native setting
                        for (int j = i + 2; j < settings.Length; j++)
                            newSettings.Add(settings[j]);
                    }
                    else
                    {
                        newSettings.Add(command.Cores.ToString());
                    }

                    // Change the original Native Settings.  This will get set later during the environment variable setting
                    command.NativeSettings = string.Join(" ", newSettings.ToArray());

                    task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "PE setting with cores: {0}", command.NativeSettings);

                    // This means that RSM_HPC_SGE_PE doesn't need to be created and we are done.
                    return null;
                }
            }

            // user does not explicitly specify pe from native setting, but it is parallel job
            // which requires pe be specified, then we take it from default setting from CS dialog
            // For single core job, pe is optional, so we do not enforce it
            if (command.Cores > 1)
            {
                peName = (this._allowDistributed) ? task.ParallelEnvironmentDistributed : task.ParallelEnvironmentSharedMemory;
                if (string.IsNullOrEmpty(peName))
                    throw new Exception(task.GetLocalizedString("ID_ParallelEnvironmentRequiredForJob"));

                task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "Using PE name from Compute Server: {0}", peName);
                return peName;  // Only return the PE name
            }

            task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "No Parallel Environment Required for 1 core job");
            return null;
        }

        private void CleanUpLocalFiles(ITask task)
        {
            ReadOnlyCollection<string> filesToCleanUp = new List<string>
            {
                GenericJobBase.StdOutFileName,
                GenericJobBase.StdErrFileName,
                SchedulerBase.ControlFileName,
                SchedulerBase.HostsFileName,
                SchedulerBase.ExitCodeFileName,
                SchedulerBase.ClusterStdOutLiveLogFileName,
                SchedulerBase.ClusterStdErrLiveLogFileName,
                SchedulerBase.ClusterJobCustomizationFileName,
                DefaultClusterJobCommandDefinition.ClusterJobScriptFileName,
                DefaultClusterJobCommandDefinition.ClusterWrapperScriptNameWindows,
                DefaultClusterJobCommandDefinition.ClusterWrapperScriptNameLinux,
                SchedulerBase.ClusterInquireRequestFileName,
                SchedulerBase.ClusterInquireConfirmFileName,
                SchedulerBase.PsshRemoteInputCacheFileName,
                SchedulerBase.RestartFileName
            }.AsReadOnly();

            foreach (string file in filesToCleanUp)
                if (!string.IsNullOrEmpty(file))
                    Utilities.TryToDeleteFile(task, Path.Combine(task.WorkingDirectory, file));
        }

        private static ClusterType GetClusterTypeFromResults(ITopLevelCommandResults results)
        {
            // If not defined assume custom.
            if (!results.FinalPrimaryVariables.ContainsKey("RSM_HPC_PARSE"))
            {
                return ClusterType.CUSTOM;
            }

            return (ClusterType)Enum.Parse(typeof(ClusterType), results.FinalPrimaryVariables["RSM_HPC_PARSE"], true);
        }

        private static string GetParseMarkerFromResults(ITopLevelCommandResults results)
        {
            // Only return a parse marker if it is defined and not blank (or spaces).
            string parseMarker;
            if (results.FinalPrimaryVariables.TryGetValue("RSM_HPC_PARSE_MARKER", out parseMarker) && !string.IsNullOrWhiteSpace(parseMarker))
                return parseMarker;

            return null;
        }

        #endregion

        #region Custom HPC File Transfer

        private static IEnumerable<string> GetFileListByTag(ReadOnlyCollection<ITaskFile> fileList, string tag)
        {
            return GetFileListByTag(fileList, new HashSet<string> { tag });
        }

        private static IEnumerable<string> GetFileListByTag(IEnumerable<ITaskFile> fileList, HashSet<string> tags)
        {
            return from file in fileList where tags.Contains(file.SpecialTag) select file.FileName;
        }

        private string FileNameListToStringFormat(IEnumerable<string> fileNames)
        {
            if (fileNames == null)
            {
                return string.Empty;
            }

            string list = string.Empty;
            foreach (string name in fileNames)
            {
                list += name + ";";
            }

            // Transfer code can correctly handle an ending ';' so this trim is not necessary, but for the sake of custom integration we will remove
            // the trailing ;
            return list.TrimEnd(';');
        }

        private bool TryUploadFileNameCollection(ITask task, IJobHandle handle, IEnumerable<string> fileNames, IEnumerable<string> excludes, string context, string squelchId, out CommandExitStatus commandExitStatus)
        {
            return TryTransferFileNameCollection(task, handle, fileNames, excludes, "UPLOAD", context, squelchId, out commandExitStatus);
        }

        private bool TryUploadFileNameCollection(ITask task, IJobHandle handle, IEnumerable<string> fileNames, string excludesAsString, string context, string squelchId, out CommandExitStatus commandExitStatus)
        {
            return TryTransferFileNameCollection(task, handle, fileNames, excludesAsString, "UPLOAD", context, squelchId, out commandExitStatus);
        }

        private bool TryDownloadFileNameCollection(ITask task, IJobHandle handle, IEnumerable<string> fileNames, string excludesAsString, string context, string squelchId, out CommandExitStatus commandExitStatus)
        {
            return TryTransferFileNameCollection(task, handle, fileNames, excludesAsString, "DOWNLOAD", context, squelchId, out commandExitStatus);
        }

        private bool TryDownloadFileNameCollection(ITask task, IJobHandle handle, IEnumerable<string> fileNames, IEnumerable<string> excludes, string context, string squelchId, out CommandExitStatus commandExitStatus)
        {
            return TryTransferFileNameCollection(task, handle, fileNames, excludes, "DOWNLOAD", context, squelchId, out commandExitStatus);
        }

        private bool TryTransferFileNameCollection(ITask task, IJobHandle handle, IEnumerable<string> fileNames, IEnumerable<string> excludes, string direction, string context, string squelchId, out CommandExitStatus commandExitStatus)
        {
            return TryTransferFileNameCollection(task, handle, fileNames, FileNameListToStringFormat(excludes), direction, context, squelchId, out commandExitStatus);
        }

        /// <summary>
        /// This method attempts to use the transfer command from the hpc_commands file to transfer the file list, if there is no transfer command it returns false otherwise it returns True.
        /// The CommandExitStatus tells you if the process has succeeded or not.
        /// </summary>
        private bool TryTransferFileNameCollection(ITask task, IJobHandle handle, IEnumerable<string> fileNames, string excludesAsString, string direction, string context, string squelchId, out CommandExitStatus commandExitStatus)
        {
            if (this._clusterApi.UsesTransfer())
            {
                IDictionary<string, string> transferVariables = new Dictionary<string, string>();
                transferVariables.Add("RSM_HPC_FILELIST", FileNameListToStringFormat(fileNames));
                transferVariables.Add("RSM_HPC_FILEDIRECTION", direction);
                transferVariables.Add("RSM_HPC_FILEMARKER", task.Id.ToString());
                transferVariables.Add("RSM_HPC_FILECONTEXT", context);
                transferVariables.Add("RSM_HPC_FILEEXCLUDE", excludesAsString);

                var results = this._clusterApi.Transfer(handle, task.WorkingDirectory, this._jobId, transferVariables, squelchId);

                // Transfer Script has an output Variable that tells us if there was actually a transfer done, check it here to see what the exit status should be...
                string directoryShared;
                bool isDirectoryShared;
                if (results.FinalPrimaryVariables.TryGetValue(TransferSshDirectorySharedVariableName, out directoryShared))
                    if (bool.TryParse(directoryShared, out isDirectoryShared))
                    {
                        commandExitStatus = CommandExitStatus.NotRequired;  // Right now its used for Transfer to signify that nothing was transferred.
                        return true;
                    }

                // Need to check WasStopped first, because if job was stopped, then it is also considered failed.  So if we check failed first, we will never get stopped.
                if (results.WasStopped)
                {
                    commandExitStatus = CommandExitStatus.Killed;
                }
                else if (results.FailureOccurred)
                {
                    commandExitStatus = CommandExitStatus.Failure;
                }
                else if (results.RanToSuccessfulCompletion)
                {
                    commandExitStatus = CommandExitStatus.Success;
                }
                else
                {
                    throw new InvalidOperationException("Unhandled result case of running the transfer command");
                }

                return true;
            }

            commandExitStatus = CommandExitStatus.NotRun;
            return false;
        }
        
        #endregion

        #region Restart Utilities

        private void SaveRestartInfo(ITask task)
        {
            string filePath = Path.Combine(task.WorkingDirectory, RestartFileName);

            XmlDocument xmlDoc = new XmlDocument();
            XmlProcessingInstruction pi = xmlDoc.CreateProcessingInstruction("xml", "version='1.0'");
            xmlDoc.AppendChild(pi);

            XmlNode root = xmlDoc.CreateNode(XmlNodeType.Element, "Restart", null);
            xmlDoc.AppendChild(root);

            XmlNode node = xmlDoc.CreateElement("ClusterID");
            node.InnerText = _jobId;
            root.AppendChild(node);

            xmlDoc.Save(filePath);
            task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "Restart file saved to {0}", filePath);
        }

        private string CheckRestartInfo(ITask task)
        {
            string filePath = Path.Combine(task.WorkingDirectory, RestartFileName);
            if (!File.Exists(filePath))
            {
                task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "Restart file {0} not found.", filePath);
                return null;
            }

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filePath);

            XmlNode node = xmlDoc.SelectSingleNode("Restart/ClusterID");
            if (node == null)
                return null;

            task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "Found restart file. Job ID: {0}", node.InnerText);
            return node.InnerText;
        }

        #endregion // external HPC commands

        #region Parsing Methods

        #region Parse Job ID

        internal static string ParseJobID(ITask task, ReadOnlyCollection<string> stdOutCollection, ClusterType clusterTypeToParseFor, string parseMarker)
        {
            // find parse start marker.  If IndexOf doesn't find marker, returns -1
            int startIndex = 0;
            if (!string.IsNullOrEmpty(parseMarker))
                startIndex = stdOutCollection.IndexOf(parseMarker) + 1;

            ReadOnlyCollection<string> validStdOutCollection = stdOutCollection.Skip(startIndex).ToList().AsReadOnly();

            // Check to see if there is really any output from stdOut
            if (!validStdOutCollection.Any() || string.IsNullOrEmpty(validStdOutCollection.FirstOrDefault(line => !string.IsNullOrWhiteSpace(line))))
                throw new GenericJobCodeException("ID_NoOutputFromSubmission");

            switch (clusterTypeToParseFor)
            {
                case ClusterType.LSF:
                    return ParseJobID_LSF(task, validStdOutCollection);
                case ClusterType.MSCC:
                    return ParseJobID_MSCC(task, validStdOutCollection);
                case ClusterType.PBS:
                    return ParseJobID_PBS(task, validStdOutCollection);
                case ClusterType.TORQUE:
                    return ParseJobID_TORQUE(task, validStdOutCollection);
                case ClusterType.SGE:
                    return ParseJobID_SGE(task, validStdOutCollection);
                case ClusterType.YAC:
                    return ParseJobID_Yac(task, validStdOutCollection);
                case ClusterType.NONE:
                    return ParseJobID_None(task, validStdOutCollection);
                default:
                    return ParseJobID_Custom(task, validStdOutCollection);
            }
        }

        private static string ParseJobID_None(ITask task, ReadOnlyCollection<string> stdOutCollection)
        {
            return ParseJobID_Custom(task, stdOutCollection);
        }

        private static string ParseJobID_Custom(ITask task, ReadOnlyCollection<string> stdOutCollection)
        {
            const string prefix = "RSM_HPC_JOBID=";
            string jobId = null;
            string jobIdLine = stdOutCollection.FirstOrDefault(line => line.StartsWith(prefix));

            // TODO: should we throw here if the value is not present?
            if(!string.IsNullOrEmpty(jobIdLine))
                jobId = jobIdLine.Substring(prefix.Length);

            task.AddMessage(TaskMessageType.Important, TaskMessageSource.Cluster, 60000, "ID_JobId", true, "Custom", jobId);
            return jobId;
        }

        private static string ParseJobID_SGE(ITask task, ReadOnlyCollection<string> stdOutCollection)
        {
            string jobIdLine = stdOutCollection.FirstOrDefault(line => line.StartsWith("Your"));

            if (string.IsNullOrEmpty(jobIdLine))
                throw new GenericJobCodeException("ID_SGENotSubmitted");

            // Parse the Job ID from the process submission output
            string[] tokens = jobIdLine.Split(new char[] { ' ' });
            string jobId = tokens[2];

            if(task != null)
                task.AddMessage(TaskMessageType.Important, TaskMessageSource.Cluster, 60000, "ID_JobId", true, "SGE", jobId);

            return jobId;
        }

        private static string ParseJobID_MSCC(ITask task, ReadOnlyCollection<string> stdOutCollection)
        {
            if (stdOutCollection.Count < 1)
                throw new GenericJobCodeException("ID_MccJobNotSubmitted");

            // assumes job id on FIRST line by itself
            // output looks like "job has been submitted. ID: xxxx."
            int jobNumber;
            string jobidstr = null;
            string lastOutput = stdOutCollection[0];
            string[] output = lastOutput.Split(':');
            if (output.Length > 1)
                jobidstr = output[1].TrimEnd('.');

            if (jobidstr == null || !int.TryParse(jobidstr, out jobNumber) || jobNumber == 0)
            {
                if (task != null)
                    task.AddMessage(TaskMessageType.Important, TaskMessageSource.Cluster, 60000, lastOutput);
                throw new GenericJobCodeException("ID_MccJobNotSubmitted");
            }

            if (task != null)
                task.AddMessage(TaskMessageType.Important, TaskMessageSource.Cluster, 60000, "ID_JobId", true, "MS HPC", jobNumber);
            
            return jobNumber.ToString();
        }

        private static string ParseJobID_TORQUE(ITask task, ReadOnlyCollection<string> stdOutCollection)
        {
            return ParseJobID_PBS(task, stdOutCollection);
        }

        private static string ParseJobID_PBS(ITask task, ReadOnlyCollection<string> stdOutCollection)
        {
            // first line is qsub output
            string jobIdStr = stdOutCollection.FirstOrDefault(line => !string.IsNullOrWhiteSpace(line));

            if (string.IsNullOrEmpty(jobIdStr))
                throw new GenericJobCodeException("ID_PBSQSUBFailed");

            if (jobIdStr.StartsWith("qsub:")) // error message follows
                throw new GenericJobCodeException("ID_PBSQSUBFailed");

            if(task != null)
                task.AddMessage(TaskMessageType.Important, TaskMessageSource.Cluster, 60000, "ID_JobId", true, "PBS", jobIdStr);

            return jobIdStr;
        }

        private static string ParseJobID_LSF(ITask task, ReadOnlyCollection<string> stdOutCollection)
        {
            // first line is bsub output
            if (stdOutCollection.Count < 1)
                throw new GenericJobCodeException("ID_LSFBSUBFailed");

            string jobIdStr = null;
            string jobIdLine = stdOutCollection.FirstOrDefault(line => line.StartsWith("Job <"));

            if(!string.IsNullOrEmpty(jobIdLine))
                jobIdStr = jobIdLine.Split(new Char[] { '<', '>' })[1];

            if (string.IsNullOrEmpty(jobIdStr))
                throw new GenericJobCodeException("ID_LSFBSUBFailed");

            if (task != null)
                task.AddMessage(TaskMessageType.Important, TaskMessageSource.Cluster, 60000, "ID_JobId", true, "LSF", jobIdStr);

            return jobIdStr;
        }

        private static string ParseJobID_Yac(ITask task, ReadOnlyCollection<string> stdOutCollection)
        {
            const string prefix = "#YAC_JOB_ID=";

            string jobIdLine = stdOutCollection.FirstOrDefault(line => line.StartsWith(prefix));

            if(!string.IsNullOrEmpty(jobIdLine))
                return jobIdLine.Substring(prefix.Length);
            else
                throw new GenericJobCodeException("ID_YACSubmitFailed");
        }

        #endregion

        #region Parse Status

        internal ClusterStatus ParseStatus(ITask task, IJobHandle handle, ReadOnlyCollection<string> stdOutCollection, ReadOnlyCollection<string> stdErrCollection, ClusterType clusterTypeToParseFor, string parseMarker)
        {
            int startIndex = 0;
            if (!string.IsNullOrEmpty(parseMarker))
                startIndex = stdOutCollection.IndexOf(parseMarker) + 1;

            ReadOnlyCollection<string> validStdOutCollection = stdOutCollection.Skip(startIndex).ToList().AsReadOnly();

            switch (clusterTypeToParseFor)
            {
                case ClusterType.LSF:
                    return ParseStatus_LSF(task, validStdOutCollection);
                case ClusterType.MSCC:
                    return ParseStatus_MSCC(validStdOutCollection);
                case ClusterType.PBS:
                    return ParseStatus_PBS(validStdOutCollection);
                case ClusterType.TORQUE:
                    return ParseStatus_TORQUE(validStdOutCollection);
                case ClusterType.SGE:
                    return ParseStatus_SGE(task, handle, validStdOutCollection, stdErrCollection);
                case ClusterType.YAC:
                    return ParseStatus_Yac(validStdOutCollection);
                case ClusterType.NONE:
                    return ParseStatus_None(validStdOutCollection);
                default:
                    return ParseStatus_Custom(validStdOutCollection);
            }
        }

        private static ClusterStatus ParseStatus_None(ReadOnlyCollection<string> stdOutCollection)
        {
            const string prefix = "RSM_HPC_PROCESS=";
            
            string jobStatusLine = stdOutCollection.FirstOrDefault(line => line.StartsWith(prefix));

            if (!string.IsNullOrEmpty(jobStatusLine))
            {
                if (jobStatusLine.Split(new char[] {'='}, StringSplitOptions.RemoveEmptyEntries).Length > 1)
                    return ClusterStatus.Running;

                return ClusterStatus.Finished;
            }

            // If plink fails then be sure to be ClusterStatus Unknown.
            return ClusterStatus.Unknown;
        }

        private static ClusterStatus ParseStatus_Custom(ReadOnlyCollection<string> stdOutCollection)
        {
            ClusterStatus status = ClusterStatus.Unknown;
            IEnumerable<string> jobStatusLines = stdOutCollection
                .Where(line => line.StartsWith("RSM_HPC_STATUS="))
                .Select(line => line.ToUpper());

            foreach (string line in jobStatusLines)
            {
                if (line.Contains("QUEUED"))
                    status = ClusterStatus.Queued;
                else if (line.Contains("RUNNING"))
                    status = ClusterStatus.Running;
                else if (line.Contains("FINISHED"))
                    status = ClusterStatus.Finished;
                else if (line.Contains("FAILED"))
                    status = ClusterStatus.Failed;
                else if (line.Contains("CANCELLED") || line.Contains("CANCELED"))
                    status = ClusterStatus.Cancelled;

                continue; // still process all lines for errors and debug messages.
            }
            return status;
        }

        private ClusterStatus ParseStatus_SGE(ITask task, IJobHandle handle, ReadOnlyCollection<string> stdOutCollection, ReadOnlyCollection<string> stdErrCollection)
        {
            ClusterStatus status = ClusterStatus.Unknown;
            
            // Check if we can parse a valid answer from Qstat - if not this means that the job was not found in qstat so we need to check qacct 
            if (TryParseQstatOutput_SGE(task, stdOutCollection, stdErrCollection, _jobId, out status))
                return status;
            else
            {
                status = ParseQacctCommand(task, handle);  // whenever we check qacct - it means we are done job has failed, ended, or we will assume it is even if qacct can not be parsed well
                return status;
            }
        }

        internal static bool TryParseQstatOutput_SGE(ITask task, ReadOnlyCollection<string> stdOutCollection, ReadOnlyCollection<string> stdErrCollection, string jobId, out ClusterStatus status)
        {
            status = ClusterStatus.Unknown;

            // NOTE: this parsing is base on "qstat -u user" command. When job is done there should be no output from the command.
            if (stdErrCollection.Count > 0)
            {
                // Output should already be displayed
                task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "STDERR from qstat!");
                return true;  // If qstat has some error, then we should assume Unknown State, dont bother checking qacct.
            }

            /* UGE Man page documentation
        
            the  status  of  the [SGE/UGE] job  is  one  of  
            d(eletion),  
            E(rror), 
            h(old),
            r(unning),  
            R(estarted),  
            s(uspended),  
            S(uspended),  
            t(ransfering),
            T(hreshold) 
            w(aiting)
         
            o  a  one  letter  specifier  indicating  whether  the current resource
            availability value was dominated by either
            `g' - a cluster global,
            `h' - a host total or
            `q' - a queue related resource consumption.
        
            */

            // Skip first 2 lines they are the Header and seperator lines
            string outputLineWithJobId =
                stdOutCollection.Skip(2)
                .Select(line => line.Trim())
                .FirstOrDefault(line => line.StartsWith(jobId));

            if (string.IsNullOrEmpty(outputLineWithJobId)) 
                return false;

            string[] elements = outputLineWithJobId.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (elements.Length > 4)
            {
                string state = elements[4];
                // the order is important below
                if (state.Contains("E"))  // all pending states with error 	Eqw, Ehqw, EhRqw
                    status = ClusterStatus.Failed;  // dont set finalstatus because the job is still in the queue even when its E state.

                else if (state.Contains("qw") || state.Contains("hR") || state.Contains("wq"))
                    status = ClusterStatus.Queued;

                else
                {
                    // for now suspended state and deleted state are considered as still running
                    // when after qdel, job state will change
                    // if (state == "r" || state == "t" || state == "Rt" || state == "Rr")
                    status = ClusterStatus.Running;
                }
            }
            else
                task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "Matching qstat line has wrong format");  // This means PBS has changed their formatting on us...

            // we will return true for all cases where we found the jobId, it means thats qacct shouldn't work yet, job is not done.
            return true;
        }

        private static ClusterStatus ParseStatus_MSCC(ReadOnlyCollection<string> stdOutCollection)
        {
            foreach (string line in stdOutCollection.Where(line => line.StartsWith("State")))
            {
                if (line.Contains("Queued"))
                    return ClusterStatus.Queued;

                if (line.Contains("Running"))
                    return ClusterStatus.Running;

                if (line.Contains("Finished"))
                    return ClusterStatus.Finished;

                if (line.Contains("Failed"))
                    return ClusterStatus.Failed;

                if (line.Contains("Cancelled") || line.Contains("Canceled"))
                    return ClusterStatus.Cancelled;
            }

            return ClusterStatus.Unknown;
        }

        private static ClusterStatus ParseStatus_TORQUE(ReadOnlyCollection<string> stdOutCollection)
        {
            return ParseStatus_PBS(stdOutCollection);
        }

        private static ClusterStatus ParseStatus_PBS(ReadOnlyCollection<string> stdOutCollection)
        {
            // should get 3 lines for queued or running job
            // If we get 0 that means there is not even a header present. When qstat returns nothing we will assume Finished.
            if (stdOutCollection.Count < 1)
            {
                // PBS and TORQUE qstat can give no output when job is done. PBS qstat also exits !=0 in that case, so we should not even get here.
                // But PBS can change their exitcode for some versions, so we will just keep this in case.
                return ClusterStatus.Finished;
            }
            else if (stdOutCollection.Count < 3)
            {
                // TODO: we should be able to remove this because the timing issue seems to have been fixed, need to check.
                // This is an odd case we see from TORQUE where sometimes qstat it will return a header (2 lines) with no jobs listed
                // This seems like a timing issue as it happens at the very start of a job (and more often with increased cluster loading)
                // If we get this case, there is nothing to parse so we shouldnt go on but we should retry, so set to unknown.
                return ClusterStatus.Unknown;
            }

            /* PBS documentation (PBSProRefGuide 11.2).  

            B Array job has at least one subjob running.
            E Job is exiting after having run.
            F Job is finished.
            H Job is held.
            M Job was moved to another server.
            Q Job is queued. -- Same for Torque
            R Job is running. -- Same for Torque
            S Job is suspended.
            T Job is being moved to new location.
            U Cycle-harvesting job is suspended due to keyboard activity.
            W Job is waiting for its submitter-assigned start time to be reached.
            X Subjob has completed execution or has been deleted.

            C - Job is completed after having run (only used from PBS Torque)
             */

            string line = stdOutCollection[2];
            string qstatJobId;
            string qstatStatus;

            if (!ParseQstatOutput_PBS(line, out qstatJobId, out qstatStatus))
                return ClusterStatus.Unknown;

            if (qstatStatus.Equals("R") || qstatStatus.Equals("E"))
                return ClusterStatus.Running;

            if (qstatStatus.Equals("Q"))
                return ClusterStatus.Queued;

            if (qstatStatus.Equals("F") || qstatStatus.Equals("C"))
                return ClusterStatus.Finished;

            return ClusterStatus.Unknown;
        }

        private static ClusterStatus ParseStatus_Yac(ReadOnlyCollection<string> stdOutCollection)
        {
            var output = stdOutCollection[0];
            if (output == "Finished")
            {
                return ClusterStatus.Finished;
            }

            if (output == "Running")
            {
                return ClusterStatus.Running;
            }

            if (output == "Queued")
            {
                return ClusterStatus.Queued;
            }

            throw new InvalidOperationException("Unknown status from dev cluster of : " + output);
        }

        private static bool ParseQstatOutput_PBS(string line, out string jobId, out string status)
        {
            jobId = null;
            status = null;

            string[] items = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (items.Length > 4)
            {
                jobId = items[0]; // 1st item is jobid
                status = items[4]; // 5th item is status
                return true;
            }
            else
                return false;
        }

        private ClusterStatus ParseStatus_LSF(ITask task, ReadOnlyCollection<string> stdOutCollection)
        {
            string statusLine = "";
            // Be sure that there is enough output to even parse (0 or 1 lines is not the correct output length, Must be an Error)
            if (stdOutCollection.Count < 2)
            {
                // This is probably an error message
                if (task != null)
                {
                    if (stdOutCollection.Count == 1)
                        task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, stdOutCollection[0]);
                    else
                        task.AddMessage(TaskMessageType.Warning, TaskMessageSource.Cluster, 60000, "ID_NoOutputFromCommand", true, "bjobs");
                }
                // Calling code will retry 3 times before giving up on job.
                _finalStatus = ClusterStatus.Unknown;
                return _finalStatus;
            }

            // Handle Long and Short output
            if (!TryParseLongBjobsOutput(task, stdOutCollection, out statusLine))
                statusLine = stdOutCollection[1]; // "...Messages[startIndex]" will be the LSF Header - not Data Goto the line thats supposed to have Data

            if (statusLine.Contains("EXIT"))
            {
                if (task != null)
                    task.AddMessage(TaskMessageType.Error, TaskMessageSource.Cluster, 60000, "ID_LSFJobFailed", true);
                _finalStatus = ClusterStatus.Failed;
                return _finalStatus;
            }
            else if (statusLine.Contains("DONE"))
            {
                _finalStatus = ClusterStatus.Finished;
                return _finalStatus;
            }
            else if (statusLine.Contains("RUN"))
            {
                return ClusterStatus.Running;
            }
            else if (statusLine.Contains("PEND") || statusLine.Contains("PSUSP") || statusLine.Contains("USUSP") || statusLine.Contains("SSUSP"))
            {
                return ClusterStatus.Queued;
            }
            else
            {
                return ClusterStatus.Unknown;
            }
        }

        private bool TryParseLongBjobsOutput(ITask task, ReadOnlyCollection<string> stdOutCollection, out string statString)
        {
            if (stdOutCollection.Count < 3) // this is not from a -l (Long Output)
            {
                statString = "UNKWN";
                return false;
            }
            // To ensure that "Status <VAL>" is not split across two lines at any point, combine first 3 lines into 1 line and parse from that.
            string statusLine = stdOutCollection[0];
            statusLine += stdOutCollection[1].Trim();  // this trimming can technically mess up some spacing but the
            statusLine += stdOutCollection[2].Trim();  // parsing we are worried about doesnt need it to be correct

            if (!(statusLine.Contains("Status") && statusLine.Contains('<') && statusLine.Contains('>')))
            {
                statString = "UNKWN";
                return true;  //The output was acceptably long to be considered for LongOutput style, but we still cant find status. Unknown is valid for this situation...
            }

            statString = statusLine.Substring(statusLine.IndexOf("Status")); // cut off beginning of line before "Status".
            statString = statString.Substring(0, statString.IndexOf(">"));  // cut off end.  statString = "Status <VALUE"

            // If the job is in some pending state, then lets see if we can print out the reason (unless we have already printed it and we dont want to do it again)
            // Skip this for testing when: task == null.
            if(task != null && !_repeatMessageDisplayed && (statString.Contains("PEND") || statString.Contains("PSUSP") || statString.Contains("USUSP") || statString.Contains("SSUSP")))
            {
                bool foundReason = false;
                foreach (string line in stdOutCollection)
                {
                    if (line.Contains("SCHEDULING PARAMETERS")) // no more pending reasons to display
                        break;

                    if (!foundReason && line.Contains("PENDING REASONS"))
                    {
                        task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60009, line);
                        foundReason = true;
                        continue;
                    }

                    if (foundReason)
                    {
                        // TODO - will this always be the first line of output below pending reasons header?
                        // TODO 2 - Since code designed to call this only when status changes, if we get a different pending reason like
                        // "Unable to determine user account for execution;" initially (because account not exist at all) then we never get
                        // a chance to detect this case
                        if (line.Contains("Failed to get user password") || line.Contains("Failed to logon user"))
                        {
                            task.AddMessage(TaskMessageType.Error, TaskMessageSource.Cluster, 60003, "ID_InvalidLSFPassword", true, _jobId);
                            _repeatMessageDisplayed = true;
                            KillJob(task); // cancels cluster job.  RSM job ends as failed
                        }
                        else if (line.Contains("Not enough processors") && line.Contains("spanning requirement"))
                        {
                            task.AddMessage(TaskMessageType.Warning, TaskMessageSource.Cluster, 60010, line);
                            _repeatMessageDisplayed = true;
                            // TODO: Possibly figure out a way to tell if the job can not EVER be run and cancel it automatically
                        }
                        else // This is probably "New job is waiting for scheduling".  Usually only shown once.
                            task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60009, line);
                    }
                }
            }
            return true;
        }

        private ClusterStatus ParseQacctCommand(ITask task, IJobHandle handle)
        {
            // original code has this sleep prior to running qacct
            // TODO: Note by Jon (11/6/2014) : This sleep is still not always long enough to get the job id in the qacct database...
            Thread.Sleep(5000);

            // Parse exit_status from qacct command here. User can disable use of this command in hpc_commands_SGE.xml
            if (!this._clusterApi.UsesFinalStatus())
            {
                return ClusterStatus.Finished;
            }

            var topLevelCommandResults = this._clusterApi.GetFinalStatus(handle, task.WorkingDirectory, this._jobId, new JobFinishedOnStatusErrorNotifications(task));

            // This is a little ugy, casting to process results, but this queryQacct parsing logic shouldn't even be in C#.  It should be defined in hpc_commands some how.
            // Then it would just define and output variable, which is very easy to get to on the top level command results.
            // until then, we have to cast and assume it was a process and get ahold of stdout that way.
            if (topLevelCommandResults.FailureOccurred)
            {
                return ClusterStatus.Finished; // Assume finished if qacct has not run...
            }

            var primaryOperationProcessResults = topLevelCommandResults.PrimaryCommandResults as IExternalCommandResults;
            if (primaryOperationProcessResults == null)
            {
                throw new InvalidOperationException(string.Format(task.GetLocalizedString("ID_CommandExpectedToBeExternal"), HpcCommandsReader.StandardCommandNameQacct));
            }

            foreach (string line in primaryOperationProcessResults.Stdout)
            {
                if (!line.StartsWith("exit_status", StringComparison.OrdinalIgnoreCase))
                    continue;

                // chop off 'exit_status ' and parse
                int status = -1;
                int.TryParse(line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[1], out status);

                return (status != 0) ? ClusterStatus.Failed : ClusterStatus.Finished;
            }

            // We couldnt find the exit status in the qacct command output...
            task.AddMessage(TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, "Couldnt find exit_status in qacct output, it could be blank. exit_status unknown.");
            return ClusterStatus.Finished; // Assume finished if qacct is not parsable.
        }

        #endregion

        #region Parse Queues

        internal static ReadOnlyCollection<string> ParseQueues(ITask task, ReadOnlyCollection<string> stdOutCollection, ReadOnlyCollection<string> stdErrCollection, ClusterType clusterTypeToParseFor, string parseMarker)
        {
            int startIndex = 0;
            if (!string.IsNullOrEmpty(parseMarker))
                startIndex = stdOutCollection.IndexOf(parseMarker) + 1;

            ReadOnlyCollection<string> validStdOutCollection = stdOutCollection.Skip(startIndex).ToList().AsReadOnly();

            switch (clusterTypeToParseFor)
            {
                case ClusterType.LSF:
                    return ParseQueues_LSF(task, validStdOutCollection, stdErrCollection);
                case ClusterType.MSCC:
                    return null;
                case ClusterType.PBS:
                    return ParseQueues_PBS(task, validStdOutCollection, stdErrCollection);
                case ClusterType.TORQUE:
                    return ParseQueues_TORQUE(task, validStdOutCollection, stdErrCollection);
                case ClusterType.SGE:
                    return ParseQueues_SGE(task, validStdOutCollection, stdErrCollection);
                case ClusterType.YAC:
                    return ParseQueues_Yac(validStdOutCollection);
                case ClusterType.NONE:
                    throw new NotSupportedException(task.GetLocalizedString("ID_QueuesNotSupportedForNonCluster"));
                default:
                    return ParseQueues_Custom(task, validStdOutCollection, stdErrCollection);
            }
        }

        private static ReadOnlyCollection<string> ParseQueues_Custom(ITask task, ReadOnlyCollection<string> stdOutCollection, ReadOnlyCollection<string> stdErrCollection)
        {
            return null;  // not checking queues for custom cluster but may add in the future
        }

        private static ReadOnlyCollection<string> ParseQueues_SGE(ITask task, ReadOnlyCollection<string> stdOutCollection, ReadOnlyCollection<string> stdErrCollection)
        {
            // already dumping stdio and stderr in CheckQueue
            if (stdErrCollection.Count > 0)
            {
                task.AddMessage(TaskMessageType.Warning, TaskMessageSource.Cluster, 60001, "ID_HpcCommandFailed", true, HpcCommandsReader.StandardCommandNameQueues);
                return null;
            }

            return stdOutCollection
            .Where(line => !string.IsNullOrWhiteSpace(line))
            .Select(line => line.Trim())
            .ToList().AsReadOnly();
        }

        private static ReadOnlyCollection<string> ParseQueues_TORQUE(ITask task, ReadOnlyCollection<string> stdOutCollection, ReadOnlyCollection<string> stdErrCollection)
        {
            return ParseQueues_PBS(task, stdOutCollection, stdErrCollection);
        }

        private static ReadOnlyCollection<string> ParseQueues_PBS(ITask task, ReadOnlyCollection<string> stdOutCollection, ReadOnlyCollection<string> stdErrCollection)
        {
            // already dumping stdio and stderr in CheckQueue
            if (stdErrCollection.Count > 0)
            {
                task.AddMessage(TaskMessageType.Warning, TaskMessageSource.Cluster, 60001, "ID_HpcCommandFailed", true, HpcCommandsReader.StandardCommandNameQueues);
                return null;
            }

            if (stdOutCollection.Count < 3)
            {
                task.AddMessage(TaskMessageType.Warning, TaskMessageSource.Cluster, 60001, "ID_HpcCommandFailed", true, HpcCommandsReader.StandardCommandNameQueues);
                return null;
            }

            /* Example Pbs Queue 
               Skip 2 lines.  then grab queue from beginning of the rest.
            
            START
            Queue              Max   Tot Ena Str   Que   Run   Hld   Wat   Trn   Ext Type
            ---------------- ----- ----- --- --- ----- ----- ----- ----- ----- ----- ----
            WB_pbsnat_reuse      0     0 yes yes     0     0     0     0     0     0 Exec
            */

            return stdOutCollection
            .Where(line => !string.IsNullOrWhiteSpace(line))
            .Skip(2)
            .Select(line => line.Substring(0, line.IndexOf(' ')))
            .ToList().AsReadOnly();
        }

        private static ReadOnlyCollection<string> ParseQueues_LSF(ITask task, ReadOnlyCollection<string> stdOutCollection, ReadOnlyCollection<string> stdErrCollection)
        {
            // already dumping stdio and stderr in CheckQueue
            if (stdErrCollection.Count > 0)
            {
                task.AddMessage(TaskMessageType.Warning, TaskMessageSource.Cluster, 60001, "ID_HpcCommandFailed", true, HpcCommandsReader.StandardCommandNameQueues);
                return null;
            }

            if (stdOutCollection.Count < 2)
            {
                task.AddMessage(TaskMessageType.Warning, TaskMessageSource.Cluster, 60001, "ID_HpcCommandFailed", true, HpcCommandsReader.StandardCommandNameQueues);
                return null;
            }

            /* note: expected output should look like follows
            We should skip 2 lines and then grab queue from beginning of the rest;
            however, to be on the safe side (an empty line might be filtered out by the CommandRunner?),
            process also second line and check if indeed empty
            
            START
            QUEUE_NAME      PRIO STATUS          MAX JL/U JL/P JL/H NJOBS  PEND   RUN  SUSP
            
            normal          43  Open:Active       -    -    -    -     0     0     0     0
            */

            // Be sure to filter the whitespace first, in case of this old output with space in it.
            return stdOutCollection
                .Where(line => !string.IsNullOrWhiteSpace(line))
                .Skip(1)
                .Select(line => line.Substring(0, line.IndexOf(' ')))
                .ToList().AsReadOnly();
        }

        private static ReadOnlyCollection<string> ParseQueues_Yac(ReadOnlyCollection<string> stdOutCollection)
        {
            return stdOutCollection.Where(x => !string.IsNullOrWhiteSpace(x)).ToList().AsReadOnly();
        }

        #endregion

        #region Parse Pe

        internal static ReadOnlyCollection<string> ParseParallelEnviornment(ITask task, ReadOnlyCollection<string> stdOutCollection,
            ReadOnlyCollection<string> stdErrCollection, ClusterType targetClusterType, string parseMarker)
        {
            int startIndex = 0;
            if (!string.IsNullOrEmpty(parseMarker))
                startIndex = stdOutCollection.IndexOf(parseMarker) + 1;

            ReadOnlyCollection<string> validStdOutCollection = stdOutCollection.Skip(startIndex).ToList().AsReadOnly();

            switch (targetClusterType)
            {
                case ClusterType.SGE:
                    return ParseParallelEnvironment_SGE(task, validStdOutCollection, stdErrCollection);
                default:
                    throw new NotSupportedException("Check PE command only supported for SGE/UGE cluster type");
            }
        }

        private static ReadOnlyCollection<string> ParseParallelEnvironment_SGE(ITask task, ReadOnlyCollection<string> stdOutCollection, 
            ReadOnlyCollection<string> stdErrCollection)
        {
            // already dumping stdio and stderr in CheckPe
            if (stdErrCollection.Count > 0)
            {
                task.AddMessage(TaskMessageType.Warning, TaskMessageSource.Cluster, 60001, "ID_HpcCommandFailed", true, "checkPe");
                return null;
            }

            return stdOutCollection
                .Where(line => !string.IsNullOrWhiteSpace(line))
                .Select(line => line.Trim())
                .ToList().AsReadOnly();
        }

        #endregion

        #endregion

        #region Logging of HPC Command Output

        private void DisplayLineCustom(ITask task, TaskMessageType type, TaskMessageSource source, int messageID, string line)
        {
            if (string.IsNullOrEmpty(line))
                return;

            if (task == null)
                Console.WriteLine("******* " + line); // stdout from TaskHost.exe will be captured in log

            TaskMessageType msgType;
            int index = 0;
            if (!line.StartsWith("RSM_HPC_")) // avoid all the other else if
                msgType = type;
            else
            {
                if (line.StartsWith("RSM_HPC_ERROR="))
                {
                    msgType = TaskMessageType.Error;
                    index = 14;
                }
                else if (line.StartsWith("RSM_HPC_DEBUG="))
                {
                    msgType = TaskMessageType.Debug;
                    index = 14;
                }
                else if (line.StartsWith("RSM_HPC_FILE="))
                {
                    msgType = TaskMessageType.FileHandling;
                    index = 13;
                }
                else if (line.StartsWith("RSM_HPC_FILEDEBUG="))
                {
                    msgType = TaskMessageType.FileHandling | TaskMessageType.Debug;
                    index = 18;
                }
                else if (line.StartsWith("RSM_HPC_DEVDEBUG="))
                {
                    msgType = TaskMessageType.DevDebug;
                    index = 17;
                }
                else if (line.StartsWith("RSM_HPC_FILEDEVDEBUG="))
                {
                    msgType = TaskMessageType.FileHandling | TaskMessageType.DevDebug;
                    index = 21;
                }
                else if (line.StartsWith("RSM_HPC_WARN="))
                {
                    msgType = TaskMessageType.Warning;
                    index = 13;
                }
                else if (line.StartsWith("RSM_HPC_CLUSTER="))
                {
                    source = TaskMessageSource.Job | TaskMessageSource.Cluster;
                    msgType = type;
                    index = 16;
                }
                else
                    msgType = type;
            }

            string message = (index == 0) ? line : line.Substring(index);
            if (string.IsNullOrEmpty(message))
                return;

            task.AddMessage(msgType, source, messageID, message);
        }

        private void LocalAddMessage(TaskMessageType type, TaskMessageSource source, int messageID, string format, params object[] args)
        {
            DisplayLineCustom(_task, type, source, messageID, format); // this is stdout/stderr so no args
        }

        #endregion

        #region ITopLevelCommandCallbacks

        public void StdoutReceived(string data)
        {
            DisplayLineCustom(_task, TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, data);
        }

        public void StderrReceived(string data)
        {
            DisplayLineCustom(_task, TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, data);
        }

        public void DisplayDebugOutput(string message)
        {
            DisplayLineCustom(_task, TaskMessageType.Debug, TaskMessageSource.Cluster, 60000, message);
        }

        public void DisplayOutput(string message)
        {
            DisplayLineCustom(_task, TaskMessageType.Information, TaskMessageSource.Cluster, 60000, message);
        }

        #endregion

        #region ICanUploadInputFiles

        public void UploadInputFiles(IJobHandle handle, IEnumerable<string> fileNames)
        {
            CommandExitStatus uploadExitStatus;
            if (this.TryUploadFileNameCollection(_task, handle, fileNames, _uploadExclusions, "INPUTS", "UploadInputs", out uploadExitStatus))
            {
                if (uploadExitStatus == CommandExitStatus.NotRequired)  // If the transfer was not done but the command exists, then it must have been shared
                    _externalTransferCleanupRequired = false;

                if (uploadExitStatus == CommandExitStatus.Failure)
                    throw new InvalidOperationException(string.Format(_task.GetLocalizedString("ID_RemoteMachineOperationFailed"), "Upload", "Inputs"));
            }
        }

        public bool UsesTransfer()
        {
            return this._clusterApi.UsesTransfer();
        }

        #endregion

        #region Classes

        private class GenericClusterErrorNotifications : ITopLevelCommandErrorNotificationCallbacks
        {
            protected readonly ITask _task;

            public GenericClusterErrorNotifications(ITask task)
            {
                this._task = task;
            }

            public virtual void ExternalOperationFailed(IExternalOperationData operationData, IExternalOperationResults operationResults)
            {
                _task.AddMessage(TaskMessageType.Error, TaskMessageSource.Cluster, 60000, "ID_ExternalOperationFailed", true, operationData.DisplayName);
            }

            public virtual void ExternalOperationHasIncorrectOutputs(IExternalOperationData operationData, IExternalOperationResults operationResults)
            {
                var missingOutputsPrintableString = string.Join(",", operationData.ExpectedOutputVariables.Where(x => !operationResults.OutputVariables.ContainsKey(x)));
                _task.AddMessage(TaskMessageType.Error, TaskMessageSource.Cluster, 60000, "ID_ExternalOperationMissingOutputs", true, operationData.DisplayName, missingOutputsPrintableString);
            }
        }

        private class JobFinishedOnStatusErrorNotifications : GenericClusterErrorNotifications, ITopLevelCommandErrorNotificationCallbacks
        {
            public JobFinishedOnStatusErrorNotifications(ITask task):base(task)
            {
            }

            public override void ExternalOperationFailed(IExternalOperationData operationData, IExternalOperationResults operationResults)
            {
                _task.AddMessage(TaskMessageType.Information, TaskMessageSource.Cluster, 60000, "ID_JobFinished", true);
            }
        }

        #endregion
    }
}
