SUBROUTINE initomp(time)
!  Purpose:
!    This subroutine initializes the values of ITASK that will be used
!    throughout execution to determine array indexes. It works for
!    serial runs as well.
!  Usage:
!    time==1     => allocate and compute itask
!    time==0     => deallocate itask
!    time!={0,1} => error
USE params ; USE ubuf
#ifndef _OPENMP
USE my_omp
#endif
IMPLICIT NONE

INTEGER :: time
INTEGER :: ijs, ijl, ijss, ijll, ijsst, ijllt, jtask, nn, k, ij
#ifdef _OPENMP
INTEGER           :: omp_get_max_threads
#endif

IF( 1 .EQ. time ) THEN
!NIKOS Iff OpenMP extensions are enabled at compile time, set NPROCS equal
!      to the number of available threads.
!      Otherwise set it to 1 (==serial run)
!$OMP PARALLEL
!$OMP MASTER
   nprocs = omp_get_max_threads()
!$OMP END MASTER
!$OMP END PARALLEL
   ALLOCATE(itask(4,nprocs))

   ijs = 1
   ijl = niblo
   nn = ( (ijl - ijs + 1) + nprocs - 1) / nprocs
   ijll = ijs - 1
   DO jtask = 1, nprocs
      ijss = ijll + 1
      ijll = MIN(ijll + nn, IJL)
      ijsst = ijss
      ijllt = ijll
      DO k = 1, 2
         DO ij = ijss, ijll
            IF(klat(ij,k) .gt. 0) THEN
               ijsst = MIN(ijsst, klat(ij,k) )
               ijllt = MAX(ijllt, klat(ij,k) )
            ENDIF
            IF(klon(ij,k) .gt. 0) THEN
               ijsst = MIN(ijsst, klon(ij,k) )
               ijllt = MAX(ijllt, klon(ij,k) )
            ENDIF
         ENDDO
      ENDDO
      itask(1,jtask) = ijss
      itask(2,jtask) = ijll
      itask(3,jtask) = ijsst
      itask(4,jtask) = ijllt
      PRINT*, jtask, ' MULTITASK AREA: ', ijss, ijll
      PRINT*, jtask, '     ijsst: ', ijsst,'ijllt:', ijllt
   ENDDO
ELSE IF( 0 .EQ. time ) THEN
   DEALLOCATE(itask)
ELSE
   PRINT*,'ERROR: WRONG ARGUMENT PASSED TO initomp.'
   PRINT*,'Parallel or serial variables were not set, so ABORTING.'
   CALL ABORT
ENDIF

RETURN
END SUBROUTINE initomp
