program rms2int
  use sep
  use vrms2int_new
	use bin1

  implicit none
  integer                          :: i1, i2, n1, n2, niter, iprec, stat
  real                             :: eps
  real, dimension (:), allocatable :: vint, vrms
  real, dimension (:), pointer     :: weight, err, res, mrefl

  call sep_init ()
  call from_history (n1)
  call from_either ("n2",n2,1)

  call from_par ("niter",niter,20)
  call from_par ("eps",eps,1.)
  call from_par ("prec",iprec,1)

  call to_history ("title","Interval velocity")
  call to_history ("n1",n1)
  call to_history ("n1",n1,"vrms")
  call to_history ("title","RMS velocity","vrms")
  call to_history ("esize",4,"vrms")
  if( exist_file("err") ) call to_history ("n1",niter,"err")
  if( exist_file("res") ) then
		call to_history ("n1",n1,"res")
		call to_history ("n2",1,"res")
	end if


  allocate( vint(n1), vrms(n1), weight(n1), err(niter), res(n1), mrefl(n1) )

	vint = 0; weight=0; err=0; res=0; mrefl=0

  do i2= 1, n2 
     call sep_read (vrms); vrms = 1./vrms
     mrefl=0;
     if(exist_file("refl"))  call sep_read( mrefl, file="refl")
     weight=1;
     if(exist_file("weight")) call sep_read (weight, file="weight")

     call vrms2int( niter, eps, weight, mrefl, vrms, vint, (iprec==1), err, res )

     vint = 1./vint; call sep_write (vint) 
     if( exist_file("vrms")) call sep_write( vrms, "vrms")
     if( exist_file("err") ) call sep_write( err, "err")
     if( exist_file("res") ) call sep_write( res, "res")
  end do

  call sep_close ()

  deallocate (vint, vrms, weight, err, res, mrefl)
  call exit (0)


end program rms2int

