function shipVelocity( hMainFig )
%
% Compute the ship velocity in knots
% Used to test bad Position
%
% At present 

% Get the data from the application GUI
% -------------------------------------
tsg = getappdata( hMainFig, 'tsg_data');

% Get tsg fieldnames
% ------------------
tsgNames     = fieldnames(tsg);
nbFieldNames = length( tsgNames );

% Record number
% -------------
tsgLength = length(tsg.DAYD);

% Test for bad velocity.
% Suppress the bad records
% ------------------------
nBadVelocity   = 0;
indBadVelocity = 1;
indStart       = 1;
velocity = nan*ones(tsgLength,1);

while ~isempty( indBadVelocity )

    % Spherical earth distance in km - Velocity in knots
    % --------------------------------------------------
    range    = m_lldist(tsg.LONX(indStart:tsgLength),tsg.LATX(indStart:tsgLength));
    velocity(indStart:tsgLength) = [range;0] ./ ((circshift(tsg.DAYD(indStart:tsgLength),-1)...
        -tsg.DAYD(indStart:tsgLength)) * 24 * 1.854);

    % Find velocity > 50 knots
    % ------------------------
    indBadVelocity = find( velocity(indStart:tsgLength) > 50 );

    if ~isempty( indBadVelocity )

        nextBad=circshift(indBadVelocity,-1)-indBadVelocity;

        if (nextBad(1)==1)
            
            % Case when one bad position lead to 2 bad velocities
            % ---------------------------------------------------
            indBadVelocity = indBadVelocity(1) + 1;

            % Delete bad record
            % -----------------
            for i = 1 : nbFieldNames

                para = char( tsgNames{i} );

                % Find array of length DAYD in the TSG structure
                % ----------------------------------------------
                if length( tsg.(para) ) == tsgLength
                    tsg.(para)(indStart+indBadVelocity-1,:) = [];
                end

            end

            tsgLength=tsgLength-1;
            indStart=indStart+indBadVelocity-2;

        else
            
            % Case when sudden shift in position: apply NaN to velocity
            % ---------------------------------------------------------
            indBadVelocity = indBadVelocity(1);
            velocity(indStart+indBadVelocity-1)=nan;
            indStart=indStart+indBadVelocity;

        end

        % Store the number of bad Velocity
        % --------------------------------
        nBadVelocity = nBadVelocity + 1;



    end

end

% Keep the number of data not in increasing date
% ----------------------------------------------
tsg.report.badvelocity = nBadVelocity;

% Keep ship velocity from positions if sog not available
% ------------------------------------------------------
if isempty(tsg.SPDC)
  tsg.SPDC = velocity(1:tsgLength);
end

% Save tsg structure
% ------------------
setappdata( hMainFig, 'tsg_data', tsg);

end
