      subroutine ACpatch(trans,nnn,nl,r0,delr,
     .     wavl,vel,fd,fdd,fddd,prf,ht,theta,npfin,
     .     a2,a4,slope,inter,ideskew,na_valid)
      
      integer*4 mmm
      parameter (mmm=6144)
      REAL*4       PI,PI2
      PARAMETER    (PI=3.141592653,PI2=6.2831853072)
      integer nnn,nl,ideskew,npfin,na_valid
      real*4 vel, prf,theta,a2,a4
      real*8 r0, delr,wavl,fd,fdd,fddd, ht,slope,inter
      real*8 r(mmm), phase, az, rd0
      integer*4 n, nfc, nf0
      complex*8 trans(nnn,nl),ctmp,ref(4096)
      real*4 Dm,t, scl
      real*4 a2p, y(mmm),f0(mmm),f_rate(mmm)
      integer*4 firsttime, np(mmm)
      save ref
c      common /tmp/ref(4096,1280)
c      common /tmp/ctmp(4096,1280),ref(4096,1280)
c      data firsttime/1/
c      save IFAX,Twiddle
      
c note: - on y1 because chirp is conjugated below

c both ref and trans are forward transformed and need scaling down

      scl = 1./float(nnn)

      a2p = a2
      if(ideskew .eq. 0) a2p = 0.

      dx = vel/prf
      v1 =wavl**2/(8.*dx**2)
      do i = 1 , nl
         r(i) = r0 + float(i-1)*delr
         f0(i) = fd + fdd*r(i) + fddd*r(i)*r(i)
         rd0 = r(i)/(1 + v1*(f0(i)/prf)**2)
         f_rate(i) = -2.d0 * vel**2*(rd0/r(i))**2/(wavl*r(i))
         f_dum = -2.d0 * vel**2/(wavl*r(i))
c         type *, 'old/new frate ',i, f_dum, f_rate(i)
         np(i) = int(r(i)*a4)/2
         phi = 0.
         if(ht .lt. r(i)) phi = acos(ht/r(i))
         az = slope * r(i) + inter
         y2 = pi2 * az / float(nnn)
         sinsq = wavl*f0(i)/2./vel
         y(i) =  r(i) * a2p * sinsq + y2

c  zero out ref
         do  j = 1, nnn
            ref(j) = cmplx(0.,0.)
         end do
c  create reference function
         phase = pi * f0(i)**2 /f_rate(i)
         ref(1) = cmplx(cos(phase),sin(phase))*scl
         do  j = 1, np(i)
            t = float(j)/prf
            phase = pi * f_rate(i)*t*t + pi2*f0(i)*t
            ref(j+1) = cmplx(cos(phase),sin(phase))*scl
            phase = pi * f_rate(i)*t*t - pi2*f0(i)*t
            ref(-j+nnn+1) = cmplx(cos(phase),sin(phase))*scl
         end do

c  transform the reference
         call cfft1d(nnn,ref,-1)
c  multiply the reference by the data
         n = nint(f0(i)/prf)
         nf0 = nnn*(f0(i)-n*prf)/prf
         nfc = nf0 + nnn/2
         if(nfc .gt. nnn) nfc = nfc - nnn
         phase = - y(i) * nf0
         do k = 1, nfc
            trans(k,i)=trans(k,i)*conjg(ref(k))
     .           *cmplx(cos(phase),sin(phase))
            phase = phase + y(i)
         end do
           
         phase = - y(i) * nf0
         do k = nnn, nfc+1,-1
            trans(k,i)=trans(k,i)*conjg(ref(k))
     .           *cmplx(cos(phase),sin(phase))
            phase = phase - y(i)
         end do
c  inverse transform the product
         call cfft1d(nnn,trans(1,i),1)
      end do

      return
      end



