function [mon,corrs,maxc,maxcm]=lagcor_chc(N,p1,p2)
% =========================================================================
% Computing lag Correlation of p1 and p2
% input:      N[int]: Range of lagging mths
%            p1[row]: data 1
%            p2[row]: data 2
% output:   mon[12*N,1]: Lagging month(s), between -N and N    
%         corrs[12*N,1]: Correlations of [p2] and [p1 laging mon month(s)].
%          maxc[float]:  Max. correlation.
%         maxcm[int]: lagging month(s) with respect to [maxc]
% ========================================================================
p1=reshape(p1,[length(p1),1]);p2=reshape(p2,[length(p2),1]);
cut=N;
%np=1+cut:length(p1)-cut;
mon=-cut:cut;
corrs=zeros(length(mon),1);
for i=1:N
% negative lag
    [A]=corrcoef(p1(1:end-i),p2(i+1:end));
    corrs(N-i+1)=A(1,2);
% positive lag
    [A]=corrcoef(p1(i+1:end),p2(1:end-i));
    corrs(N+i+1)=A(1,2);
end
% zero lag
    [A]=corrcoef(p1,p2);
    corrs(N+1)=A(1,2);

[mm in] = max(abs(corrs)); 
maxcm = mon(in);
maxc = corrs(in);

%figure;clf;set(gca,'fontsize',16);set(gcf,'color','w')
if(0==1)
figure('Units','centimeters','position',[2 3 30 15],'color','w')
axes('Units','centimeters','position',[1.8 1.5 27.5 12.5]);
plot(mon,corrs,'r','linewidth',3);grid on;hold on
xlabel('p1 lags [mons]','fontsize',16);ylabel('Correlation','fontsize',16);
axis([mon(1) mon(end) -1 1]);
plot([0 0],[-1 1],'k')
legend(['Max. R= ',sprintf('%3.2f',corrs(in)),', p1 lags ',sprintf('%d',maxcm),' month(s)'],4);
title('p1 vs. p2','fontsize',16);
set(legend,'fontsize',16);
xlim([-N N]);
end
return;
