function status = RemoteDanMC(MachineName,ScriptName)
% function hRemoteMatlab = RemoteDanMC(MachineName,Scriptname)
% runs the DanMC modeling program on another machine.

disp('About to try and launch the remote activeX server...');
try
   hRemoteMatlab = actxserver('Matlab.Application.single.5',MachineName);
   result = invoke(hRemoteMatlab, 'execute','disp(''This text is produced by another machine'')');
catch
   disp('Unable to start the active x server');
   status=-1;
   return
end


if (result == 0)
	release(hRemoteMatlab);
	hSpecServer = 0;
	error('Unable to initialise remote matlab');
end

disp('The remote active x server launched OK...')
disp('Now copying file to the shared workspace on DanF...')
dos(['copy "',ScriptName,'" "\\danf\share\Modeling\',ScriptName,'"']);

%have to use a directory not on the server because can't authenticate to hrr1?
%in fact if the computer is not logged in as me I can't even use a shared
%directory of DanF will have to do the simulation locally...
%If that is the can doesn't actually checkout a matlab licence either.
try
   disp('Changing remote system to the shared modeling directory on DanF...');
   invoke(hRemoteMatlab, 'execute',  'cd ''\\danf\share\Modeling''');
   s=invoke(hRemoteMatlab, 'execute',  'cd');
   
   if ~strcmp(s,'\\danf\share\Modeling') %then can't be authenticated cas it failed
      disp('Couldn''t change directory :( ');
      %give it something to do?
      disp('Generating 10000 random numbers on remote machine...');
      randnums = invoke(hRemoteMatlab, 'execute',  'rand(100,100)');
      f2;
      surf(randnums);
   else
      disp(['Succesffully changed to ', s]);
      %have to see up access to our scripts in this directory!
      invoke(hRemoteMatlab, 'execute',  'addpath(''\\Danf\Share\Modeling\matlabscripts'')')
      
      disp(['launching DanMC with: 'ScriptName '...']);
      RemoteProgress = invoke(hRemoteMatlab, 'execute',['DanMC(''' ScriptName ''',''',MachineName,''');'])
   end
   
   disp('The script has completed on the remote machine releasing the handle');
   release(hRemoteMatlab);
   status =0;
catch
   %if we fail release the activex server handle
   release(hRemoteMatlab);
   status =-1;
end
