function [ Hk ] = y_Hkappa_modified( RF, time, rayp, H, k, vp, weight )

% H-kappa search for P-receiver functions
% Chunquan Yu, @MIT-EAPS, 06/13

% RF: nt * ntrace matrix
% time: nt * 1 vector
% rayp: ntrace * 1 vector

% % H k range
% H = 20:0.1:80; % crustal thickness for searching
% k = 1.5:0.01:2.0; % kappa = Vp/Vs for searching
% vp = 6.3; % assumed crustal P-wave speed
% % weight for 3 phases: Ps, PpPs, PpSs+PsPs
% weight = [2/5 2/5 1/5];

% normalize data
for i = 1:size(RF,2)
    RF(:,i) = RF(:,i)/(max(RF(:,i))-min(RF(:,i)));
end

delta = time(2)-time(1);
r1 = zeros(length(k),length(H));
r2 = zeros(length(k),length(H));
r3 = zeros(length(k),length(H));
for m = 1:length(H)
    for n = 1:length(k)
%         if H(m) < 40  || k(n) < 1.6 || k(n) > 1.9 || H(m) > 49
%             continue
%         end
        vs = vp/k(n);        
        for i = 1:size(RF,2) % loop for all receiver functions            
            partP = sqrt(vp^(-2) - rayp(i)^2);
            partS = sqrt(vs^(-2) - rayp(i)^2);
            tPs = H(m)*(partS-partP);
            tPpPs = H(m)*(partP+partS);
            tPpSs = 2*H(m)*partS;
%             if tPs < 5 || tPpPs < 18 || tPpPs > 18.5
%                 continue
%             end
            RFi = RF(:,i);
            r1(n,m) = r1(n,m) + RFi(round((tPs-time(1))/delta) + 1);
            r2(n,m) = r2(n,m) + RFi(round((tPpPs-time(1))/delta) + 1);
            r3(n,m) = r3(n,m) + RFi(round((tPpSs-time(1))/delta) + 1);
        end
    end
end

%     % Hk, r1, r2 should be positive, and r3 should be negative, otherwise
%     % setting them to be zero
%     r1(find(r1<0))=0;
%     r2(find(r2<0))=0;
%     r3(find(r3>0))=0;

Hk = weight(1)*r1 + weight(2)*r2 - weight(3)*r3;

% Hk(find(Hk<0)) = 0;


end
