SUBROUTINE CONGRAD_AD(YDSENS,kmaxit,kiter,pwork,YDCGLWK)

!     Purpose.
!     --------
!       Multiply vector by adjoint of estimated Hessian.

!     Author.
!     -------
!       Yannick Tremolet

!     Modifications.
!     --------------
!       Original : 08-02-22
! ---------------------------------------------------------------------

USE PARKIND1,ONLY: JPRB, JPIM
USE YOMHOOK, ONLY: LHOOK, DR_HOOK
USE YOMCVA , ONLY: YSCALPSQRT, YRSCALPSQRT
USE YOMVAR , ONLY: LMPCGL
USE CONTROL_VECTORS

IMPLICIT NONE
TYPE(CONTROL_VECTOR), INTENT(INOUT) :: YDSENS
INTEGER(KIND=JPIM), INTENT(IN) :: kmaxit,kiter
REAL(KIND=JPRB), INTENT(IN) :: pwork(kmaxit+1,4)
TYPE(CONTROL_VECTOR), INTENT(IN) :: YDCGLWK(kmaxit+1)

REAL(KIND=JPRB) :: zaa(kiter)
INTEGER(KIND=JPIM) :: ji,jj
REAL(KIND=JPRB) :: ZHOOK_HANDLE

#include "precond.intfb.h"

! ---------------------------------------------------------------------

IF (LHOOK) CALL DR_HOOK('CONGRAD_AD',0,ZHOOK_HANDLE)

!$OMP PARALLEL DO SCHEDULE(STATIC) PRIVATE(jj)
DO jj=1,YDSENS%nsizel
  YDSENS%data(jj) = YDSENS%data(jj)*YSCALPSQRT%data(jj)
ENDDO
!$OMP END PARALLEL DO

if (LMPCGL) call precond(YDSENS,-2)

zaa=0.0_JPRB
do jj=1,kiter
  zaa(jj)=dot_product(YDSENS,YDCGLWK(jj))
enddo
do jj=2,kiter
  zaa(jj)=zaa(jj)-pwork(jj,2)*zaa(jj-1)
enddo
zaa(kiter)=zaa(kiter)/pwork(kiter,1)
do jj=kiter-1,1,-1
  zaa(jj)=zaa(jj)/pwork(jj,1) - zaa(jj+1)*pwork(jj+1,2)
enddo

YDSENS=0.0_JPRB

do ji=1,kiter
!$OMP PARALLEL DO SCHEDULE(STATIC) PRIVATE(jj)
  do jj=1,YDSENS%nsizel
    YDSENS%data(jj) = YDSENS%data(jj) + zaa(ji) * YDCGLWK(ji)%data(jj)
  enddo
!$OMP END PARALLEL DO
enddo

if (LMPCGL) call precond(YDSENS,-2)

!$OMP PARALLEL DO SCHEDULE(STATIC) PRIVATE(jj)
DO jj=1,YDSENS%nsizel
  YDSENS%data(jj) = YDSENS%data(jj)*YRSCALPSQRT%data(jj)
ENDDO
!$OMP END PARALLEL DO

IF (LHOOK) CALL DR_HOOK('CONGRAD_AD',1,ZHOOK_HANDLE)
END SUBROUTINE CONGRAD_AD
