% -----------------------------------------------------------------------------
% HexapodSagStability.m
% -----------------------------------------------------------------------------
%
%  This script runs a spatial hexapod simulation with the specified 
% parameters and determines whether the locomotion was stable or not. In
% particular, it modulates the saggital plane initial conditions.
%
% -----------------------------------------------------------------------------
%
%  function val = HexapodSagStability( point );
%
% -----------------------------------------------------------------------------
%  Input Arguments and Global Variables:
%
%     point : A 2 element array [ydot, z] indicating which point in the apex
%             coordinate space should be investigated. This value chooses the 
%             initial condition.
%
%   The following global variables are required for proper operation:
%
%     params      : struct with hexapod parameters
%     speedrange  : 2 vector to specify the range of speeds
%     heightrange : 2 vector to specify the range of heights
%     basename    : Base filename for the RC and data files
%
% -----------------------------------------------------------------------------
%  Outputs :
%
%     val  : Indicates stability of the run.
%            1    : stable
%            0    : unstable, does not converge
%            < 0  : Simulation error (see DetectHexError.m)
%
% -----------------------------------------------------------------------------
%  Notes :
%
%    This script requires the following scripts to be in the path:
%
%      CreateRCFile.m
%      RunSimSect.m
%      HexapodDatatypes.m
%      LoadSimSectData.m
%      DetectHexError.m
%      AnalyzeHexRun.m
%
% -----------------------------------------------------------------------------
% $Id: HexapodSagStability.m,v 1.1.1.1 2003/10/28 20:05:59 ulucs Exp $
% -----------------------------------------------------------------------------

function val = HexapodSagStability( point );

global params;
global speedrange;
global heightrange;
global basename;

% Output file options
RCname = strcat( basename, '.rc' );
dataName = strcat( basename, 'dat' );

params.dataBaseName   =  dataName;

% Set the current goal
params.ydot_initial = ...
    speedrange(1) + point(1) * (speedrange(2) - speedrange(1));
params.z_initial = ...
    heightrange(1) + point(2) * (heightrange(2) - heightrange(1));

%  disp( sprintf('Running simulation with ydot:%f, z:%f', ...
%               params.ydot, params.z ) );

% Run hexapedal simulation
CreateRCFile( params, RCname );
[s,w] = RunSimSect( [' -c ' RCname ] );

errorflag = DetectHexError( w );
if ( errorflag == 0 )
  datatypes = HexapodDatatypes;
  hexdata = LoadSimSectData( dataName, datatypes );

  % Determine whether the run is stable or not
  stability = AnalyzeHexRun( hexdata, 10, params.final_apex, 1e-4 );

  val = stability.stable;
  
else
%  disp(sprintf('Error #%i', errorflag));
  val = -errorflag;
end
