function err = ecgError(x,s,freq,debug) %nested function

% err = ecgError(x,s,freq)
%
% Input Variables
%   x - parameters for the ecgGen that are to be estimated
%   s - signal
%   freq - sampling freq
%
% Output Variables
%   err - SSE of the generated ECG and the original signal
%
% Description
%   This nested function is used by fmincon to find the minimum error
%   parameters of the ecg model.

% Created
%   4/21/2006, Richard J. Povinelli, Marquette University
%
% This software is released under the terms of the GNU General
% Public License (http://www.gnu.org/copyleft/gpl.html).
% Modified

ecg = ecgGen(1:length(s),convertX(x));
d = s(:) - ecg(:); %residual
err = d(:)' * d(:); %sum of square error

if nargin == 4 %debug
    t = (1:length(s))./freq;
    plot(t,s,t,ecg);
    Q = debug(1)/freq;
    T = debug(2)/freq;
    line([Q,Q],[min(s) max(s)],'Color','c');
    line([T,T],[min(s) max(s)],'Color','k');
end %if
