%--------------------------------------------------------------------------
%
% PURPOSE: Simulate 21" AUV dynamics with the Qnx simulator. Plot the results.
% AUTHOR:  Rob McEwen
% DATE:    2015/4/14
%
%--------------------------------------------------------------------------
%
missionList = {'SimWCakeSimple.cfg',
               'Flat4c.cfg',
               'PortOALow2.cfg',
               'PortOAHigh.cfg',
               'PortOA30.cfg',
	       'PortAllRob.cfg',
               'SimMC1850.cfg',
               '20150827_IcebergTesting_m1v4_rob.cfg',
               'SimMC2800.cfg',
               'Transect.cfg',
	       'PlateauWest.cfg',
	       'PlateauTest.cfg',
	       'Wall2014.cfg',
               'SimVIsland.cfg'};

[status cname]=system('hostname');
fprintf('Starting a simulation on %s',cname);

if( exist('missionFileName')==0 )
    fprintf('Please set missionFileName. Supported missions are:\n');
    %missionList = textread('missionList.txt','%s');
    for( i=1:length(missionList) )
        fprintf('   %s\n',char(missionList(i)));
    end
    return
else
    pwdstr = pwd;
    if(strncmp(computer,'PCWIN',5))
        hostPathToOnboard = char(regexp(pwdstr,'\\.*onboard','match'));
	location = 'network';
	linDirPath = hostPathToOnboard;
            %
            % First swap the slash \ for /:
            for( i=1:length(linDirPath) )
                if(linDirPath(i) == '\')
                    linDirPath(i) = '/';
                end
            end
    elseif(strncmp(computer,'MAC',3))
      if( strfind(pwdstr, '/Volumes/'))
	location = 'network';
        hostPathToOnboard = char(regexp(pwdstr,'/Volumes/.*onboard','match'));
      elseif( strfind(pwdstr, '/Users/rob'))
	location = 'local';
        hostPathToOnboard = char(regexp(pwdstr,'/Users/rob/.*onboard','match'));
      else
	fprintf(['Can''t find either the local or network directory on the' ...
		 ' Mac.\n']);
      end
    else
	fprintf('Unrecognized computer type %s\n.',computer);
    end
        
    if( ~isempty(hostPathToOnboard) )
        cd(hostPathToOnboard)
        fprintf('Running out of %s directory %s\n.',location, pwd);
    else
        fprintf(['%s is an unrecognized directory.  Please cd to ' ...
                 '"onboard".\n'],pwdstr);
        return
    end

    if( strcmp(computer,'PCWIN64'))
        guestname = 'mvc-bi.shore.mbari.org';
        guestname = 'sandpiper-qnx.shore.mbari.org';
        fprintf('Telnetting to %s.\n',guestname);
    elseif( strcmp(computer,'MACI64'))
        %guestname = 'whitebird-qnx';
        %guestname = 'sandpiper-qnx.shore.mbari.org';
        guestname = '134.89.33.101';
    else
        fprintf('Unrecognized host.  Exit.\n');
        return
    end
    fprintf('Telnetting to %s.\n',guestname);
    worked = 0;
    recognized = 0;
    missionListStr='';
    len = length(missionList);
    for(i=1:len-1)
        %
        % strcat plays nasty tricks with trailing spaces.
        missionListStr = [missionListStr,char(missionList(i)),' '];
    end
    missionListStr = [missionListStr,char(missionList(len))];
    %missionList = textread('missionList.txt','%s');
    for( i=1:length(missionList) )
        if( strcmp(missionList(i), missionFileName ))
            recognized = 1;
            fprintf('Running supported mission %s out of %s.\n',...
                    missionFileName, hostPathToOnboard);
        end
    end
    if(~recognized) 
        fprintf('Running mission %s out of %s\n', ...
                missionFileName, hostPathToOnboard);
    end

      % Automated tranferring the mission to whitebird-qnx.  Need to compute
      % guestPathToMissions?  See below for guestPathToLatest. Or just
      % hardcode it?
      %
      if( strcmp(computer,'MACI64'))
	switch( location )
	 case{'network'}
	 case{'local'}
	  fprintf('Matlab: Transfer mission to guest:\n');
	  guestPathToMissions = 'auv-qnx/auv/altex/onboard/missions';
	  eval(['cd ', hostPathToOnboard, '/missions'])
	  putString = sprintf(['/usr/local/bin/ncftpput '...
		    '-R -u rob -p rob %s %s %s'], ...
			      guestname, guestPathToMissions, missionFileName);
	  [status result] = system(putString);
	  if( status )
	    fprintf('Matlab: Error transferring mission to guest: %s\n',result);
	    return
	  else
	    fprintf('Matlab: mission ncftpput suceeded.\n')
	  end
	end
      end
      
    fprintf('Matlab: Starting the qnx sim in 2 seconds.\n');
    pause(2);
    
    %    runString = sprintf(['rsh %s "../../offboard/sim ' ...
    %                        '%s > /dev/null >& /dev/null"'], guestname,...
    %                        missionFileName);
    %
    % The qnx .profile cd's to onboard/bin.
    %
    runString = sprintf('rsh %s ../../offboard/sim %s %s',...
                        guestname, ...
                        missionFileName, missionListStr);
    tic
    status = system(runString);
    telapsed=toc;

    fprintf('status = %d\n',status);
    
    if( status ~= worked ) 
        fprintf('Qnx sim failed with status = %d; Exit.\n',status);
        return
    end

    lsString = sprintf('rsh %s ls -l ../logs/latest',guestname);
    [status result] = system(lsString);
    
    if( status == worked )
        guestPathToLatest = ...
	    char(regexp(result, '[\w/-]*\d\d\d\d\.\d\d\d\.\d\d','match'));
        guestPathToLogs = ...
	    char(regexp(result, '[\w/-]*/logs/','match'));
        latestdir = char(regexp(result, '\d\d\d\d\.\d\d\d\.\d\d','match'));
        fprintf('Matlab:  latest = %s\n',guestPathToLatest);
        fprintf('Matlab:  latestdir = %s\n',latestdir);
    else
        fprintf('Matlab:  Can''t find "latest" in %s\n',result);
        return
    end        

    if( strcmp(computer,'PCWIN64'))
        eval(['cd //atlas', guestPathToLatest(10:end)])
    elseif( strcmp(computer,'MACI64'))
      switch( location )
       case{'network'}
	eval(['cd /Volumes', guestPathToLatest(10:end)])
       case{'local'}
	%eval(['cd /Users/rob', guestPathToLatest(10:end)])
	eval(['cd ', hostPathToOnboard, '/logs'])
	%runString = sprintf('rcp -r %s %s .',guestname, guestPathToLatest);
	getString = sprintf(['/usr/local/bin/ncftpget '...
		    '-R -u rob -p rob %s . %s'], ...
		    guestname, guestPathToLatest)	
	[status result] = system(getString);
	if( ~status )
	  fprintf('Matlab: %s\n',result);
	else
	  fprintf('Matlab: ncftpget suceeded.\n')
	end
	eval(['cd ', latestdir])
      end
    else
        fprintf('Unrecognized host.  Exit.\n');
        return
    end

    if(recognized)
        % switch(missionFileName)
        %     case{'SimWCakeSimple.cfg','SimVIsland.cfg'}
        %     npbeams=119; idt.vertMt=0; plotSwFlags=1;
        %     loadData; review; dvl; deltaT
        %   case('Flat4c.cfg')
        %     npbeams=119; idt.vertMt=1; loc= 'portu';
        %     loadData; loadGrd; review; dvl; deltaT
        %   case{'PortOALow2.cfg', 'PortOA15.cfg','PortOAHigh.cfg'}
        %     npbeams=119; idt.vertMt=1; loc= 'portu';
        %     loadData; loadGrd; review; dvl; deltaT; deci=2; plotSurf
        %   case{'PortOA30.cfg'}
        %     npbeams=119; idt.vertMt=1; loc= 'portu';
        %     loadData; loadGrd; review; dvl; deltaT; terrainPlot; deci=2; plotSurf
        %   case{'SimMC1850.cfg','20150827_IcebergTesting_m1v4_rob.cfg'}
        %     npbeams=119; idt.vertMt=1; loc= 'MC1850';
        %     loadData; loadGrd; review; dvl; deltaT; terrainPlot; plotSurf
        %   case{'SimMC2800.cfg'}
        %     npbeams=119; idt.vertMt=1; loc= 'MC2800';
        %     loadData; loadGrd; review; dvl; deltaT; terrainPlot; plotSurf
        %   case{'PlateauTest.cfg', 'PlateauWest.cfg'}
        %     npbeams=119; idt.vertMt=1; 
        %     loadData; review; dvl; deltaT; plotThetaB;
        %   case{'Transect.cfg'}
        %     loadData; review; dvl
        %   otherwise
        %     fprintf('Unrecognized scenario.\n')
        % end
        if( strcmp(missionFileName,'SimWCakeSimple.cfg') || ...
	    strcmp(missionFileName,'SimVIsland.cfg'))
	  npbeams=119; idt.vertMt=0; plotSwFlags=1;
	  loadData; review; dvl; deltaT
	elseif( strcmp(missionFileName,'Flat4c.cfg') )
	  npbeams=119; idt.vertMt=1; loc= 'portu';
	  loadData; loadGrd; review; dvl; deltaT
        elseif( strncmp(missionFileName,'Port',4) )
	  npbeams=119; idt.vertMt=1; loc= 'portu';
	  loadData; loadGrd; review; dvl; deltaT; terrainPlot; deci=2; plotSurf
        elseif( strcmp(missionFileName,'SimMC1850.cfg') || ...
		strcmp(missionFileName,'20150827_IcebergTesting_m1v4_rob.cfg'))
	  npbeams=119; idt.vertMt=1; loc= 'MC1850';
	  loadData; loadGrd; review; dvl; deltaT; terrainPlot; plotSurf
	elseif( strcmp(missionFileName,'SimMC2800.cfg') )
	  npbeams=119; idt.vertMt=1; loc= 'MC2800';
	  loadData; loadGrd; review; dvl; deltaT; terrainPlot; plotSurf
	elseif( strncmp(missionFileName,'Plateau',7) )
	  npbeams=119; idt.vertMt=1; 
	  loadData; review; dvl; deltaT; plotThetaB;
	elseif( strncmp(missionFileName,'Transect.cfg',7) )
	  loadData; review; dvl
	elseif( strncmp(missionFileName,'Wall2014.cfg',7) )
	  npbeams=119; idt.vertMt=0; plotSwFlags=1; loc='wall';
	  loadData; loadGrd; review; dvl; deltaT; plotSurf
	else
            fprintf('Unrecognized scenario.\n')
        end
    else
        %loadData; review; dvl
	npbeams=119; idt.vertMt=1; loc= 'portu';
	loadData; loadGrd; review; dvl; deltaT; plotThetaB; deci=2; plotSurf
    end
    if( telapsed > 0 )
        fprintf(['Simulated time = %.1f; Elapsed time = %.1f; '...
                'speed increase of x%.2f.\n'],...
                dataNav(end,1), telapsed, dataNav(end,1)/telapsed);
    end   
       
    return
end
