program PickOnAmp
use sep
implicit none

integer:: nt,n1,n2,n3,i1,i2,i3,it,t2,t1,f
real::o1,ot,d1,dt,t,m,m2,o2,d2,fx,ft,bt,st,tt,st1
real,allocatable,dimension(:,:):: data,panel
real,allocatable,dimension(:):: time
logical::check,muterite,panelrite

muterite=.false.;panelrite=.false.
call sep_init()
call from_history("n1",n1)
call from_history("n2",n2)
call from_history("n3",n3)
call from_history("d1",d1)
call from_history("o1",o1)
call from_history("o2",o2)
call from_history("d2",d2)
if(exist_file('panel')) then
   panelrite=.true.
   call from_param("ot",ot,0.)
   call from_param("nt",nt,512)
   call from_param("dt",dt,0.004)
   call to_history('o1',ot,'panel')
   call to_history('n1',nt,'panel')
   call to_history('d1',dt,'panel')
   call to_history('esize',4,'panel')
   call to_history('o2',o2,'panel')
   call to_history('n2',n2,'panel')
   call to_history('d2',d2,'panel')
   allocate(panel(nt,n2))
end if

call to_history("n1",n2)
call to_history("d1",d2)
call to_history("o1",o2)
call to_history("n2",n3)

call from_param('mint',st,0.)
call from_param('mintx0',st1,0.)
call from_param('firstT',bt,0.)
call from_param('maxt',ft,o1+(n1-1)*d1)

call from_param('maxx',fx,o2+(n2-1)*d2)
call from_param('check',check,.true.)
if(exist_file('mute')) then
   call to_history('n1',n1,'mute')
   call to_history('n2',n2,'mute')
   call to_history('n3',n3,'mute')
   call to_history('d1',d1,'mute')
   call to_history('d2',d2,'mute')
   call to_history('o1',o1,'mute')
   call to_history('o2',o2,'mute')
   muterite=.true.
end if

fx=fx-o2
ft=ft-bt
m=ft/fx

call sep_close()
allocate(data(n1,n2),time(n2))

do i3=1,n3
   call sep_read(data)
   data=data*data
   time(1)=bt
!write(0,*) 'firstT',bt,time(1)
   do i2=2,n2
      ! lower mute
      t1=1.5 + (-o1+bt+(i2-1)*d2*m)/d1
      t1=min(n1,t1)
      do i1=t1,n1
         data(i1,i2)=0
      end do
      !upper mute
      if (st.gt.0)then
         if(bt.gt.0)tt=st1
         ft=st-tt
         m2=ft/fx
         t2=1.5 + (-o1+tt+(i2-1)*d2*m2)/d1
         f=1.5+ (bt-o1)/d1 -2
         t2=max(1,t2,f)
         do i1=1,t2
            data(i1,i2)=0
         end do
      end if
      !find energy
      it=maxloc(data(:,i2),DIM=1)
!      it=maxloc(data(t2:t1,i2),DIM=1)
      time(i2)=o1+(it-1)*d1

      if(check.and.abs(time(i2) - time(i2-1)).gt.d1*2) then
         time(i2)=time(i2-1)+d1
      end if
   end do

   if (panelrite) then
!write(0,*)' panelrite', nt,ot,dt
      do i2=1,n2
         it=1.5+ (time(i2)-ot)/dt
         panel(it,i2)=1.
      end do
      call sep_write(panel,'panel')
   end if
   if (muterite) call sep_write(data,'mute')
   call sep_write(time)
end do
end program PickOnAmp
