function clean_frame = kalmanFilter(AR, Q, R, frame_data, initial_state, frame_index)
% function call made from kfukfpf.m file
%
% to clean the signal with the AR model
%

% disp('into the function kalmanFilter ..');
[F, H, G, P] = modelKalman(AR, Q, R);
p = length(AR);

%     % call the function to Kalman filter the signal
%     % the function call will have frame_index passed so that it can
%     % computation done. computation is different for first frame and
%     % different there after
%     %
%     for i = 1:1:length(frame_data)
%         cleaned_signal = kf(states, obsn, F, H, G, Q, R);
%
%     end;
frame_length = length(frame_data);
if frame_index == 0

    % initialize the state vector to initial order values of the
    % observation
    % not filtering the first p data points in the analysis frame
    %
    s(1:p) = initial_state;
    clean_frame = s;
    for i = p+1 : frame_length
        z = frame_data(i);
        x_state = s(i-p:i-1)';
        [s(i), P] = kf(x_state, z, P, Q, R, F, G, H);
        clean_frame = [clean_frame s(i)];
    end;
else
    % have a separate program for first order samples
    % a separate program code for the remaining samples
    %
    w(1:p) = initial_state;
    for i = 1:1:p
        z = frame_data(i);
        x_state = w(1:p)';
        [s(i), P] = kf(x_state, z, P, Q, R, F, G, H);
        w(1:p-1) = w(2:p);
        w(p) = s(i);
    end;
    s(1:p) = w(1:p);
    clean_frame = s;
    for i = p+1:1:frame_length
        z = frame_data(i);
        x_state = s(i-p:i-1)';
        [s(i), P] = kf(x_state, z, P, Q, R, F, G, H);
        clean_frame = [clean_frame s(i)];
    end;
end;

% clean_frame = s(i);
% figure;
% plot(frame_data, 'r');
% hold on; plot(clean_frame, 'k');
% legend('input data', 'cleaned data');
% disp('out of the function kalmanFilter ..');
% disp('out of the function kalmanFilter ..');
