function flag=waitonlock(md)
%WAITONLOCK - wait for a file
%
%   This routine will return when a file named 'filename' is written to disk.
%   If the time limit given in input is exceeded, return 0
%
%   Usage:
%      flag=waitonlock(md)

%Get filename (lock file) and options
executionpath=md.cluster.executionpath;
cluster=md.cluster.name;
login=md.cluster.login;
if isprop(md.cluster,'port') 
	port=md.cluster.port;
end
timelimit=md.settings.waitonlock;
filename=[executionpath '/' md.private.runtimename '/' md.miscellaneous.name '.lock'];

%waitonlock will work if the lock is on the same machine only: 
if ~strcmpi(oshostname(),cluster),

	disp('solution launched on remote cluster. log in to detect job completion.');
	choice=input('Is the job successfully completed? (y/n)','s');
	if ~strcmp(choice,'y'), 
		disp('Results not loaded... exiting'); 
		flag=0;
	else
		flag=1;
	end

%job is running on the same machine
else

	if ismember('interactive',properties(md.cluster)) & md.cluster.interactive
		%We are in interactive mode, no need to check for job completion
		flag=1;
		return;
	end
	%initialize time and file presence test flag
	time=0; ispresent=0;
	disp(['waiting for ' filename ' hold on... (Ctrl+C to exit)'])

	%loop till file .lock exist or time is up
	while (ispresent==0 & time<timelimit)
		ispresent=exist(filename,'file');
		pause(1);
		time=time+1/60;
	end

	%build output
	if (time>timelimit),
		disp('Time limit exceeded. Increase md.settings.waitonlock');
		disp('The results must be loaded manually with md=loadresultsfromcluster(md).');
		error(['waitonlock error message: time limit exceeded']);
		flag=0;
	else
		flag=1;
	end
end
