using System;
using System.Reflection;
using System.IO;

namespace @NAMESPACE@Wrapper
{
    class @MAINCLASSNAME@Wrapper
    {
        private String[] AssemblySearchPaths = { @ASSEMBLYSEARCHPATH@ };

        private String ExePath = @"@EXEPATH@";

        private String MainClassName = "@NAMESPACE@.@MAINCLASSNAME@";

        private Assembly exeAssembly;

        public @MAINCLASSNAME@Wrapper(string[] args)
        {
            // Attach the resolve event handler to the AppDomain so that missing library assemblies will be searched
            AppDomain currentDomain = AppDomain.CurrentDomain;
            currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

            // Dynamically load the executable assembly
            exeAssembly = Assembly.LoadFrom(ExePath);

            // Lookup the main class
            Type mainClass = exeAssembly.GetType(MainClassName);

            // Lookup the main method
            MethodInfo mainMethod = mainClass.GetMethod("Main");

            // Invoke the main method
            mainMethod.Invoke(this, new Object[] {args});
        }

        static void Main(string[] args)
        {
            new @MAINCLASSNAME@Wrapper(args);
        }

        private Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
        {
            // This handler is called only when the common language runtime tries to bind to the assembly and fails.

            Assembly MyAssembly;
            String assemblyPath = "";
            String requestedAssemblyName = args.Name.Substring(0, args.Name.IndexOf(","));

            // Search for the right path of the library assembly
            foreach (String currentAssemblyPath in AssemblySearchPaths)
            {
                assemblyPath = currentAssemblyPath + "/" + requestedAssemblyName + ".dll";

                if (File.Exists(assemblyPath))
                    break;
            }

            // Load the assembly from the specified path. 					
            MyAssembly = Assembly.LoadFrom(assemblyPath);

            // Return the loaded assembly.
            return MyAssembly;
        }

    }
}
