function out = normalizedCorr(data1,data2,range,max,half)
% 正規化された相関 p(t1-t2)/[r_1(t1)*r_2(t2)] のヒストグラム
% 
% [負 0 正] = normalizedCorr(データ1,データ2,試行範囲,最大時間差,発火率推定幅)
% 
trial=size(range,1);		%%% 試行数
len=range(1,2)-range(1,1);	%%% 切り出す長さ

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 発火率の推定
%
% [t-half, t+half] の区間(幅 2*half+1)で発火率 r(t) の推定を行う
%
rate1=rate(data1,range,half);	%%% data1の発火率 r_1(t) の推定値 
rate2=rate(data2,range,half);	%%% data2の発火率 r_2(t) の推定値 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 発火率で正規化した相関ヒストグラム

lhist=zeros(2*max+1,1);

for i=1:trial
  train1=data1(range(i,1)<data1 & data1<=range(i,1)+len)-range(i,1);
  train2=data2(range(i,1)<data2 & data2<=range(i,1)+len)-range(i,1);
			%%% 試行ごとに切り出す．

  for j1=1:length(train1)
     for j2=1:length(train2)
     lag=train1(j1)-train2(j2);
	   %%% data2のスパイク時刻を基準とした、data1のスパイクの相対時刻列

	if(-max<=lag & lag<=max)
	   nor=(len-abs(lag))*rate1(train1(j1))*rate2(train2(j2));
			%%% 正規化因子: (平均時間)*r_1(t)*r_2(t)

           lhist(max+lag+1) = lhist(max+lag+1)+1/nor;
        end
     end
  end
end

lhist = lhist/trial;

out= zeros(max,3);
out(:,1)= lhist(max:-1:1) ;
out(1,2)= lhist(max+1);
out(:,3)= lhist( (max+2):(2*max+1) );

