      SUBROUTINE MEM_FUNC_EX1_REV
!      INCLUDE 'mkl.fi'
      USE MKL_SPBLAS
      INTEGER    N, I
      PARAMETER (N = 1000)
      DOUBLE PRECISION     A,B,C
      POINTER    (A_PTR,A(N*N)), (B_PTR,B(N*N)), (C_PTR,C(N*N))
        
      REAL*8     ALPHA, BETA
      INTEGER*8  ALLOCATED_BYTES
      INTEGER*8  PEAK_MEMORY
      INTEGER*4  ALLOCATED_BUFFERS
!#ifdef _SYSTEM_BITS32
!        INTEGER*4 MKL_MALLOC, MKL_CALLOC, MKL_REALLOC
!        INTEGER*4 ALLOC_SIZE, NUM, SIZE
!#else
        INTEGER*8 MKL_MALLOC, MKL_CALLOC, MKL_REALLOC
        INTEGER*8 ALLOC_SIZE, NUM, SIZE
!#endif
      EXTERNAL   MKL_MALLOC, MKL_FREE, MKL_CALLOC, MKL_REALLOC
        
      ALPHA = 1.1; BETA = -1.2
!      N = 1000
      SIZE = 8
      NUM = N*N
      ALLOC_SIZE = SIZE*NUM
      PEAK_MEMORY = MKL_PEAK_MEM_USAGE(MKL_PEAK_MEM_ENABLE)
      A_PTR = MKL_MALLOC(ALLOC_SIZE,64)
      B_PTR = MKL_MALLOC(ALLOC_SIZE,64)
      C_PTR = MKL_CALLOC(NUM,SIZE,64)
      DO I=1,N*N
        A(I) = I
        B(I) = -I
      END DO
 
      CALL DGEMM('N','N',N,N,N,ALPHA,A,N,B,N,BETA,C,N);
 
      ALLOCATED_BYTES = MKL_MEM_STAT(ALLOCATED_BUFFERS)
      PRINT *,'DGEMM uses ',ALLOCATED_BYTES,' bytes in ',   &
       ALLOCATED_BUFFERS,' buffers '
 
      CALL MKL_FREE_BUFFERS
      CALL MKL_FREE(A_PTR)
      CALL MKL_FREE(B_PTR)
      CALL MKL_FREE(C_PTR)

      ALLOCATED_BYTES = MKL_MEM_STAT(ALLOCATED_BUFFERS)
      IF (ALLOCATED_BYTES > 0) THEN
       PRINT *,'MKL MEMORY LEAK!'
       PRINT *,'AFTER MKL_FREE_BUFFERS there are ',   &
         ALLOCATED_BYTES,' bytes in ',   &
         ALLOCATED_BUFFERS,' buffers'
      END IF

      PEAK_MEMORY = MKL_PEAK_MEM_USAGE(MKL_PEAK_MEM_RESET)
      PRINT *,'Peak memory allocated by Intel MKL memory allocator ',   &
       PEAK_MEMORY,' bytes. ',   &
       'Start to count new memory peak'

      A_PTR = MKL_MALLOC(ALLOC_SIZE,64)
      A_PTR = MKL_REALLOC(A_PTR,ALLOC_SIZE*SIZE)
      CALL MKL_FREE(A_PTR)
      PEAK_MEMORY = MKL_PEAK_MEM_USAGE(MKL_PEAK_MEM)
      PRINT *,'After reset of peak memory counter',   &
       'Peak memory allocated by Intel MKL memory allocator ',   &
       PEAK_MEMORY,' bytes'

      STOP
      END