SUBROUTINE TJQUAA (PAB,PZTOR,K,POI,PCF,PVAR,PEPS)

!**** *TJQUAA*  - POST-PROCESSING FOR AERONAUTICS

!     PURPOSE.
!     --------
!        To post-process jet and ICAO tropopause
!         SUBROUTINE PERFORMING THE LEAST SQUARE ADJUSTMENT
!         OF A QUADRATIC FUNCTION
!         FOR L POINTS DEFINED BY THE VECTOR PAB(K) OF THE ABCISSAS
!         ET LE VECTOR PZTOR(K) DES ORDINATES.
!         WE CAN INTRODUCE A WEIGHTING DEPENDING ON THE POINTS
!         THANKS TO THE VECTOR POI(K).
!         PCF(3) GIVES THE THREE COEFFICIENTS OF THE QUADRATIC FUNCTION:
!         Y=C(3)*X**2+PCF(2)*X+PCF(1)
!         PVAR EST LE REMAINING PART OF THE SUMMATION OF THE SQUARES
!         OBTAINED WITH THE SOLUTIONS

!**   INTERFACE.
!     ----------
!       *CALL* *TJQUAA*

!        EXPLICIT ARGUMENTS
!        --------------------
!               INPUT :
!               ------

!               OUTPUT :
!               ------

!        IMPLICIT ARGUMENTS
!        --------------------

!     METHOD.
!     -------
!        SEE DOCUMENTATION

!     EXTERNALS.
!     ----------

!     REFERENCE.
!     ----------
!        ECMWF Research Department documentation of the IFS

!     AUTHOR.
!     -------
!        F. Autones and V. Martin *METEO-FRANCE*

!     MODIFICATIONS.
!     --------------
!        ORIGINAL : 89-03-01
!        Modified : 93-01-01 J.-Marie Carriere
!        Modified : 94-11-01 X. RAGOT, R. El Khatib (adaptation to ARPEGE/IFS)
!        M.Hamrud      01-Oct-2003 CY28 Cleaning
!        M.Hamrud      01-Dec-2003 CY28R1 Cleaning
!     ------------------------------------------------------------------

USE PARKIND1  ,ONLY : JPIM     ,JPRB
USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK

IMPLICIT NONE

INTEGER(KIND=JPIM),INTENT(IN)    :: K 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PAB(K) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PZTOR(K) 
REAL(KIND=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