program wavmetric

   implicit none

   integer, parameter                 :: samplerate  = 44100
   integer, parameter                 :: frameps     = 30

   integer                            :: smplpframe, frame

   integer, allocatable               :: bufleft(:), bufright(:)


   write (0, *) "------ wave metrics ------"
   smplpframe = samplerate / frameps
   write (0, *) "samples per frame = ", smplpframe

   allocate( bufleft  (smplpframe) )
   allocate( bufright (smplpframe) )

   do frame=0, 1130
      call compute_a_frame(frame, smplpframe)
   enddo 
contains

! --------------------------------------------------------------------

subroutine compute_a_frame(numf, nbsmpl)

   integer, intent(in)               :: numf, nbsmpl
   integer                           :: foo, left, right
   integer                           :: l_zxc, r_zxc

   ! write(0, *) "compute frame", numf

   ! load values in work buffer
   do foo=1, nbsmpl
      read(*, *) left, right
      bufleft  (foo) = left
      bufright (foo) = right
      ! write(0, *) "   ", foo, left, right
    enddo

   ! compute frequencies
   l_zxc = 0 ; r_zxc = 0
   do foo=2, nbsmpl
      if ( diff_sign(bufleft(foo-1),  bufleft(foo)) ) then
         l_zxc = l_zxc + 1
      endif
      if ( diff_sign(bufright(foo-1), bufright(foo)) ) then
         r_zxc = r_zxc + 1
      endif
      ! write(0, *) foo, bufleft(foo), l_zxc
   enddo

   print *, numf,  l_zxc, r_zxc  

end subroutine

! --------------------------------------------------------------------

logical function diff_sign(a, b)
   integer, intent(in)     :: a, b

   ! write(0, *) "diff_sign", a, b
   if ( (a .lt. 0) .and. (b .ge. 0) ) then 
      diff_sign = .TRUE.
      return
   endif
   if ( (a .ge. 0) .and. (b .lt. 0) ) then
      diff_sign = .TRUE.
      return
   endif
   diff_sign = .FALSE.

end function

! --------------------------------------------------------------------

end program wavmetric