function [ baseline ] = ecg_calculate_baseline(ecg_vector, samplerate)
%ECG_CALCULATE_BASELINE calculate a baseline from an ecg

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

    if ~isscalar(samplerate) || ~isnumeric(samplerate) || (fix(samplerate) ~= samplerate)
        error('cvp:ecg_calculate_baseline:samplerate_not_integer', 'samplerate must be an integer');
    end

    % Calculate Basline Drift via Median Filter
    %Added .1 seconds to the median filters, to better get rid of the waves
    s_ecg_filt = medfilt1(ecg_vector, fix(0.25 * samplerate), 10*samplerate); % gets rid of QRS Complexes
    s_ecg_filt = medfilt1(s_ecg_filt, fix(0.75 * samplerate), 10*samplerate); % gets rid of P and T waves

    %Try Low Pass filter the result, to avoid sudden changes
    hd = create_filter_cheby(8, 2 / (samplerate / 2), 'low');
    baseline = filtfilthd(hd, s_ecg_filt);
%baseline = s_ecg_filt
end
% Author: Jan F. Kraemer <jan.kraemer@rwth-aachen.de>
%
