 function [res,res_dm,nr] = CS_PC_est(x,hp_prel3,pc_m,pc_2reg,N,T,pc_cs,reg_gl,factor) % Real HP changes (TxN); choice of CS averages  vs PC regional approach; choice of regional vs global approach; no. of factors if reg_gl=1 (2-8)
  if pc_cs==0
   national=mean(x,2);
   new_england=mean(x(:,~(hp_prel3(1,:)>6)),2);
   mid_east=mean(x(:,~(hp_prel3(1,:)>12|hp_prel3(1,:)<7)),2);
   s_east=mean(x(:,~(hp_prel3(1,:)>24|hp_prel3(1,:)<13)),2);
   gr_lakes=mean(x(:,~(hp_prel3(1,:)>29|hp_prel3(1,:)<25)),2);
   plains=mean(x(:,~(hp_prel3(1,:)>36|hp_prel3(1,:)<30)),2);
   s_west=mean(x(:,~(hp_prel3(1,:)>40|hp_prel3(1,:)<37)),2);
   rock_mount=mean(x(:,~(hp_prel3(1,:)>45|hp_prel3(1,:)<41)),2);
   f_west=mean(x(:,~(hp_prel3(1,:)>51|hp_prel3(1,:)<46)),2);
  elseif pc_cs==2
   national=pc_m(:,1);
   new_england=pc_2reg(:,1:2);
   mid_east=pc_2reg(:,3:4);
   s_east=pc_2reg(:,5:6);
   gr_lakes=pc_2reg(:,7:8);
   plains=pc_2reg(:,9:10);
   s_west=pc_2reg(:,11:12);
   rock_mount=pc_2reg(:,13:14);
   f_west=pc_2reg(:,15:16);
  end
   
  % Regressions (regional vs global regressors)
   res1=zeros(T,N);
    for i=1:N
     if reg_gl==0;
        Y1=x(:,i);
        if hp_prel3(1,i)<7
           X1=[ones(T,1) national new_england ];
        elseif hp_prel3(1,i)<13 && hp_prel3(1,i)>6
           X1=[ones(T,1) national mid_east ];
        elseif hp_prel3(1,i)<25 && hp_prel3(1,i)>12
           X1=[ones(T,1) national s_east];
        elseif hp_prel3(1,i)<30 && hp_prel3(1,i)>24
           X1=[ones(T,1) national gr_lakes];
        elseif hp_prel3(1,i)<37 && hp_prel3(1,i)>29
           X1=[ones(T,1) national plains];
        elseif hp_prel3(1,i)<41 && hp_prel3(1,i)>36
           X1=[ones(T,1) national s_west];
        elseif hp_prel3(1,i)<46 && hp_prel3(1,i)>40
           X1=[ones(T,1) national rock_mount];
        elseif hp_prel3(1,i)>45
           X1=[ones(T,1) national f_west];
        end
     elseif reg_gl==1;
        Y1=x(:,i);
        X1=[ones(T,1) pc_m(:,1:factor)];
     end
        Coef1=(X1'*X1)\X1'*Y1;     
        res1(:,i)=Y1-X1*Coef1; 
    end
    nr=size(X1,2);
  % Real house price residuals
    res=res1';
    m_res=mean(res,2);
    res_dm=zeros(size(res,1),size(res,2));
     for i=1:size(res,1)
      res_dm(i,:)=(res(i,:)-m_res(i,1));
     end
    