
      program congap
c
c program to check completeness of continuous data,
c all input is read from congap.par
c
c
c Lars Ottemoller, BGS, July 2008
c

c
c changes:
c

      implicit none 

c
c read SEISAN include files
c
      include 'seidim.inc'   ! dimensions
      include 'seisan.inc'   ! general seisan parameters
      include 'libsei.inc'
      include 'waveform.inc' ! for waveform handling
      include 'rea.inc'      ! for waveform handling
      integer seiclen

      character*80 outfile   ! name of output seisan  waveform file
      character*80 text  
      character*1040 theader ! seisan channel header
      character*80 fheader(max_trace) ! seisan waveform main header
      character*29 headtext
      character*5 net_code   ! code of network
      real duration_min      ! minute
      integer i,j,l,k        ! counter
      integer maxstat,maxtrig
      parameter (maxstat=100)
      character*5 station(maxstat),cbase(maxstat)
      character*4 component(maxstat)
      integer ind
      double precision msec_start,msec_stop,msec,trigger_msec,msec1
      character*14 stop_time,start_time,time
      integer year1,month1,day1,hour1,min1,isec1,doy1
      integer year2,month2,day2,hour2,min2,isec2,doy2
      real sec1,sec2
      integer write1,write2,write3,read1
      logical b_flag
      integer code
      integer nchan,nbase
      integer narg
      character*80 arg(40)
      real rate
      integer nz,nzt
      logical gap_flag
      real expected_time(max_trace)
      real actual_time(max_trace),atime

c
c   get seisan defaults including names of continuous waveform data bases
c
      call get_seisan_def 
c
c get arguments
c
      call get_arguments(narg,arg)
      do j=1,narg
        if (arg(j).eq.'-start') then   
          start_time=arg(j+1)
        elseif (arg(j).eq.'-stop') then   
          stop_time=arg(j+1)
        elseif (arg(j).eq.'-cbase') then
          cbase(1)=arg(j+1)
          nbase=1
        elseif (arg(j).eq.'-interval') then
           call sei get values(1,arg(j+1), code )
           duration_min=array$(1)
        endif
      enddo
      if (narg.lt.8) 
     &call get_contdet_def(nbase,cbase,start_time,stop_time,
     &   duration_min)

c
c open files
c
      call sei open( unknown$,          ! Open old file.
     &               ' ',               ! No prompt.
     &               'congap.out',    ! This filename.
     &               write1,            ! On this unit.
     &               b_flag,            ! Existance?.
     &               code )             ! Returned consition (n/a)

c
c init variables 
c
      if (cbase(1).eq.' ') then
        write(*,*) ' Name of continuous database '
        read(5,'(a)') cbase(1)
      endif

      if (start_time.eq.' ') then
        write(*,*) ' Start time (yyyymmdd...) '
        read(5,'(a)') start_time
      endif

      if (stop_time.eq.' ') then
        write(*,*) ' Stop time (yyyymmdd...) '
        read(5,'(a)') stop_time
      endif

      if (duration_min.eq.0.) then
        write(*,*) ' Duration in min '
        read(5,*) duration_min
      endif

      if (station(1).eq.' ') then
        write(*,*) ' Station '
        read(5,'(a)') station(1)
      endif

      if (component(1).eq.' ') then
        write(*,*) ' Component '
        read(5,'(a)') component(1)
      endif

      write(*,*) ' start time: ',start_time
      write(*,*) ' stop time:  ',stop_time

      do i=1,max_trace
        expected_time(i)=0.
        actual_time(i)=0.
      enddo
c
c loop over stations
c
      nchan=0
      do k=1,nbase
c
c init
c
        cont_base(1)=cbase(k)
        n_cont_trace=0

        write(*,*) ' Database: ',cbase(k)

c
c  signal that reading is from a continous data base
c
        cwav=.true.
        n_cont_base=1
c
c   calculate end time and extended start time, needed in order to
c   make sure enough files read in
c
        cwav_start_time=start_time

        read(start_time,'(i4,5i2)') year1,month1,day1,hour1,min1,isec1
        sec1=float(isec1)
        call timsec(year1,month1,day1,hour1,min1,sec1,msec_start)

c 
c compute overall endtime
c
        read(stop_time,'(i4,5i2)') year2,month2,day2,hour2,min2,isec2
        sec2=float(isec2)
        call timsec(year2,month2,day2,hour2,min2,sec2,msec_stop)

c
c set initial values
c
        call cwav_time_limits(0)
        cwav_abs_start_time=msec_start
        cont_interval=duration_min*60.

        do while(cwav_abs_start_time.lt.msec_stop)

c
c set end of interval to be read
c
          call cwav_time_limits(1)
c
c  read the header information for all files in bases in time
c  interval, assume info available in common block
c
          cwav_abs_end_time=cwav_abs_start_time+cont_interval
          call cwav_read_bases     

          call sectim(cwav_abs_start_time,year1,doy1,month1,day1,hour1,
     &    min1,sec1)
          call sectim(cwav_abs_end_time,year2,doy2,month2,day2,hour2,
     &    min2,sec2)
          write(*,'(a,i4,"/",i2,"/",i2," ",i2,":",i2,":",f5.2)')
     &    ' start time: ',year1,month1,day1,hour1,min1,sec1
          write(*,'(a,i4,"/",i2,"/",i2," ",i2,":",i2,":",f5.2)')
     &    ' stop time:  ',year2,month2,day2,hour2,min2,sec2
