function [ fixed_ecg ] = ecg_interpolate_nan(ecg_vector)
%ECG_INTERPOLATE_NAN Remove possible NaNs from an ecg signal

    if ~isvector(ecg_vector) || ~isnumeric(ecg_vector)
        error('cvp:ecg_interpolate_nan:ecg_not_vector', 'ecg_vector is not a numeric vector');
    end

    if size(ecg_vector, 1) ~= 1
        ecg_vector = reshape(ecg_vector, 1, length(ecg_vector));
    end

    nan_vector = isnan(ecg_vector);
    if (any(nan_vector))
        if all(nan_vector)
            error('cvp:ecg_interpolate_nan:ecg_all_nan', 'ecg_vector contains only NaNs');
        end
        mod_nan_vector = nan_vector;
        if nan_vector(1)
            non_nan_idx = find(~nan_vector, 1);
            ecg_vector(1) = ecg_vector(non_nan_idx);
            mod_nan_vector(1) = false;
        end
        if nan_vector(end)
            non_nan_idx = find(~nan_vector, 1, 'last');
            ecg_vector(end) = ecg_vector(non_nan_idx);
            mod_nan_vector(end) = false;
        end

        ecg_idx = 1:length(ecg_vector);
        fixed_ecg = interp1(ecg_idx(~mod_nan_vector), ecg_vector(~mod_nan_vector), ecg_idx);
    else
        fixed_ecg = ecg_vector;
    end
end
% Author: Jan F. Kraemer <jan.kraemer@rwth-aachen.de>
%
