ionRunnerFactory externalOperationRunnerFactory,
            IExternalOperationTransformationFactory protocolTransformationFactory,
            ITopLevelCommandCallbacks callbacks,
            ITopLevelCommandErrorNotificationCallbacks errorNotificationCallbacks)
        {
            if (topLevelCommand == null)
            {
                throw new ArgumentNullException("topLevelCommand");
            }

            if (externalOperationRunnerFactory == null)
            {
                throw new ArgumentNullException("externalOperationRunnerFactory");
            }

            if (protocolTransformationFactory == null)
            {
                throw new ArgumentNullException("protocolTransformationFactory");
            }

            if (callbacks == null)
            {
                throw new ArgumentNullException("callbacks");
            }

            if (errorNotificationCallbacks == null)
            {
                throw new ArgumentNullException("errorNotificationCallbacks");
            }

            this._topLevelCommand = topLevelCommand;
            this._callbacks = callbacks;
            this._errorNotificationCallbacks = errorNotificationCallbacks;

            this._externalOperationExecutor = new ExternalOperationExecutor(externalOperationRunnerFactory, _callbacks);
            this._transformationProcessor = new TransformationProcessor(protocolTransformationFactory);
        }

        public TopLevelCommandExecutor(ITopLevelCommand topLevelCommand, ITopLevelCommandCallbacks callbacks)
            : this(topLevelCommand, DefaultExternalOperationRunnerFactory.DefaultInstance, DefaultTransformationFactory.DefaultInstance, callbacks, NoErrorNotificationCallbacks.Instance)
        {
        }

        public TopLevelCommandExecutor(ITopLevelCommand topLevelCommand, IExternalOperationRunnerFactory externalOperationRunnerFactory, ITopLevelCommandCallbacks callbacks, ITopLevelCommandErrorNotificationCallbacks errorCallbacks)
            : this(topLevelCommand, externalOperationRunnerFactory, DefaultTransformationFactory.DefaultInstance, callbacks, errorCallbacks)
        {
        }

        public TopLevelCommandExecutor(ITopLevelCommand topLevelCommand, IExternalOperationRunnerFactory externalOperationRunnerFactory, ITopLevelCommandCallbacks callbacks)
            : this(topLevelCommand, externalOperationRunnerFactory, DefaultTransformationFactory.DefaultInstance, callbacks, NoErrorNotificationCallbacks.Instance)
        {
        }

        public TopLevelCommandExecutor(ITopLevelCommand topLevelCommand, IExternalOperationRunnerFactory externalOperationRunnerFactory)
            : this(topLevelCommand, externalOperationRunnerFactory, DefaultTransformationFactory.DefaultInstance, NoTopLevelCommandCallbacks.Instance, NoErrorNotificationCallbacks.Instance)
        {
        }

        public TopLevelCommandExecutor(ITopLevelCommand topLevelCommand, IExternalOperationRunnerFactory externalOperationRunnerFactory, IExternalOperationTransformationFactory protocolTransformationFactory)
            : this(topLevelCommand, externalOperationRunnerFactory, protocolTransformationFactory, NoTopLevelCommandCallbacks.Instance, NoErrorNotificationCallbacks.Instance)
        {
        }

        public TopLevelCommandExecutor(ITopLevelCommand topLevelCommand, IExternalOperationRunnerFactory externalOperationRunnerFactory, ITopLevelCommandErrorNotificationCallbacks errorNotificationCallbacks)
            : this(topLevelCommand, externalOperationRunnerFactory, DefaultTransformationFactory.DefaultInstance, NoTopLevelCommandCallbacks.Instance, errorNotificationCallbacks)
        {
        }

        public TopLevelCommandExecutor(ITopLevelCommand topLevelCommand)
            : this(topLevelCommand, NoTopLevelCommandCallbacks.Instance)
        {
        }

        #endregion

        #region Public Static Methods

        public static ITopLevelCommandResults Run(IJobHandle handle, ITopLevelCommand topLevelCommand, ITopLevelCommandCallbacks callbacks, string workingDirectory)
        {
            return (new TopLevelCommandExecutor(topLevelCommand, callbacks)).Run(handle, workingDirectory);
        }

        public static ITopLevelCommandResults Run(IJobHandle handle, ITopLevelCommand topLevelCommand, ITopLevelCommandCallbacks callbacks, string workingDirectory, IDictionary<string, VariableValue> additionalVariables)
        {
            return (new TopLevelCommandExecutor(topLevelCommand, callbacks)).Run(handle, workingDirectory, additionalVariables);
        }

        public static ITopLevelCommandResults RunUnstoppable(ITopLevelCommand topLevelCommand, ITopLevelCommandCallbacks callbacks, string workingDirectory)
        {
            return (new TopLevelCommandExecutor(topLevelCommand, callbacks)).Run(new UnstoppableJobHandle(), workingDirectory);
        }

        public static ITopLevelCommandResults RunUnstoppable(ITopLevelCommand topLevelCommand, ITopLevelCommandCallbacks callbacks, string workingDirectory, IDictionary<string, VariableValue> additionalVariables)
        {
            return (new TopLevelCommandExecutor(topLevelCommand, callbacks)).Run(new UnstoppableJobHandle(), workingDirectory, additionalVariables);
        }

        #endregion

        #region Public Methods

        public ITopLevelCommandResults Run(IJobHandle jobHandle, string workingDirectory, ILazyVariableDefinition lazyPrimaryOperationVariableDefinition)
        {
            return this.Run(jobHandle, workingDirectory, new VariableDictionary(), lazyPrimaryOperationVariableDefinition);
        }

        public ITopLevelCommandResults Run(IJobHandle jobHandle, string workingDirectory)
        {
            return this.Run(jobHandle, workingDirectory, new VariableDictionary());
        }

        public ITopLevelCommandResults Run(IJobHandle jobHandle, string workingDirectory, IDictionary<string, VariableValue> additionalVariables, IEnumerable<ILazyVariableDefinition> lazyPrimaryOperationVariableDefinitions)
        {
            // Copy the variable dictionaries because we are going to modify them and we don't want to modify our original data because that would
            // break this classes ability to be used to run multiple times
            IDictionary<string, VariableValue> primaryVariables = new VariableDictionary(additionalVariables);
            IDictionary<string, VariableValue> preAndPostVariables = new VariableDictionary(additionalVariables);
            VariableUtilities.AddDictionaryToDictionary(primaryVariables, this._topLevelCommand.PrimaryOperationGlobalInputVariables);
            VariableUtilities.AddDictionaryToDictionary(preAndPostVariables, this._topLevelCommand.PreAndPostOperationGlobalInputVariables);

            var preAndPostTransformationDatas = this._topLevelCommand.TransformationData.PreAndPostTransformationChain;
            // Copy the variables before passing so that in case the dictionary is modified directly, we don't modify our original, which we need in order to figure out the new variables that were defined.
            var tmpCopiedVariables = new VariableDictionary(preAndPostVariables);
            var tmpPreOperationResults = this.RunExternalOperationCollection(jobHandle, this._topLevelCommand.PreCommands, workingDirectory, preAndPostTransformationDatas.ChainData, tmpCopiedVariables);

            bool haltFurtherExecution = tmpPreOperationResults.Item1;

            // We need to update the primary variable dictionary with any variables that were defined, but we don't want to let any of the original pre & post variables 'leak' into the primary variable
            // dictionary because technically those variables were not defined for the primary command.
            UpdateVariableDictionaryWithAdditionsOnly(primaryVariables, preAndPostVariables, tmpPreOperationResults.Item3);

            // Now we can update the preAndPost dictionary
            preAndPostVariables = tmpPreOperationResults.Item3;

            IExternalOperationResults primaryOperationResults;

            // If a failure occurred during the pre operations, don't execute the primary command
            if (haltFurtherExecution)
            {
                primaryOperationResults = CreateNotRanOperationResults();
            }
            else
            {
                // Primary commands are allowed to have a different set of transformations defined.  For example, one day, appending of ClusterJobs may become a transformation.
                // Regardless of whether or not that ever happens, the point is give the TransformationData the ability to define a different set of transformations for the primary command
                // if it wishes.
                var primaryTransformationDatas = this._topLevelCommand.TransformationData.PrimaryCommandTransformationChain;
                // Copy the variables before passing so that in case the dictionary is modified directly, we don't modify our original, which we need in order to figure out the new variables that were defined.
                tmpCopiedVariables = new VariableDictionary(primaryVariables);
                var tmpPrimaryOperationResults = this.RunExternalOperationWithStateHandling(jobHandle, this._topLevelCommand.PrimaryCommand, workingDirectory, primaryTransformationDatas.ChainData, tmpCopiedVariables, lazyPrimaryOperationVariableDefinitions);

                // update our state variables
                haltFurtherExecution = tmpPrimaryOperationResults.Item1;
                primaryOperationResults = tmpPrimaryOperationResults.Item2;

                // We need to update the pre & post command dictionary to include any variables defined by the primary command
                UpdateVariableDictionaryWithAdditionsOnly(preAndPostVariables, primaryVariables, tmpPrimaryOperationResults.Item3);

                // Now that we've merged changes, we can update the variable
                primaryVariables = tmpPrimaryOperationResults.Item3;
            }

            IEnumerable<IExternalOperationResults> postOperationResults;

            if (haltFurtherExecution)
            {
                postOperationResults = this._topLevelCommand.PostCommands.Select(o => CreateNotRanOperationResults());
            }
            else
            {
                // Copy the variables before passing so that in case the dictionary is modified directly, we don't modify our original, which we need in order to figure out the new variables that were defined.
                tmpCopiedVariables = new VariableDictionary(preAndPostVariables);
                var tmpPostOperationResults = this.RunExternalOperationCollection(jobHandle, this._topLevelCommand.PostCommands, workingDirectory, preAndPostTransformationDatas.ChainData, tmpCopiedVariables);

                // update our state variables
                haltFurtherExecution = tmpPostOperationResults.Item1;
                postOperationResults = tmpPostOperationResults.Item2;

                // Always update variables, don't need to check if failed or anything that is handled by the code for running the operation collection.
                preAndPostVariables = tmpPostOperationResults.Item3;
            }

            // Results don't need to include the extra info VariableValue contains, so convert to a string value dictionary
            return new TopLevelCommandResults(primaryOperationResults, tmpPreOperationResults.Item2, postOperationResults, primaryVariables.ToStringValueDictionary(), preAndPostVariables.ToStringValueDictionary(), haltFurtherExecution);
        }

        public ITopLevelCommandResults Run(IJobHandle jobHandle, string workingDirectory, IDictionary<string, VariableValue> additionalVariables, ILazyVariableDefinition lazyPrimaryOperationVariableDefinition)
        {
            return this.Run(jobHandle, workingDirectory, additionalVariables, new List<ILazyVariableDefinition>(new [] { lazyPrimaryOperationVariableDefinition }));
        }

        public ITopLevelCommandResults Run(IJobHandle jobHandle, string workingDirectory, IDictionary<string, VariableValue> additionalVariables)
        {
            return this.Run(jobHandle, workingDirectory, additionalVariables, new List<ILazyVariableDefinition>());
        }

        public ITopLevelCommandResults RunUnstoppable(string workingDirectory)
        {
            return this.Run(new UnstoppableJobHandle(), workingDirectory);
        }

        public ITopLevelCommandResults RunUnstoppable(string workingDirectory, IDictionary<string, VariableValue> additionalVariables)
        {
            return this.Run(new UnstoppableJobHandle(), workingDirectory, additionalVariables);
        }

        #endregion

        #region Internal Static Methods

        internal static IExternalOperationData ProcessTransformation(IExternalOperationData operation, IEnumerable<IExternalOperationTransformationData> transformations, IExternalOperationTransformationFactory transformationFactory)
        {
            throw new NotImplementedException();
        }

        internal static IDictionary<string, VariableValue> MergeOperationOutputVariablesIntoGlobalRunVariables(IDictionary<string, VariableValue> globalRunVariables, IDictionary<string, string> operationOutputVariables)
        {
            foreach (var pair in operationOutputVariables)
            {
                // In order to prevent unnecessary complexity, don't allow commands to overwrite variables defined by commands that were ran before them.
                // Note by Mike (5/19/2014) : I don't see any reason to allow output variables to override global variables even if the variable allows
                // overwriting.  We could implement it if need be, but I suggest we don't until there is a need since it will complicate the output definition
                if (globalRunVariables.ContainsKey(pair.Key))
                {
                    throw new InvalidOperationException(string.Format("The output variable {0} was already defined by another command and cannot be overwritten", pair.Key));
                }

                globalRunVariables.Add(pair.Key, pair.Value.ToVariableValue());
            }

            return globalRunVariables;
        }

        internal static bool DoResultsHaveExpectedOutputVariables(IExternalOperationData operationData, IExternalOperationResults results)
        {
            return DoResultsHaveExpectedOutputVariables(operationData.ExpectedOutputVariables, results.OutputVariables);
        }

        /// <summary>
        /// Overloaded signature that decouples from the interface types for easier unit testing
        /// </summary>
        /// <param name="expectedOutputs"></param>
        /// <param name="outputVariables"></param>
        /// <returns></returns>
        internal static bool DoResultsHaveExpectedOutputVariables(IEnumerable<string> expectedOutputs, IDictionary<string, string> outputVariables)
        {
            var expectedAsList = new List<string>(expectedOutputs);
            if (expectedAsList.Count == 0 && outputVariables.Count == 0)
            {
                return true;
            }

            if (expectedAsList.Count != outputVariables.Count)
            {
                return false;
            }

            foreach (var item in expectedAsList)
            {
                if (!outputVariables.ContainsKey(item))
                {
                    return false;
                }
            }

            return true;
        }

        #endregion

        #region Private Static Methods

        private static IExternalOperationResults CreateNotRanOperationResults()
        {
            return new NotRanExternalOperationResults();
        }

        private static bool DetermineIfHaltExecution(IExternalOperationData operationData, IExternalOperationResults operationResults, ITopLevelCommandErrorNotificationCallbacks errorNotificationCallbacks)
        {
            if (operationResults.WasKilled || !operationResults.WasStarted)
            {
                return true;
            }

            if (operationResults.Failed)
            {
                errorNotificationCallbacks.ExternalOperationFailed(operationData, operationResults);
                return true;
            }

            if (!DoResultsHaveExpectedOutputVariables(operationData, operationResults))
            {
                errorNotificationCallbacks.ExternalOperationHasIncorrectOutputs(operationData, operationResults);
                return true;
            }

            return false;
        }


        private static IDictionary<string, string> EvaluateLazyVariableDefinitions(IDictionary<string, string> variables, IEnumerable<ILazyVariableDefinition> lazyVariableDefinitions)
        {
            var copiedVariables = new Dictionary<string, string>(variables);
            foreach (var lazyDefinition in lazyVariableDefinitions)
            {
                // Copy the variable dictionary we pass to the lazy definition so that it can't directly modify the variable dictionary we are going to use.
                // this is to force each variable definition to only do one thing.  As of writing this, this mechanism could easily be abused and instead should only
                // be used when absolutely needed.  Forcing 1 definition object be variable will help ensure it's only used when needed.
                // Note : Ideally we would passing a read only dictionary.  But .NET doesn't have one and I haven't bothered to implement one.  Although it does seem
                // overdue with all of the copying that is going on
                var result = lazyDefinition.DefineVariable(new Dictionary<string, string>(copiedVariables));
                copiedVariables.Add(result.Item1, result.Item2);
            }

            return copiedVariables;
        }

        private static void UpdateVariableDictionaryWithAdditionsOnly(IDictionary<string, VariableValue> dictionaryToUpdate, IDictionary<string, VariableValue> otherDictionary, IDictionary<string, VariableValue> modifiedOtherDictionary)
        {
            // Check for invalid combinations of input dictionaries
            if (dictionaryToUpdate == otherDictionary)
            {
                throw new ArgumentException();
            }

            if (dictionaryToUpdate == modifiedOtherDictionary)
            {
                throw new ArgumentException();
            }

            // No new variables were defined, nothing to do
            if (otherDictionary.Count == modifiedOtherDictionary.Count)
            {
                return;
            }

            foreach (var pair in modifiedOtherDictionary)
            {
                if (!otherDictionary.ContainsKey(pair.Key))
                {
                    dictionaryToUpdate.Add(pair.Key, pair.Value);
                }
            }
        }

        #endregion

        #region Private Methods

        private Tuple<bool, IEnumerable<IExternalOperationResults>, IDictionary<string, VariableValue>> RunExternalOperationCollection(
            IJobHandle jobHandle,
            IEnumerable<IExternalOperationData> operationDataCollection,
            string workingDirectory,
            IEnumerable<IExternalOperationTransformationData> transformationDatas,
            IDictionary<string, VariableValue> variables)
        {
            var operationResults = new List<IExternalOperationResults>();
            bool haltFurtherExecution = false;
            var transformationDatasCollection = transformationDatas.ToList();
            foreach (var operation in operationDataCollection)
            {
                if(!haltFurtherExecution)
                {
                    var tmpResults = this.RunExternalOperationWithStateHandling(jobHandle, operation, workingDirectory, transformationDatasCollection, variables);

                    // update our state variables
                    haltFurtherExecution = tmpResults.Item1;
                    variables = tmpResults.Item3;
                    operationResults.Add(tmpResults.Item2);
                }
                else
                {
                    operationResults.Add(CreateNotRanOperationResults());
                }
            }

            return new Tuple<bool, IEnumerable<IExternalOperationResults>, IDictionary<string, VariableValue>>(haltFurtherExecution, operationResults, variables);
        }

        private Tuple<bool, IExternalOperationResults, IDictionary<string, VariableValue>> RunExternalOperationWithStateHandling(
            IJobHandle jobHandle,
            IExternalOperationData operationData,
            string workingDirectory,
            IEnumerable<IExternalOperationTransformationData> transformationDatas,
            IDictionary<string, VariableValue> variables,
            IEnumerable<ILazyVariableDefinition> lazyVariableDefinitions)
        {
            bool haltFurtherExecution = false;

            // the interfaces we call from here on don't need a variable dictionary with VariableValue because they won't do any variable modification and thus don't need
            // the extra members on VariableValue.  So convert to string, string dictionary and pass that along.
            var stringValueVariables = variables.ToStringValueDictionary();

            // Evaluate lazy variables before processing the transformations because the transformation step may be where the variable expand occurs and if it does,
            // and the lazy variables haven't been defined yet, well.. that's a problem.  For example, RSM_HPC_COMMAND is lazy defined and it needs to be expanded during the transformation process.
            stringValueVariables = EvaluateLazyVariableDefinitions(stringValueVariables, lazyVariableDefinitions);

            // process transformations first.
            var externalOperationDataToRun = this._transformationProcessor.ProcessTransformation(operationData, transformationDatas, stringValueVariables);

            var operationResult = this._externalOperationExecutor.RunExternalOperation(jobHandle, externalOperationDataToRun, workingDirectory, stringValueVariables);

            // Set a flag so that we skip executing operations after this one
            if (DetermineIfHaltExecution(operationData, operationResult, this._errorNotificationCallbacks))
            {
                haltFurtherExecution = true;
            }
            else
            {
                // Only merge output variables back into the main variable dictionary if the operation was successful.
                // If the operation failed we may not have complete stdout or something so what data we have may be wrong anyways
                variables = MergeOperationOutputVariablesIntoGlobalRunVariables(variables, operationResult.OutputVariables);
            }

            return new Tuple<bool, IExternalOperationResults, IDictionary<string, VariableValue>>(haltFurtherExecution, operationResult, variables);
        }

        private Tuple<bool, IExternalOperationResults, IDictionary<string, VariableValue>> RunExternalOperationWithStateHandling(IJobHandle jobHandle, IExternalOperationData operationData, string workingDirectory, IEnumerable<IExternalOperationTransformationData> transformationDatas, IDictionary<string, VariableValue> variables)
        {
            return RunExternalOperationWithStateHandling(jobHandle, operationData, workingDirectory, transformationDatas, variables, new List<ILazyVariableDefinition>());
        }

        #endregion

        #region Private Classes

        private class NotRanExternalOperationResults : IExternalOperationResults
        {
            public bool WasKilled
            {
                get
                {
                    return false;
                }
            }

            public bool WasStarted
            {
                get
                {
                    return false;
                }
            }

            public bool Failed
            {
                get
                {
                    return false;
                }
            }

            public IDictionary<string, string> OutputVariables
            {
                get { throw new NotSupportedException(); }
            }
        }

        private class NoErrorNotificationCallbacks : ITopLevelCommandErrorNotificationCallbacks
        {
            public static readonly ITopLevelCommandErrorNotificationCallbacks Instance = new NoErrorNotificationCallbacks();

            public void ExternalOperationFailed(IExternalOperationData operationData, IExternalOperationResults operationResults)
            {
            }

            public void ExternalOperationHasIncorrectOutputs(IExternalOperationData operationData, IExternalOperationResults operationResults)
            {
            }
        }

        private class UnstoppableJobHandle : IJobHandle
        {
            internal UnstoppableJobHandle()
            {
            }

            public bool HasBeenKilled
            {
                get
                {
                    return false;
                }
            }

            public bool ShouldStop
            {
                get
                {
                    return false;
                }
            }
        }

        private class NoTopLevelCommandCallbacks : ITopLevelCommandCallbacks
        {
            public static readonly ITopLevelCommandCallbacks Instance = new NoTopLevelCommandCallbacks();

            public void StdoutReceived(string data)
            {
            }

            public void StderrReceived(string data)
            {
            }

            public void DisplayDebugOutput(string message)
            {
            }

            public void DisplayOutput(string message)
            {
            }
        }

        #endregion
    }
}
