!2345678901234567890123456789012345678901234567890123456789012345678901234567890
!    &                                                                  &

	MODULE  chunkModule

          IMPLICIT NONE

          TYPE  chunk_type
            INTEGER height
            INTEGER width
            REAL(KIND=8) temperature(100,12)
          END TYPE chunk_type

          TYPE  chunk_struct
            TYPE (chunk_type), POINTER :: chunk_ptr
            INTEGER             next
 	  END TYPE chunk_struct

          TYPE (chunk_struct), POINTER :: ChunkArray(:)
          INTEGER   :: size = 0
          INTEGER   :: head = 0
          INTEGER, PARAMETER :: INC = 100

      CONTAINS

        FUNCTION allocateChunk(index)
          INTEGER index, i
          TYPE (chunk_type), POINTER :: allocateChunk
          TYPE (chunk_struct), POINTER :: oldArray(:)

C         initialize/expand table
          IF (head .eq. 0) THEN
            oldArray => ChunkArray
            ALLOCATE(ChunkArray(size+INC))

C           copy old stuff to new one and deallocate
            Do i = 1, size
                ChunkArray(i) = oldArray(i)
            ENDDO
            IF( size .gt. 0) DEALLOCATE(oldArray)

C           initialize free list
            head = size+1
            size = size + INC
            DO i = head, size-1
               ChunkArray(i)%next = i+1
            ENDDO
            ChunkArray(size)%next = 0
          ENDIF

C         pick head from free list and allocate
          ALLOCATE(ChunkArray(head)%chunk_ptr)
          allocateChunk => ChunkArray(head)%chunk_ptr
          index = head
          head = ChunkArray(head)%next
          ChunkArray(index)%next = -1
        END FUNCTION

        FUNCTION getChunk(index)
          INTEGER index
          TYPE (chunk_type), POINTER :: getChunk
          getChunk => ChunkArray(index)%chunk_ptr
        END FUNCTION

        SUBROUTINE deleteChunk(index)
          INTEGER index
          IF (ChunkArray(index)%next .eq. -1) THEN
            DEALLOCATE(ChunkArray(index)%chunk_ptr)
            ChunkArray(index)%next = head
            head = index
          ENDIF
        END SUBROUTINE

      END MODULE chunkModule

