clear

jday1 = 1;
jday2 = 1;

iref =  3;

YEAR1 = '2000';
ARRAY1 = 'FNET';

for jday = jday1:jday2

if (jday < 10)
  JJDAY1 = sprintf('00%i',jday);
elseif (jday < 100)
  JJDAY1 = sprintf('0%i',jday);
else
  JJDAY1 = sprintf('%i',jday);
end

fnamein = sprintf('%s.%s.%s.pick1.dat',YEAR1,JJDAY1,ARRAY1);
[YEAR,jjday,ARRAY,mst,time,angle,xT,ifin,afin] = readpick(fnamein);
mstla = mst(1);
mstlo = mst(2);

dT=time(2)-time(1);
tfin=ifin*dT+time(1);
[dumm1,dumm2,gV]=cal_CQU_228(1./xT);

NT = length(xT);
mfin = size(ifin);
k=0;
for i = 1:mfin(1)
    for j = 1:mfin(2)
        if (afin(i,j,3) >= 2.5e-9)
           k = k + 1;
           fin_time(k) = tfin(i,j,3);
           fin_baz(k) = angle(j);
           fin_amp(k) = afin(i,j,3);
        end
          
    end
end

% Select maximum back azimuth. 
[time_sort,isort]=sort(fin_time);
itmax = length(fin_time);
time_sort1 = time_sort;
time_sort1(itmax+1)=time_sort(itmax)+1001;


i11 = 1;
idet = 1;
for ii = 1 : itmax
    itemp1 = time_sort1(ii);
    itemp2 = time_sort1(ii+1);
    if ((itemp2 - itemp1) >= 1000) 
       i12 = ii;
       [dumm,imax]=max(fin_amp(isort(i11:i12)));       
       fin_amp1(idet)=dumm;
       fin_baz1(idet)=fin_baz(isort(i11+imax-1));
       fin_time1(idet)=fin_time(isort(i11+imax-1));
       idet = idet + 1;
%       [i11,i12]
       i11 = i12+1;
    end
end


% Checking if detection has dispersion properties. 

xmaxdet = length(fin_time1);
idetf = 1;

%for ii = 1 : xmaxdet;
for ii = 1 : 1;
ibaz = round(fin_baz1(ii)/(angle(2)-angle(1)))+1;
reft= fin_time1(ii);

if (reft > 0 ) & (reft <= 24*3600)
ixT=zeros(NT,1);
for k = 1 : NT
    iimax = sum(sign(ifin(:,ibaz,k)));
    itempxT = 1;
    for i = 1 : iimax
        temptime = tfin(i,ibaz,k);
       if (temptime >= (reft-1000)) & (temptime <= (reft + 500))
          ixT(k) = ixT(k) + 1;
          ttTEMP(k,itempxT) = tfin(i,ibaz,k);
          atTEMP(k,itempxT) = afin(i,ibaz,k);
          itempxT = itempxT+1;
       end
    end
end

if (sum(sign(ixT)) == NT)
  [dumm,iatmax]=max(atTEMP');
    if (size(atTEMP,2) == 1)
      iatmax = zeros(1,NT);
      iatmax = iatmax + 1;
      dumm = atTEMP';
    end

    for i = 1:NT
      ttime(i) = ttTEMP(i,iatmax(i));
    end

  [otime,dist,qual]=cal_GV_DIST1(ttime,gV,iref);
  fin_otime2(idetf)=otime;
  fin_dist2(idetf)=dist;
  fin_baz2(idetf)=angle(ibaz);
  fin_error2(idetf,:)=qual;
  fin_amp2(idetf,:)=dumm;
  fin_time2(idetf,:)=ttime;
  idetf=idetf+1;
  itTEMP = 0;
  atTEMP = 0;
end % End of if for NT

end % End of if for reft
end
