function [reply,message]=handshakeVOL(VOL,timeout)
    % Reply=handshakeVOL(VOL,timeout)
    %
    % Sends commands 'string' to VolViewer by writing it into the WatchFile
    % then waits for VolViewer to echo 'string' back in another file: WatchMeFile.txt
    %
    % VOL, a VolViewer object
    % timeout, the length of time the function will wait for VolViewer to complete its task
    %        default is set by VOL.timeout, i.e. 30 secs.
    %        if timeout==0 then the function will not wait - it just returns with
    %           Reply=0
    %        else timeout should be set to, say, 10 seconds (Default 30 secs)
    %
    % reply, if VolViewer has not replied within the specified time, Reply=false
    %        elseif VolViewer has replied, Reply=true;
    % message, if VolViewer has not replied within the specified time, reply=timeout
    %        else message=string
    % Usage
    % [reply,message]=handshakeVOL(VOL);
    % if ~handshakeVOL(VOL,10)
    %     error('VolViewer has not replied within 10 secs')
    % end
    %
    % J.Andrew Bangham 2012
    if nargin<1
        error('needs VolViewer object and at least one command');
    end
    if nargin<2
        timeout=VOL.timeout;
    end
    tempstring=VOL.current_command_ID{1};
    ID=str2num(tempstring);
    VOL.current_command_ID={sprintf('%04d',ID+1)};
    ID=VOL.current_command_ID{1};%sprintf('%s',VOL.current_command_ID);
    t1=clock;
    filename=fullfile(VOL.PathToWatchFile,sprintf('WatchMeFile%1d.txt',VOL.WatchFileNumber));
    t2=clock;
    string=sprintf('save_text(''%s'', ''%s'')',ID,filename);
    VOL=commandsVOL(VOL,string);
    
    k=0;
    while (exist(filename)~=2)&&(etime(t2, t1)<timeout)
        pause(1);
        t2=clock;
        k=k+1;
        if k>2
            fprintf(1,'v');
            if rem(k,20)==1
                fprintf(1,'Waiting for WatchMeFile\n');
            end
        end
    end
    done=false;
    k=0;
    while (exist(filename)==2) &&(etime(t2, t1)<timeout) && (~done)
        fid=fopen(filename,'r');
        if fid~=0
            string=fgetl(fid);
            fclose(fid);
            if strcmpi(string,ID)
                done=true;
                delete(filename);
            end
        end
        pause(0.1);
        k=k+1;
        if k>2
            fprintf(1,'V');
            if rem(k,20)==1
                fprintf(1,'Waiting for VolViewer\n');
            end
        end
    end
    if ~done
        reply=false;
        message=timeout;
        if exist(filename)~=2
            message=string;
        end
    else
        fprintf(1,'VolViewer replied with %s and WatchMeFile.txt deleted\n',string),
        reply=true;
    end
end