function [fintime1,finamp1,finbaz1] = ...
          cal_pick(time,maxamp,maxbaz,amp_fac,amp_cre)

mm0 = size(maxamp);

ii=1;
for i =1 : mm0(1)-2;
    amp1 = maxamp(i);
    amp2 = maxamp(i+1);
    amp3 = maxamp(i+2);
    amp12 = amp1 - amp2;
    amp23 = amp2 - amp3;
    amp4 = amp12 * amp23;
    if (amp4 < 0) 
       finamp(ii)=maxamp(i+1);
       fintime(ii)=time(i+1);
       finbaz(ii)=maxbaz(i+1);
       ii = ii + 1;
    end  
end


mm = size(finamp);

isign = 0;
ii = 1;
tmax0=max(finamp(1),finamp(2));
tmin0=min(finamp(1),finamp(2));
tmax3=tmax0-0.1*(tmax0-tmin0);
tmin3=tmin0+0.1*(tmax0-tmin0);

isign = 0;
i=1;
while (i < mm(2)-1)

% initialization.

amp1 = finamp(i);
amp2 = finamp(i+1);
amp12 = amp1 - amp2;


tmax1 = max(amp1,amp2);
tmin1 = min(amp1,amp2);
tmax2 = max(tmax0,tmax1);
tmin2 = min(tmin0,tmin1);

if isign == 0;

if (tmax2 > amp_fac*tmin2) 
   n=i+1;
   [dumm,imax]=max(finamp(1:n));
   [dumm,imin]=min(finamp(1:n));
   if (imax > imin) % increase
       isign = 1; % pick minimum.
       icand = imin;
       tmax3 = finamp(imin);
       tmax0 = 0;
       tmin0 = 1;
   else
       isign = -1; % pick maximum.
       icand = imax;
       tmin3 = finamp(imax);
       tmax0 = 0;
       tmin0 = 1;
   end
i=i-1;
end

tmax0 = tmax2;
tmin0 = tmin0;

else
% Start main picking.

if (amp12 < 0) % increasing. 
   if (tmax2 > tmax3) & (isign == -1) % find another max.
      icand = i+1;
      tmax3 = finamp(icand);
      tmin2 = 1;
   end

   if (tmax2 > amp_fac*tmin2) & (isign == 1) % find next maximum.
      finamp0(ii) = finamp(icand);
      fintime0(ii) = fintime(icand);
      finbaz0(ii) = finbaz(icand);
      tmax3 = finamp(i+1);
      tmin3 = 0;
      tmax0 = 0;
      tmin0 = 1;
      tmax2 = 0;
      ii = ii + 1;
      isign = -1;
      icand = i + 1;
   else
      tmax0 = tmax2;
      tmin0 = tmin2;
   end

else % decreasing.

   if (tmin2 < tmin3) & (isign == 1) % find another min.
      icand = i + 1;
      tmin3 = finamp(icand);
      tmax2 = 0;
   end

   if (tmax2 > amp_fac*tmin2) & (isign == -1) % find next minimum.
      finamp0(ii) = finamp(icand);
      fintime0(ii) = fintime(icand);
      finbaz0(ii) = finbaz(icand);
      tmin3 = finamp(i+1);
      tmax3 = 0;
      tmax0 = 0;
      tmin0 = 1;
      tmin2 = 1;
      ii = ii + 1;
      isign = 1;
      icand = i+1;
   else
      tmax0 = tmax2;
      tmin0 = tmin2;
   end
end
end
i=i+1;
end

mm = size(finamp0);
jj = 1;
for j = 1 : mm(2)-2;
    tamp1 = finamp0(j);
    tamp2 = finamp0(j+1);
    tamp3 = finamp0(j+2);
    tamp12 = tamp1 - tamp2;
    tamp23 = tamp2 - tamp3;
    if (tamp12 < 0) & (tamp23 > 0)
       if (tamp2 > amp_cre)
          fintime1(jj)=fintime0(j+1);
          finamp1(jj)=finamp0(j+1);
          finbaz1(jj)=finbaz0(j+1);
          jj = jj + 1;
       end
    end
end

