function TIME = rfrtim(D,V,DIP,NOL,XDIST)
% COMPUTE REFRACTED (HEAD WAVE) TRAVEL TIMES FOR NOL
% DIPPING LAYERED HALF SPACE AT DISTANCE XDIST . DIP
% IS POSITIVE FOR UPDIP,NEGATIVE FOR DOWN DIP, DIP
% IS GIVEN IN DEGREES.  DIP(I) IS DIP OF LOWER
% INTERFACE FOR LAYER I.  NOTE DIP(NOL) NOT SPECIFIED 
% D(I) IS THICKNESS (MEASURED VERTICALLY) AT ORIGIN 
% XDIST=0.0.  TIME(I) IS FOR REFRACTION (OR DIRECT
% ARRIVAL) ALONG TOP OF LAYER I. 
% Modified from FORTRAN code RFRTIM from TXCURV.
% L. Braile, 2/7/03
N1=NOL-1;
for I = 1:N1				
    DP(I)=DIP(I)*0.017453;
end
[A,B] = angles(V,DP,NOL);
% DIRECT ARRIVAL TIME 
TIME(1)=XDIST/V(1);
% CALCULATE CRITICAL DISTANCE FOR EACH REFRACTOR
XCR(1)=0.0;
for I = 2:NOL
	SUM=0.0;
	SUMA=0.0;
	SUMB=0.0;
	K=I-1;
    for J = 1:K
        NS = 0;
        if (V(J) > V(I))
            NS = 1;
            break
        end
        D2=-SUMA*tan(DP(J)); 
        if (J > 1) 
            D2=D2+SUMA*tan(DP(J-1));
        end
        DEP=D2+D(J);
        XNUM=DEP*tan(A(J,I)+DP(J));
        XDEN=1. + tan(A(J,I)+DP(J))*tan(DP(J));
        SUMA=SUMA+XNUM/XDEN;
end % 210 continue
if NS ~= 1
    for J = 1:K
		D2=-SUMB*tan(DP(J));
        if (J > 1) 
            D2=D2-SUMB*tan(DP(J-1));
        end
        DEP=D2+D(J);
        XNUM=DEP*tan(B(J,I)-DP(J));
        XDEN=1. + tan(B(J,I)-DP(J))*tan(DP(J));
        SUMB=SUMB+XNUM/XDEN;
    end % 211
		SUM=SUMA+SUMB;
        XCR(I) = SUM;
	continue
    else    
	    SUM=-1.0 % 205
end
% -1.0 INDICATE LVL SO NO CRITICAL DISTANCE OR HEAD 
% WAVE PRODUCED 
	    XCR(I)=SUM;
end % 200
for J = 2:NOL
    if ((XDIST <= XCR(J)) | (XCR(J) <= 0.0))
        TIME(J)= NaN; % no refracted arrival at this distance
	continue
    else
		K=J-1;
		SUM=0.0;
        for I = 1:K
            SUM=SUM+D(I)*(cos(A(I,J))+cos(B(I,J)))/V(I);
        end %100
% SUM=INTERCEPT TIME
       TIME(J)=XDIST*sin(B(1,J))/V(1)+SUM;
   end
end % 70
				
