function [error,torigin] = ...
         cal_errorinlo(stla,stlo,time,baz,evla,evlo,trefgvel)

% function designed to calculate error by comparing difference in time and 
% back azimuth.
% Preferred norm is selected by referring to Kennett(1996)
% Update; Normaization for epicentral distance. (08/27/2003)

Erad = 6371;

% Calculate origintime. (time is matched with julian days)
tmpepi(1) = cal_epi1(stla(1),stlo(1),evla,evlo);
dtorigin = tmpepi(1)*Erad*pi/180/trefgvel;
torigin = time(1)-dtorigin/(24*3600);


% Epicentral distance from observed time.
obsepi(1)=tmpepi(1)*Erad*pi/180;
obsepi(2)=(time(2)-torigin)*24*3600*trefgvel;
obsepi(3)=(time(3)-torigin)*24*3600*trefgvel;

% Epicentral distances from trial epicenter.

tmpepi(2)=cal_epi1(stla(2),stlo(2),evla,evlo);
tmpepi(3)=cal_epi1(stla(3),stlo(3),evla,evlo);
tmpepi=tmpepi.*Erad*pi/180;

% Back azimuths from trial epicenter.
tmpbaz(1)=cal_baz(stla(1),stlo(1),evla,evlo);
tmpbaz(2)=cal_baz(stla(2),stlo(2),evla,evlo);
tmpbaz(3)=cal_baz(stla(3),stlo(3),evla,evlo);

% Calculate Error by combining difference in epicenter and backazimuth.

alpha = 0.1;
n=3;
errepi=(1-alpha).*(obsepi'-tmpepi').^2./n;

tempin=zeros(size(baz,2),3);
out = zeros(size(baz,2),1);
tempin(:,1) = tmpbaz'-baz';
tempin(:,2) = -(tmpbaz'+360-baz');
tempin(:,3) = baz'+360-tmpbaz';

[dumm,imin]=min(abs(tempin'));

for k=1:size(baz,2)
out(k,1)=tempin(k,imin(k));
end


errbaz=alpha.*(out.*pi/180.*tmpepi').^2./n;
error=real(sum(sqrt((errepi+errbaz)).^(1.25)));
