!  array_fun   -  A program to show some example of array behavior,
!                 tricks, and fucntion in fortran
!  by Jim Crumley   20070219

PROGRAM array_fun
  IMPLICIT NONE

  INTEGER, PARAMETER :: array_size1 =10000, array_size2= 20, n1=5,n2=7
  REAL :: a(array_size1, array_size2), b(n1,n2), sqroot(n1,n2)
  REAL :: c(-2: array_size1-3, 10:array_size2+9)
  INTEGER :: i,j

! Play with the functions that return information about array sizes and shapes
  100 FORMAT  (a6,' | ', 2I6, '   | ', 2I6,' | ', 2I5, ' | ',I6)
  
  PRINT *, "Array |   lower bounds | upper bounds |   shape    | size"
  PRINT *, '------|----------------|--------------|------------|-------'
  PRINT 100, 'a',  LBOUND(a), UBOUND(a), SHAPE(a), SIZE(a) 
  PRINT 100, 'c',  LBOUND(c), UBOUND(c), SHAPE(c), SIZE(c)
  PRINT 100, 'b',  LBOUND(b), UBOUND(b), SHAPE(b), SIZE(b)
  
  ! inititialize array b
  DO i =1, n1
    DO j =1,n2
      b(i,j) = i*j*(-1.)**(i+j)
    ENDDO
  ENDDO

  CALL print_array(b, n1, n2, 'b')

!calculate square root
  WHERE ((b >= 0.0) .AND. (b < 20.0))
    sqroot = SQRT(b)
  ELSEWHERE
    sqroot = -999.
  ENDWHERE

  CALL print_array(sqroot, n1, n2, 'sqroot')

END PROGRAM


SUBROUTINE print_array(array, dim1, dim2, arr_name)
  IMPLICIT NONE

  INTEGER, INTENT(IN) :: dim1, dim2
  REAL, DIMENSION(dim1, dim2), INTENT(IN) :: array 
  CHARACTER (len=*), INTENT(IN) :: arr_name
  INTEGER :: i

  ! header lines for the print out
  PRINT *,
  PRINT *, "Array ", arr_name
  PRINT *, '  i|     1     2     3     4     5     6     7'
  PRINT *, '---|--------------------------------------------'

  !  Print each line of the array
  DO i =1, dim1
    PRINT "(I3, a3, 7F6.0)",i, ' | ', array(i,:)
  ENDDO

  PRINT *,
  
END SUBROUTINE
