module M_Array_2D_to_1D
    
    contains
    
    subroutine Array_2D_to_1D ( b2D, IsPackUse )
    
        implicit none
        
        real*8, intent(in) :: b2D (: , :)
        logical, intent(in) :: IsPackUse
        
        !LOCAL
        real*8, allocatable :: loc1D ( : )
        integer :: nx, ny
        integer:: i, j, ind
        integer :: ios

        nx = ubound ( b2D ( :, : ), DIM = 1 )
        ny = ubound ( b2D ( :, : ), DIM = 2 )

        allocate( loc1D ( nx*ny ), stat = ios)

        if ( ios /= 0 ) then
            print*, "Memory can not be allocated loc1D"
            return
        endif
        
        if( IsPackUse ) then
            loc1D(:) = pack(b2D, .true.)
        else
            do j = 1, ny
                do i = 1, nx
                    ind = ( j - 1 ) * nx + i
                    loc1D ( ind ) = b2D ( i, j )
                enddo
            enddo                
        endif

        deallocate( loc1D )
        
        return
    end subroutine Array_2D_to_1D
end module M_Array_2D_to_1D