function [evla2,evlo2,error,torigin]=cal_loc1(stla,stlo,time,baz,refgvel)

% cal_loc; calculate location by using three arrival times and back azimuths.
%     Reference array is automatically determined by using arrival times.
%     2nd far array from the source is selected as a reference array.
% Usage; [eve_loc,error]=cal_loc(stla,stlo,time,baz,refgvel)

error = 0;

% defining initial points for location.


inilat = -90:10:90;
inilon = -180:10:180;

len1=length(inilat);
len2=length(inilon);

for i = 1:len1
    for j = 1:len2
        potini((i-1)+j,1)=inilat(i);
        potini((i-1)+j,2)=inilon(j);

    end
end


len_ini = size(potini);

for i = 1 : len_ini(1)
    ini_error(i) = ...
    cal_errorinloc1(stla,stlo,time,baz,potini(i,1),potini(i,2),refgvel);
end

[dumm,imin0] = min(ini_error');
evla0 = potini(imin0,1)
evlo0 = potini(imin0,2)

[potpos] = cal_potpos(evla0,evlo0,30);

len_pot = size(potpos);

for j = 1 : len_pot(1)
    tmp_error(j) = ...
    cal_errorinloc1(stla,stlo,time,baz,potpos(j,1),potpos(j,2),refgvel);
end

[dumm,imin1] = min(tmp_error');
evla1 = potpos(imin1,1);
evlo1 = potpos(imin1,2);

[potpos1] = cal_potpos(evla1,evlo1,15);

len_pot = size(potpos1);

for j = 1 : len_pot(1)
    [tmp_error1(j),totemp(j)] = ...
    cal_errorinloc1(stla,stlo,time,baz,potpos1(j,1),potpos1(j,2),refgvel);
end

[dumm,imin1] = min(tmp_error1');
evla2 = potpos1(imin1,1);
evlo2 = potpos1(imin1,2);
error = dumm;
torigin = totemp(imin1);
