SUBROUTINE WRITENN(KLEN,KMXCOUNT,PVPOBS,POBS,PRADM,PPS5,PTS5,PLS5,PZEANG,PLAT,PLON,PEM5)
!**********************************************
!*    Neural network bias correction for AIRS *
!**********************************************
USE PARKIND1  ,ONLY : JPIM     ,JPRB
USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK
USE YOMLUN   , ONLY : NULOUT
USE YOMMP    , ONLY : MYPROC
USE YOMNNE   , ONLY : LNNMSKRS 

IMPLICIT NONE

INTEGER(KIND=JPIM),INTENT(IN)    :: KMXCOUNT 
INTEGER(KIND=JPIM),INTENT(IN)    :: KLEN 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PVPOBS(KLEN,KMXCOUNT) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: POBS(KLEN,KMXCOUNT) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PRADM(KLEN,KMXCOUNT) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PPS5(KLEN) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PTS5(KLEN) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PLS5(KLEN) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PZEANG(KLEN) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PLAT(KLEN) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PLON(KLEN) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PEM5(KLEN,KMXCOUNT) 
INTEGER(KIND=JPIM)               :: ICHAN,INBRS,IRS,IPAT,IBCHAN_DUMP,J
REAL(KIND=JPRB), ALLOCATABLE     :: ZLATRS(:),ZLONRS(:)
LOGICAL                          :: LLOLD, LLMSKMISS, LLMSK
CHARACTER                        :: CL_FILE_LEARN*60,CL_FILE_MSKRS*60
CHARACTER                        :: CL_CPROC*2
REAL(KIND=JPRB) :: ZHOOK_HANDLE

IF (LHOOK) CALL DR_HOOK('WRITENN',0,ZHOOK_HANDLE)
WRITE(NULOUT,*)'----> WRITENN'

WRITE(CL_CPROC,'(I2)') MYPROC
CL_FILE_LEARN='nn_learning_file'//TRIM(ADJUSTL(CL_CPROC))
INQUIRE(file=TRIM(CL_FILE_LEARN), exist=LLOLD)
IF (LLOLD) THEN
  OPEN(13,file=CL_FILE_LEARN,form='unformatted',status='old',position='append')
ELSE
  OPEN(13,file=CL_FILE_LEARN,form='unformatted',status='replace')
ENDIF

CL_FILE_MSKRS='AIRS_RS.dat'
INQUIRE(file=TRIM(CL_FILE_MSKRS),exist=LLMSK)
LNNMSKRS = (LNNMSKRS).AND.(LLMSK)
IF (LNNMSKRS) THEN
  OPEN(14,file=CL_FILE_MSKRS,status='old')
  READ(14,*) INBRS
  ALLOCATE(ZLATRS(INBRS)) ; ALLOCATE(ZLONRS(INBRS))
  ZLATRS=0 ; ZLONRS=0
  DO IRS=1,INBRS
    READ(14,*) J,ZLATRS(IRS),ZLONRS(IRS)
  ENDDO
  CLOSE(14)
ENDIF

PATLOOP: DO IPAT=1,KLEN
  IF (LNNMSKRS) THEN
    LLMSKMISS=.TRUE.
    DO IRS=1,INBRS
      IF ((ABS(ZLATRS(IRS)-PLAT(IPAT))<0.001).AND.(ABS(ZLONRS(IRS)-PLON(IPAT))<0.001)) LLMSKMISS=.FALSE.
    ENDDO
    IF (LLMSKMISS) CYCLE PATLOOP
  ENDIF
  WRITE(13) PLAT(IPAT),PLON(IPAT),PPS5(IPAT),PTS5(IPAT),PLS5(IPAT),PZEANG(IPAT)
  IBCHAN_DUMP=0
  DO ICHAN=1,KMXCOUNT
    IF (POBS(IPAT,ICHAN) > 0) IBCHAN_DUMP=IBCHAN_DUMP+1
  ENDDO
  WRITE(13) IBCHAN_DUMP
  DO ICHAN=1,KMXCOUNT
    IF (POBS(IPAT,ICHAN) > 0) &
     & WRITE(13) INT(PVPOBS(IPAT,ICHAN)),&
     & POBS(IPAT,ICHAN),POBS(IPAT,ICHAN)-PRADM(IPAT,ICHAN),&
     & PEM5(IPAT,ICHAN)  
  ENDDO
ENDDO PATLOOP
CLOSE(13)

IF (LNNMSKRS) DEALLOCATE(ZLATRS,ZLONRS)
IF (LHOOK) CALL DR_HOOK('WRITENN',1,ZHOOK_HANDLE)

END SUBROUTINE WRITENN
