
! Calcul des coefficients r par la methode de Beylkin
! nouvelle version tenant compte des differentes ondelettes possibles

	subroutine coef_r(rr,L)

	use param_run
        use wavelets_BL
        use wavelets_daub
        use wavelets_daub4
        use wavelets_spline


	implicit none

	integer, parameter :: ni=10
	integer n,i,ll,k,m,L
	real(kind(0d0)) som,rr(-L+2:L-2)
	real(kind(0d0)), dimension (:), allocatable :: h,rh,g,rg,a
	real(kind(0d0)), dimension (:,:), allocatable :: r

! choose the wavelet
        if (wavelet == 'daub4') then
         allocate(h(L),rh(L),g(L),rg(L),a(L-1),r(-L+2:L-2,ni))
         h=h4; rh=rh4; g=g4; rg=rg4
        else if (wavelet == 'daub8') then
         allocate(h(L),rh(L),g(L),rg(L),a(L-1),r(-L+2:L-2,ni))
         h=h8; rh=rh8; g=g8; rg=rg8
        else if (wavelet == 'splines') then
         allocate(h(8),rh(4),g(4),rg(8))
         h=hs; rh=rhs; g=gs; rg=rgs
	 print*,'There may be a problem with splines'
        else if (wavelet == 'lemarie') then
         allocate(h(L),rh(L),g(L),rg(L),a(L-1),r(-L+2:L-2,ni))
         h=h_l; rh=rh_l; g=g_l; rg=rg_l
        else
         stop'in mres2d: no wavelet supplied'
        endif


! 1) calcul des a(2k-1)

	do n=1,L-1,2
	 a(n)=0
	 do i=0,L-1-n
	  a(n)=a(n)+2*rh(i+1)*rh(i+1+n)
	 enddo
	enddo

! 1b) calcul direct des a(2k-1) : gives the same results as above
!
!	forall(i=1:L/2-1) b(i)=real(2*i+1)/2
!	C8=product(b)**2
!	do m=1,L/2
!	 fm=1d0
!	 do i=1,L/2-m
!	  fm=fm*i
!	 enddo
!	 fmp=1d0
!	 do i=1,L/2+m-1
!	  fmp=fmp*i
!	 enddo
!	 aa(2*m-1)=(-1)**(m-1)*C8/fm/fmp/(2*m-1)
!	enddo

! 2) calcul des r_l par methode iterative de Beylkin 1992

	r=0
	r(-1,1)=0.5 ; r(1,1)=-0.5

	do i=2,ni
	 do ll=-L+2,L-2
	  som=0.0
	  do k=1,L/2
	   if (2*ll+2*k-1 < L-1 .and. 2*ll+2*k-1 > -L+1) &
                                   som=som+a(2*k-1)*r(2*ll+2*k-1,i-1)
	   if (2*ll-2*k+1 < L-1 .and. 2*ll-2*k+1 > -L+1) &
                                   som=som+a(2*k-1)*r(2*ll-2*k+1,i-1)
	  enddo
	  r(ll,i)=som
	  if (2*ll < L-1 .and. 2*ll > -L+1) r(ll,i)=som+2*r(2*ll,i-1)
	 enddo
	enddo

! verification

!	forall (i= -L+2:l+2) rr(i)=i*r(i,ni)
!	print*,'check',sum(rr)+1
	rr(:)=r(:,ni)

	deallocate(h,rh,g,rg)
	end
