function [sig,tests,sk,Q,chi]=res_sig(th,y,alpha,draw);
% 
% Test the normality and autocorrelation within the "th" IDPOLY model
%
% syntax: [sig,tests,sk,Q,chi]=res_sig(th,y,alpha)
% 
% INPTUS:
% th      : IDPOLY model
% y       : data vector
% alpha   : level of significance
%         : (optional input - implicitly 0.05)
% draw    : 0 = do no plot graphs, 1 = plot graphs
%         : (optional input - implicitly 1)
%
% OUTPUTS:
% sig     : statistical significance of autocorrelation of residuals within IDPOLY model
%         : (0 = residuals autocorrelated, 1 = residuals not autocorrelated)
% test    : vector of results of normality tests of residuals
%         : (all values:  0 = Gaussian; 1 = Non-Gaussian)
% sk      : skewness, kurtosis (- 3)
% Q       : Q-statistics for computation of autocorrelation of residuals
% chi     : percentile of Chi-square distribution for testing stat. sig.
%
% Created: May 2005, Jan Capek
% Modified: April 2006, Jan Capek
    


if nargin < 2
    error('At least two inputs needed')
end

if nargin < 3
    alpha=0.05;
    disp('Setting alpha = 0.05')
end

if nargin < 4
    draw = 1;
    disp('Will draw graphs')
end


e=pe(y,th);

if length(e)==1
    e=e.OutputData;
end

sk = [skewness(e); kurtosis(e)-3];

if draw == 1
    figure
    normplot(e);
    figure
    histfit(e,15);
end

jb=jbtest(e);                   % Jarque-Bera test
ks=kstest((e-mean(e))/std(e));  % Kolmogorov-Smirnov test
li=lillietest(e);               % Lilliefors test
% all tests: 0: Gaussian; 1: Non-Gaussian
tests=[jb;ks;li];



K=round(sqrt(th.EstimationInfo.DataLength));
r=acf(e,K);
Q=th.EstimationInfo.DataLength*sum(r.^2);

chi=chi2inv(1-alpha,K-length(th.ParameterVector));

sig = Q < chi;