c
c find channel index
c
          do i=1,n_cont_trace
            ind=0
            do j=1,nchan
              if (cwav_stat(i).eq.station(j).and.
     &            cwav_comp(i).eq.component(j)) 
     &        then
                ind=j
              endif
            enddo
c new channel
            if (ind.eq.0) then
              nchan=nchan+1
              ind=nchan
              station(nchan)=cwav_stat(i)
              component(nchan)=cwav_comp(i)
            endif
c
c count expected time
c
            expected_time(ind)=expected_time(ind)+cont_interval 

c
c  read the waveform data, one trace at a time
c
            call wav_read_channel(i)    ! read trace

c            wav_nsamp(i)=wav_nsamp(i)-1  ! removed 12/08/2008
            rate = wav_rate(i)
            if (wav_nsamp(i).lt.0) then
              wav_nsamp(i)=0
            endif
c
c check for gap, which has constant level for more than 1 s
c
            gap_flag=.false.
            nz=0
            nzt=0
            do j=2,wav_nsamp(i)
              if (signal1(j).eq.signal1(j-1)) then
                nz=nz+1
c                if (.not.gap_flag) then
c                  write(*,*) ' gap, start sample ',j
c                  write(*,*) signal1(j),signal1(j-1)
c                endif
                gap_flag=.true.
              else
                if (gap_flag) then
                  if (float(nz)/rate.gt.1.) then
                    nzt=nzt+nz+1
                    write(*,*) ' gap, end sample  ',j,nz
                  endif
                endif
                nz=0
                gap_flag=.false.
              endif
            enddo

c            rate = cwav_rate(i,cwav_nseg(i))

            write(*,*) ' channel number: ',i
            write(*,*) ' total samples: ',wav_nsamp(i)
            write(*,*) ' sampling rate: ',rate
            write(*,*) ' duration: ',float(wav_nsamp(i))/
     &                               rate
            write(*,*) ' gap duration: ',float(nzt)/rate
            atime=float(wav_nsamp(i)-nzt)/rate
            actual_time(ind)=actual_time(ind)+atime
             write(write1,
     &       '(a5,1x,a3,1x,i4,2i2.2,1x,2i2.2,f5.2,1x,f9.2,1x,f9.2)')
     &        station(ind),component(ind)(1:2)//component(ind)(4:4),
     &        year1,month1,day1,hour1,min1,sec1,atime,cont_interval
          enddo ! loop over traces
c
c set start of next interval to read
c
          cwav_abs_start_time=cwav_abs_end_time
        enddo ! loop over time
      enddo ! end of loop over stations

      write(*,'(a)') ' -------------------------------------------- '
      write(*,'(a)') '  # stat comp       actual     expected     % '
      write(*,'(a)') ' -------------------------------------------- '
      do i=1,nchan
        write(*,'(i3,1x,a5,1x,a3,1x,f12.2,1x,f12.2,1x,f5.1)') 
     &      i,station(i),
     &      component(i)(1:2)//component(i)(4:4),
     &      actual_time(i),expected_time(i),
     &      actual_time(i)/expected_time(i)*100.
      enddo
      write(*,'(a)') ' -------------------------------------------- '
c
c close files
c
      call sei close( close$, write1, code )

      stop
      end

      subroutine get_contdet_def(nbase,cbase,startdate,stopdate,
     &   duration)

      implicit none
      include 'libsei.inc'
      include 'seidim.inc'

      character*80 def_file         ! file names
      integer in                    ! file unit
      integer code                  ! return code from opening def file
      integer i                     ! counter
      character*80 line             ! text line
      real var                      ! value of variables
      integer nbase                 ! station counter
      integer seiclen

      character*(*) cbase(*),startdate,stopdate
      real duration
   
c
c check for file end open
c

      def_file = 'congap.par'

      call sei get file( open$+ignore$,   ! Open waveform file.
     &                   in,              ! On unit.
     &                   code,            ! Returned condition.
     &                   'DAT',           ! Alternative search directory.
     &                   def_file )       ! For this filename.

      if(code.ne.e_ok$) then
        write(*,*) ' definition file does not exist: congap.par'
        stop
      endif
c
c init values
c
      cbase(1)=' '
      startdate=' '
      stopdate=' '
      duration=60.
      nbase=0  ! station counter


100   continue

c
c read text line from file, check for code and set variables
c
      read(in,'(a)',end=300,err=200) line

      if (line(1:10).eq.'START DATE') then
        read(line(41:54),'(a)') startdate
      elseif (line(1:9).eq.'STOP DATE') then
        read(line(41:54),'(a)') stopdate
      elseif (line(1:9).eq.'CONT BASE') then
        nbase=nbase+1
        read(line(41:45),'(a)') cbase(nbase)
      elseif (line(1:8).eq.'INTERVAL') then
        read(line(41:50),'(f10.1)') var
        if (var.gt.0.) duration=var
      endif

      goto 100

200   continue
      write(*,*) ' Error in congap.par file'

300   continue
      call sei close( close$, in, code )

      return
      end

