% Cornwell-Schmidt Estimator (Within only)
% Written by Wonho Song, December 2002
% E-mail: whsong@kiep.go.kr, whsong73@hotmail.com

function [betaw,se_bw,CSSW,R2cw]=cssw(y,x,n)

   [nt,p] = size(x);
t=nt/n;


%%%%%%% CSS WITHIN %%%%%%%

t1 = 1:t; t1 = t1';  t2 = t1.^2;    
tt = [ones(t,1) t1 t2];

Pt=tt*inv(tt'*tt)*tt';
Qt=eye(t)-Pt;

       yy = []; 
       xx = [];

    for i = 1:n
       yy = [yy;Qt*y(t*(i-1)+1:t*i,1)];    
       xx = [xx;Qt*x(t*(i-1)+1:t*i,:)];
       end;

betaw = inv(xx'*xx)*xx'*yy;

err=yy-xx*betaw;
ssg=err'*err/(nt-n-p);
bcov=ssg*inv(xx'*xx);
se_bw=sqrt(diag(bcov));

temp = y-x*betaw;  


% Calculation of R2 
ey=y-mean(y);
R2cw=1-(err'*err)/(ey'*ey);
R2cw=[R2cw;1-(1-R2cw)*(nt-1)/(nt-p-n)];


thetaw=[];
for i=1:n
thetaw=[thetaw;inv(tt'*tt)*tt'*temp(t*(i-1)+1:t*i,1)];
end;

CSSW=[];
for i=1:n
CSSW=[CSSW tt*thetaw(3*(i-1)+1:3*i)];
end;

CSSW=CSSW-mean(mean(CSSW));

