!  dfadn.f90 
!
!  FUNCTIONS/SUBROUTINES exported from dfadn.dll:
!  dfadn - subroutine 
!
subroutine dfnr8(SA)
use ifcom
use ISO_C_BINDING
  implicit none
  ! Expose subroutine dfadn to users of this DLL
  !
  !
  !dec$ attributes dllexport, stdcall, reference, alias : "DFNR8" :: dfnr8
  ! Variables
REAL(8),PARAMETER :: PI  = 4 * atan (1.0_8)  
integer(int_ptr_kind()), intent(inout) :: SA  !Pointer to a SafeArray structure
integer idim
type bounds_type
    integer lb  ! Lower Bound
    integer ub  ! Upper Bound
end type bounds_type
integer ibounds  ! Number of bounds
type(bounds_type), allocatable :: bounds(:)
integer, allocatable :: indexes(:)  ! Array to hold current element indexes
integer, allocatable :: aidimn(:)
integer :: i, iRes,isize,ivart,ilen
integer(C_INTPTR_T):: adptr
type(c_ptr) cptr;
real(8), pointer :: array_data(:), array_data1(:)
real(8), pointer :: a2d( : , : )
real(8), pointer :: a3d( : , : , : )
real(8), pointer :: a4d( : , : , : , : ) 
real(8), pointer :: a5d( : , : , : , : , : )
  ! Body of dfadn
ires=SafeArrayLock(SA)
isize=SafeArrayGetElemsize(SA)
!ires=SafeArrayGetVartype(SA,ivart) ! would be nice to be in ifcon to xlat types
!This routine for real(8)
idim = SafeArrayGetDim (SA)
allocate (bounds(idim), indexes(idim),aidimn(idim))
ilen=1
do i=1,idim
    ires = SafeArrayGetLbound (SA, i, bounds(i)%lb)
    ires = SafeArrayGetUbound (SA, i, bounds(i)%ub)
    aidimn(i)=bounds(i)%ub-bounds(i)%lb + 1
    ilen=ilen*aidimn(i)
end do
!
ires=SafeArrayAccessData(SA,adptr)
cptr=transfer(adptr,c_null_ptr)
call c_f_pointer(cptr,array_data,[ilen])  
call c_f_pointer(cptr,array_data1,[ilen])
array_data(0:) => array_data1
! Problem now is how to access as multidimensional array the elements
! Perhaps case idim 
! First, lets make each dim work independently from[2,5]
!case 2
if( idim==2 )then
    a2d(bounds(1)%lb:bounds(1)%ub,bounds(2)%lb:bounds(2)%ub)=>array_data
    !a2d(0:aidimn(1)-1, 0:aidimn(2)-1)=>array_data
endif
!end case 2
! manipulate a2d
  do i=0,2
      a2d(i,3)=PI*a2d(i,0)*a2d(i,0)*a2d(i,1)*a2d(i,2)/4
  end do  
! end manipulate a2d
iRes=SafeArrayUnlock(SA)
  ! 
deallocate (bounds)
deallocate (indexes)
deallocate (aidimn)
!
end subroutine dfnr8
