
      program select
      implicit none

      integer*4 imxrec
      parameter(imxrec=300000)
      character cline(imxrec)*200,filein*50,cc*20,c81*8,c82*8,hd*200,
     &          fout*50
      integer*8 i1,i2,id
      integer*4 j,ifl,n_sel,n_org,il

      call getarg(1,filein)
      call getarg(2,cc)
      read(cc,*) i1
      call getarg(3,cc)
      read(cc,*) i2
      ifl=index(filein,' ')-1

! basic check of the calling command:
      if(ifl.lt.1.OR.i1.lt.20050101.OR.i2.gt.21151231.OR.i2.lt.i1) then
        write(*,*) "Usage:"
        write(*,*) "./select.exe dbfile.txt yyyymmdd YYYYMMDD"
        write(*,*) "where yyyymmdd YYYYMMDD are start and stop dates."
        stop'F-ERR: bad calling arguments !!'
      end if
  
      write(*,*) "Selecting from file: ",filein(1:ifl)
      write(*,*) "Start date: ",i1
      write(*,*) " Stop date: ",i2

      write(c81,'(i8.8)')i1
      write(c82,'(i8.8)')i2
      fout=c81//"_"//c82//"_"//filein(1:ifl)

      open(1,file=filein,status='old')
      read(1,'(a)') hd
      il=index(hd,'   ')
      open(2,file=fout,status='unknown')
      write(2,'(a)') hd(1:200)

      n_org = 0     
      n_sel = 0
      do j=1,imxrec
        read(1,'(a)',end=108)cline(j)
        n_org = n_org + 1
        read(cline(j)(1:8),*) id
        if( (id.GE.i1).AND.(id.le.i2) ) then
          n_sel = n_sel + 1
          il=index(cline(j),'   ')
          write(2,'(a)') cline(j)(1:200)
        end if
      end do ! end loop j=1,imxrec
      stop'F-ERR: imxrec too small !!'

108   close(1)
      close(2)

      write(*,*)"N. of records in the original DB: ",n_org
      write(*,*)"N. of records selected:           ",n_sel
      

      stop'INFO: normal completion.'
      end

       
