!
!     (c) 2019-2020 Guide Star Engineering, LLC
!     This Software was developed for the US Nuclear Regulatory Commission (US NRC) under contract
!     "Multi-Dimensional Physics Implementation into Fuel Analysis under Steady-state and Transients (FAST)",
!     contract # NRC-HQ-60-17-C-0007
!
module adi_mod
  implicit none
  integer ,parameter :: digits=8  ! num. digits of kind
  integer ,parameter :: decades=9 ! num. representable decades
  integer ,parameter :: rkind = selected_real_kind(digits)
  integer ,parameter :: ikind = selected_int_kind(decades)

  type grid_block
    real(rkind), dimension(8,4) :: v
    real(rkind), dimension(8)   :: ddx2, ddy2, ddz2
    real(rkind), dimension(8)   :: T_analytical
  end type grid_block

  type(grid_block)  ,dimension(:,:,:) ,allocatable  :: global_grid_block
  integer(ikind)  :: i, j, k
  integer(ikind) ,parameter :: nx=41, ny=41, nz=41

contains

  pure function position_vectors(nx,ny,nz) result(vector_field)
    integer(ikind), intent(in) :: nx, ny, nz
    integer(ikind), parameter :: components=4
    real(rkind), parameter :: dx=0.6/(15.0), dy=0.6/(15.0)
    real(rkind), parameter :: dx_s=0.4/5.0, dy_s=0.4/5.0
    real(rkind), dimension(:,:,:,:) ,allocatable  :: vector_field
    integer(ikind) :: ii, jj, kk

    allocate( vector_field(nx,ny,nz,components) )

    associate( dz=>2.0/(nz-1) )
      do concurrent( ii=1:nx, jj=1:ny, kk=1:nz )
        vector_field(ii,jj,kk,1) = merge(-0.6+(ii-6)*dx, merge( -1.0+(ii-1)*dx_s, 0.6+(ii-36)*dx_s, ii<6), ii>=6 .and. ii<=36)
        vector_field(ii,jj,kk,2) = merge(-0.6+(jj-6)*dy, merge( -1.0+(jj-1)*dy_s, 0.6+(jj-36)*dy_s, jj<6), jj>=6 .and. jj<=36)
        vector_field(ii,jj,kk,3) = -1.0+(kk-1)*dz
        vector_field(ii,jj,kk,4) = merge(2.0, 1.0, (ii==1 .or. ii==nx .or. jj==1 .or. jj==ny .or. kk==1 .or. kk==nz))
      end do
    end associate
  end function

  function tridiagonal_matrix_algorithm(a,b,c,d) result(x)
    real(rkind), dimension(:), intent(inout)  :: a,b,c,d
    real(rkind), dimension(:), allocatable :: x
    integer(ikind)                         :: i,n
    real(rkind)                            :: w
    n= size(b)
    allocate(x(n))
    do i=2,n
      w=a(i)/b(i-1)
      b(i)=b(i)-w*c(i-1)
      d(i)=d(i)-w*d(i-1)
    end do
    x(n)=d(n)/b(n)
    do i=n-1,1,-1
      x(i)=(d(i)-c(i)*x(i+1))/b(i)
    end do
  end function

  subroutine get_ddx2(this)
    type(grid_block), dimension(:,:,:), intent(inout)     :: this
    integer(ikind)                                        :: i, j, k
    real(rkind), dimension(8)                             :: dx_f, dx_b, dx_m
    associate( n=>shape(this) )
    do concurrent(k=2:n(3)-1, j=2:n(2)-1, i=2:n(1)-1)
      associate(nv=>[1,3,5,7])
        dx_m(nv)=0.5*(this(i,j,k)%v(nv+1,1)-this(i-1,j,k)%v(nv,1))
        dx_f(nv)=this(i,j,k)%v(nv+1,1)-this(i,j,k)%v(nv,1)
        dx_b(nv)=this(i,j,k)%v(nv,1)-this(i-1,j,k)%v(nv,1)
        this(i,j,k)%ddx2(nv)=(this(i,j,k)%v(nv+1,4) - this(i,j,k)%v(nv,4))/(dx_f(nv)*dx_m(nv)) - &
                              (this(i,j,k)%v(nv,4) - this(i-1,j,k)%v(nv,4))/(dx_b(nv)*dx_m(nv))
      end associate
      associate(nv=>[2,4,6,8])
        dx_m(nv)=0.5*(this(i+1,j,k)%v(nv,1)-this(i,j,k)%v(nv-1,1))
        dx_f(nv)=this(i+1,j,k)%v(nv,1)-this(i,j,k)%v(nv,1)
        dx_b(nv)=this(i,j,k)%v(nv,1)-this(i,j,k)%v(nv-1,1)
        this(i,j,k)%ddx2(nv)=(this(i+1,j,k)%v(nv,4) - this(i,j,k)%v(nv,4))/(dx_f(nv)*dx_m(nv)) - &
                              (this(i,j,k)%v(nv,4) - this(i,j,k)%v(nv-1,4))/(dx_b(nv)*dx_m(nv))
      end associate
    end do
    end associate
  end subroutine

  subroutine get_ddy2(this)
    type(grid_block), dimension(:,:,:), intent(inout)     :: this
    integer(ikind)                                        :: i, j, k
    real(rkind), dimension(8)                             :: dy_f, dy_b, dy_m
    associate( n=>shape(this) )
      do concurrent(k=2:n(3)-1, j=2:n(2)-1, i=2:n(1)-1)
        associate(nv=>[1,2,5,6])
          dy_m(nv)=0.5*(this(i,j,k)%v(nv+2,2) - this(i,j-1,k)%v(nv,2))
          dy_f(nv)=this(i,j,k)%v(nv+2,2) - this(i,j,k)%v(nv,2)
          dy_b(nv)=this(i,j,k)%v(nv,2) - this(i,j-1,k)%v(nv,2)
          this(i,j,k)%ddy2(nv)=(this(i,j,k)%v(nv+2,4) - this(i,j,k)%v(nv,4))/(dy_f(nv)*dy_m(nv)) - &
                                (this(i,j,k)%v(nv,4) - this(i,j-1,k)%v(nv,4))/(dy_b(nv)*dy_m(nv))
        end associate
        associate(nv=>[3,4,7,8])
          dy_m(nv) =0.5*(this(i,j+1,k)%v(nv,2) - this(i,j,k)%v(nv-2,2))
          dy_f(nv) =this(i,j+1,k)%v(nv,2) - this(i,j,k)%v(nv,2)
          dy_b(nv) =this(i,j,k)%v(nv,2) - this(i,j,k)%v(nv-2,2)
          this(i,j,k)%ddy2(nv)=(this(i,j+1,k)%v(nv,4) - this(i,j,k)%v(nv,4))/(dy_f(nv)*dy_m(nv)) - &
                                (this(i,j,k)%v(nv,4) - this(i,j,k)%v(nv-2,4))/(dy_b(nv)*dy_m(nv))
        end associate
      end do
    end associate
  end subroutine

  subroutine get_ddz2(this)
    type(grid_block), dimension(:,:,:), intent(inout)     :: this
    integer(ikind)                                        :: i, j, k
    real(rkind), dimension(8)                             :: dz_f, dz_b, dz_m
    associate( n=>shape(this) )
      do concurrent(k=2:n(3)-1, j=2:n(2)-1, i=2:n(1)-1)
        associate(nv=>[1,2,3,4])
          dz_m(nv)=0.5*(this(i,j,k)%v(nv+4,3) - this(i,j,k-1)%v(nv,3))
          dz_f(nv)=this(i,j,k)%v(nv+4,3) - this(i,j,k)%v(nv,3)
          dz_b(nv)=this(i,j,k)%v(nv,3) - this(i,j,k-1)%v(nv,3)
          this(i,j,k)%ddz2(nv)=(this(i,j,k)%v(nv+4,4) - this(i,j,k)%v(nv,4))/(dz_f(nv)*dz_m(nv)) - &
                                (this(i,j,k)%v(nv,4) - this(i,j,k-1)%v(nv,4))/(dz_b(nv)*dz_m(nv))
        end associate
        associate(nv=>[5,6,7,8])
          dz_m(nv)=0.5*(this(i,j,k+1)%v(nv,3)-this(i,j,k)%v(nv-4,3))
          dz_f(nv)=this(i,j,k+1)%v(nv,3)-this(i,j,k)%v(nv,3)
          dz_b(nv)=this(i,j,k)%v(nv,3)-this(i,j,k)%v(nv-4,3)
          this(i,j,k)%ddz2(nv)=(this(i,j,k+1)%v(nv,4) - this(i,j,k)%v(nv,4))/(dz_f(nv)*dz_m(nv)) - &
                                (this(i,j,k)%v(nv,4) - this(i,j,k)%v(nv-4,4))/(dz_b(nv)*dz_m(nv))
        end associate
      end do
    end associate
  end subroutine

  subroutine write_component(grid_blocks, component, file_unit, string)
    type(grid_block), intent(in), dimension(:,:,:) :: grid_blocks
    character(len=*), intent(in) :: component
    character(len=*), intent(in), optional :: string
    integer, intent(in) :: file_unit
    integer(ikind) :: i, j, k, nv, ndimension
    associate( n=>shape(grid_blocks) )
    do k=1, n(3)
      do j=1, n(2)
        do i=1, n(1)
          do nv=1,merge(1,8,component=="string")
            select case(component)
              case("T")
                write (file_unit,*) grid_blocks(i,j,k)%v(nv,4)
              case("v")
                write(file_unit, *) (grid_blocks(i,j,k)%v(nv,ndimension), ndimension=1,3)
              case("analytical_T")
                write (file_unit,*) grid_blocks(i,j,k)%T_analytical(nv)
              case("string")
                write (file_unit,*) string
              case default
                error stop "write_component: unrecognized component"
            end select
          end do
        end do
      end do
    end do
    end associate
  end subroutine

  subroutine output_result(grid_blocks)
    type(grid_block), intent(in), dimension(:,:,:) :: grid_blocks
    integer file_unit

    open(newunit=file_unit, file="3d-htc-grid.vtk")
    write(file_unit, '(a)') '# vtk DataFile Version 3.0'
    write(file_unit, '(a)') '3d-htc voxels'
    write(file_unit, '(a)') 'ASCII'
    write(file_unit, '(a)') 'DATASET UNSTRUCTURED_GRID'
    write(file_unit, '(a,i10,a)') "POINTS ", 8*(nx-1)*(ny-1)*(nz-1), " double"
    call write_component( grid_blocks, "v", file_unit)

    block
      integer i, j, k, nv
      write(file_unit,'(a,i10,3x,i10)') "CELLS ", (nx-1)*(ny-1)*(nz-1), 9*(nx-1)*(ny-1)*(nz-1)
      associate( n=>shape(grid_blocks) )
        do k=1, n(3)
          do j=1, n(2)
            do i=1, n(1)
              associate( grid_block_id => 8*(i+(j-1)*n(1)+(k-1)*n(1)*n(2)-1) )
                write(file_unit,*) "8", (grid_block_id+nv-1, nv=1,8)
              end associate
            end do
          end do
        end do
      end associate
    end block

    write(file_unit,'(a,I10)') "CELL_TYPES ", (nx-1)*(ny-1)*(nz-1)
    call write_component( grid_blocks, "string", file_unit, string="11")

    write(file_unit,'(a, I10)') 'POINT_DATA ', 8*(nx-1)*(ny-1)*(nz-1)
    write(file_unit,'(a)') 'SCALARS Temperature double 1'
    write(file_unit,'(a)') 'LOOKUP_TABLE default'
    call write_component( grid_blocks, "T", file_unit)

    write(file_unit,'(a)') 'SCALARS analytical_T double 1'
    write(file_unit,'(a)') 'LOOKUP_TABLE default'
    call write_component( grid_blocks, "analytical_T", file_unit)

    close(file_unit)

    block
      integer k, error_file_unit
      open(newunit=error_file_unit, file="error-order.dat")
      do k=1, nz-1
        write(error_file_unit, *) &
          grid_blocks(20,20,k)%v(1,4)-grid_blocks(20,20,k)%T_analytical(1)
      end do
      close(error_file_unit)
    end block
  end subroutine output_result

  end module adi_mod

program main
  use adi_mod
  implicit none
    real(rkind)            :: avg_err_percentage
    integer(ikind)         :: nv
    real(rkind), dimension(:,:,:), allocatable :: a_mnl, k_mnl
    integer(ikind)                             :: l,m,n,kk,jj,ii
    real(rkind)                                :: pi, t
  associate( p => position_vectors(nx,ny,nz) )

    allocate(global_grid_block(nx-1,ny-1,nz-1))

    associate( x=>(p(:,:,:,1)), y=>(p(:,:,:,2)), z=>(p(:,:,:,3)), T=>(p(:,:,:,4)) )
      do concurrent(k=1:nz-1, j=1:ny-1, i=1:nx-1)
        associate( v=>global_grid_block(i,j,k)%v )
          v(1,:) = [x(i,j,k)      , y(i,j,k)      , z(i,j,k)       , T(i,j,k)       ]
          v(2,:) = [x(i+1,j,k)    , y(i+1,j,k)    , z(i+1,j,k)     , T(i+1,j,k)     ]
          v(3,:) = [x(i,j+1,k)    , y(i,j+1,k)    , z(i,j+1,k)     , T(i,j+1,k)     ]
          v(4,:) = [x(i+1,j+1,k)  , y(i+1,j+1,k)  , z(i+1,j+1,k)   , T(i+1,j+1,k)   ]
          v(5,:) = [x(i,j,k+1)    , y(i,j,k+1)    , z(i,j,k+1)     , T(i,j,k+1)     ]
          v(6,:) = [x(i+1,j,k+1)  , y(i+1,j,k+1)  , z(i+1,j,k+1)   , T(i+1,j,k+1)   ]
          v(7,:) = [x(i,j+1,k+1)  , y(i,j+1,k+1)  , z(i,j+1,k+1)   , T(i,j+1,k+1)   ]
          v(8,:) = [x(i+1,j+1,k+1), y(i+1,j+1,k+1), z(i+1,j+1,k+1) , T(i+1,j+1,k+1) ]
          associate(ddx2=>global_grid_block(i,j,k)%ddx2, ddy2=>global_grid_block(i,j,k)%ddy2, &
                            ddz2=>global_grid_block(i,j,k)%ddz2 )
            ddx2(:) = 0.0
            ddy2(:) = 0.0
            ddz2(:) = 0.0
          end associate
        end associate
      end do
    end associate
  end associate

  time_advancing: block
    real(rkind)  :: dx_m, dy_m, dz_m
    real(rkind)  :: dx_f, dy_f, dz_f
    real(rkind)  :: dx_b, dy_b, dz_b
    integer(ikind), dimension(3) :: n
    real(rkind), dimension(8,4)            :: v
    real(rkind), dimension(8)              :: ddx2, ddy2, ddz2
    real(rkind), dimension(:), allocatable :: a,b,c,d
    real(rkind)                            :: f,dt,t

    f=0.1
    dt=0.002
    t=0.0
    do while(t<=0.1)
    !associate(n=>shape(global_grid_block))
    n = shape(global_grid_block)
      !x direction
      allocate(a(n(1)-1),b(n(1)-1),c(n(1)-1),d(n(1)-1))
      call get_ddy2(global_grid_block)
      call get_ddz2(global_grid_block)
      do k=2,n(3)
        do j=2,n(2)
          do i=2,n(1)
            !associate(v=>global_grid_block(i,j,k)%v, ddy2=>global_grid_block(i,j,k)%ddy2, ddz2=>global_grid_block(i,j,k)%ddz2)
            v=global_grid_block(i,j,k)%v; ddy2=global_grid_block(i,j,k)%ddy2; ddz2=global_grid_block(i,j,k)%ddz2
              dx_m = 0.5*(v(2,1) - global_grid_block(i-1,j,k)%v(1,1))
              dx_f =      v(2,1) - v(1,1)
              dx_b =      v(1,1)   - global_grid_block(i-1,j,k)%v(1,1)
              a(i-1)=-(3.0-2.0*f)/(dx_b*dx_m)
              b(i-1)=(3.0-2.0*f)/(dx_f*dx_m)+(3.0-2.0*f)/(dx_b*dx_m)+3.0/dt
              c(i-1)=-(3.0-2.0*f)/(dx_f*dx_m)
              d(i-1)=3.0*v(1,4)/dt+f*ddy2(1)+f*ddz2(1)
              if (i==2) d(i-1)=d(i-1)-a(i-1)*global_grid_block(i-1,j,k)%v(1,4)
              if (i==n(1)) d(i-1)=d(i-1)-c(i-1)*v(2,4)
            !end associate
          end do
          associate(U=>tridiagonal_matrix_algorithm(a,b,c,d))
            do i=2,n(1)
              global_grid_block(i-1,j-1,k-1)%v(8,4)=U(i-1)
              global_grid_block(i-1,j-1,k)%v(4,4)=U(i-1)
              global_grid_block(i-1,j,k-1)%v(6,4)=U(i-1)
              global_grid_block(i-1,j,k)%v(2,4)=U(i-1)
              global_grid_block(i,j,k)%v(1,4)=U(i-1)
              global_grid_block(i,j-1,k-1)%v(7,4)=U(i-1)
              global_grid_block(i,j-1,k)%v(3,4)=U(i-1)
              global_grid_block(i,j,k-1)%v(5,4)=U(i-1)
            end do
          end associate
        end do
      end do
      deallocate(a,b,c,d)

      ! y direction
      allocate(a(n(2)-1),b(n(2)-1),c(n(2)-1),d(n(2)-1))
      call get_ddx2(global_grid_block)
      call get_ddz2(global_grid_block)
      do k=2,n(3)
        do i=2,n(1)
          do j=2,n(2)
            !associate(v=>global_grid_block(i,j,k)%v, ddx2=>global_grid_block(i,j,k)%ddx2, ddz2=>global_grid_block(i,j,k)%ddz2)
            v=global_grid_block(i,j,k)%v; ddx2=global_grid_block(i,j,k)%ddx2; ddz2=global_grid_block(i,j,k)%ddz2
              dy_m=0.5*(v(3,2) - global_grid_block(i,j-1,k)%v(1,2))
              dy_f=v(3,2) - v(1,2)
              dy_b=v(1,2) - global_grid_block(i,j-1,k)%v(1,2)
              a(j-1)=-(3.0-2.0*f)/(dy_b*dy_m)
              b(j-1)=(3.0-2.0*f)/(dy_f*dy_m)+(3.0-2.0*f)/(dy_b*dy_m)+3.0/dt
              c(j-1)=-(3.0-2.0*f)/(dy_f*dy_m)
              d(j-1)=3.0*v(1,4)/dt+f*ddx2(1)+f*ddz2(1)
              if (j==2) d(j-1)=d(j-1)-a(j-1)*global_grid_block(i,j-1,k)%v(1,4)
              if (j==n(2)) d(j-1)=d(j-1)-c(j-1)*v(3,4)
            !end associate
          end do
          associate(U=>tridiagonal_matrix_algorithm(a,b,c,d))
          do j=2,n(2)
            global_grid_block(i-1,j-1,k-1)%v(8,4)=U(j-1)
            global_grid_block(i-1,j-1,k)%v(4,4)=U(j-1)
            global_grid_block(i-1,j,k-1)%v(6,4)=U(j-1)
            global_grid_block(i-1,j,k)%v(2,4)=U(j-1)
            global_grid_block(i,j,k)%v(1,4)=U(j-1)
            global_grid_block(i,j-1,k-1)%v(7,4)=U(j-1)
            global_grid_block(i,j-1,k)%v(3,4)=U(j-1)
            global_grid_block(i,j,k-1)%v(5,4)=U(j-1)
          end do
          end associate
        end do
      end do
      deallocate(a,b,c,d)

      ! z direction
      allocate(a(n(3)-1),b(n(3)-1),c(n(3)-1),d(n(3)-1))
      call get_ddx2(global_grid_block)
      call get_ddy2(global_grid_block)
      do j=2,n(2)
        do i=2,n(1)
          do k=2,n(3)
            associate(v=>global_grid_block(i,j,k)%v, ddx2=>global_grid_block(i,j,k)%ddx2, ddy2=>global_grid_block(i,j,k)%ddy2)
              dz_m=0.5*(v(5,3) - global_grid_block(i,j,k-1)%v(1,3))
              dz_f=v(5,3) - v(1,3)
              dz_b=v(1,3) - global_grid_block(i,j,k-1)%v(1,3)
              a(k-1)=-(3.0-2.0*f)/(dz_b*dz_m)
              b(k-1)=(3.0-2.0*f)/(dz_f*dz_m)+(3.0-2.0*f)/(dz_b*dz_m)+3.0/dt
              c(k-1)=-(3.0-2.0*f)/(dz_f*dz_m)
              d(k-1)=3.0*v(1,4)/dt+f*ddx2(1)+f*ddy2(1)
              if (k==2) d(k-1)=d(k-1)-a(k-1)*global_grid_block(i,j,k-1)%v(1,4)
              if (k==n(3)) d(k-1)=d(k-1)-c(k-1)*v(5,4)
            end associate
          end do
          associate(U=>tridiagonal_matrix_algorithm(a,b,c,d))
          do k=2,n(3)
            global_grid_block(i-1,j-1,k-1)%v(8,4)=U(k-1)
            global_grid_block(i-1,j-1,k)%v(4,4)=U(k-1)
            global_grid_block(i-1,j,k-1)%v(6,4)=U(k-1)
            global_grid_block(i-1,j,k)%v(2,4)=U(k-1)
            global_grid_block(i,j,k)%v(1,4)=U(k-1)
            global_grid_block(i,j-1,k-1)%v(7,4)=U(k-1)
            global_grid_block(i,j-1,k)%v(3,4)=U(k-1)
            global_grid_block(i,j,k-1)%v(5,4)=U(k-1)
          end do
          end associate
        end do
      end do
      deallocate(a,b,c,d)
    !end associate
    t=t+dt
    end do
  end block time_advancing

!  analytical_solution: block
!    real(rkind), dimension(:,:,:), allocatable :: a_mnl, k_mnl
!    integer(ikind)                             :: l,m,n,kk,jj,ii
!    real(rkind)                                :: pi, t

    pi=4.0*atan(1.0)
    t=0.1
    allocate(a_mnl(10,10,10), k_mnl(10,10,10))
    do concurrent(l=1:10, n=1:10, m=1:10)
      a_mnl(m,n,l)=-64.0/(pi**3*(2.0*m-1)*(2.0*n-1)*(2.0*l-1))*sin(0.5*(2.0*m-1)*pi)*sin(0.5*(2.0*n-1)*pi)*sin(0.5*(2.0*l-1)*pi)
      k_mnl(m,n,l)=(0.5*(2.0*m-1)*pi)**2+(0.5*(2.0*n-1)*pi)**2+(0.5*(2.0*l-1)*pi)**2
    end do
    do concurrent(kk=1:nz-1,jj=1:ny-1,ii=1:nx-1)
      global_grid_block(ii,jj,kk)%T_analytical(:)=2.0
    end do
    do concurrent(k=2:nz-1,j=2:ny-1,i=2:nx-1)
      do concurrent(l=1:10,n=1:10,m=1:10)
        global_grid_block(i,j,k)%T_analytical(1)=global_grid_block(i,j,k)%T_analytical(1)+a_mnl(m,n,l)*exp(-k_mnl(m,n,l)*t)* &
                                                  cos(0.5*(2.0*m-1)*pi*global_grid_block(i,j,k)%v(1,1))* &
                                                  cos(0.5*(2.0*n-1)*pi*global_grid_block(i,j,k)%v(1,2))* &
                                                  cos(0.5*(2.0*l-1)*pi*global_grid_block(i,j,k)%v(1,3))
      end do
    end do
    do concurrent(k=2:nz-1,j=2:ny-1, i=2:nx-1)
      global_grid_block(i-1,j-1,k-1)%T_analytical(8)=global_grid_block(i,j,k)%T_analytical(1)
      global_grid_block(i-1,j-1,k)%T_analytical(4)=global_grid_block(i,j,k)%T_analytical(1)
      global_grid_block(i-1,j,k-1)%T_analytical(6)=global_grid_block(i,j,k)%T_analytical(1)
      global_grid_block(i-1,j,k)%T_analytical(2)=global_grid_block(i,j,k)%T_analytical(1)
      global_grid_block(i,j,k)%T_analytical(1)=global_grid_block(i,j,k)%T_analytical(1)
      global_grid_block(i,j-1,k-1)%T_analytical(7)=global_grid_block(i,j,k)%T_analytical(1)
      global_grid_block(i,j-1,k)%T_analytical(3)=global_grid_block(i,j,k)%T_analytical(1)
      global_grid_block(i,j,k-1)%T_analytical(5)=global_grid_block(i,j,k)%T_analytical(1)
    end do
!  end block analytical_solution

!  error_calculation: block
!    real(rkind)            :: avg_err_percentage
!    integer(ikind)         :: nv
    avg_err_percentage=0.0
    do concurrent(k=1:nz-1,j=1:ny-1,i=1:nx-1,nv=1:8)
      avg_err_percentage=avg_err_percentage+abs((global_grid_block(i,j,k)%v(nv,4)-global_grid_block(i,j,k)%T_analytical(nv))/ &
              global_grid_block(i,j,k)%T_analytical(nv))
    end do
    avg_err_percentage=100*avg_err_percentage/((nz-1)*(ny-1)*(nx-1)*8)
    if (avg_err_percentage < 0.1) print *, "Test passed."
!  end block error_calculation

  call output_result(global_grid_block)

end program main


program intrinsics_25
implicit none

integer(4), parameter:: x = ishft(123, 5)
integer(4), parameter:: y = ishft(25, 0)
integer(8), parameter:: z = ishft(1000000000, -2)

print *, x, y, z
print *, ishft(123, 5), ishft(25, 0), ishft(1000000000, -2)

end program intrinsics_25


      SUBROUTINE AB09JD( JOBV, JOBW, JOBINV, DICO, EQUIL, ORDSEL,
     $                   N, NV, NW, M, P, NR, ALPHA, A, LDA, B, LDB,
     $                   C, LDC, D, LDD, AV, LDAV, BV, LDBV,
     $                   CV, LDCV, DV, LDDV, AW, LDAW, BW, LDBW,
     $                   CW, LDCW, DW, LDDW, NS, HSV, TOL1, TOL2,
     $                   IWORK, DWORK, LDWORK, IWARN, INFO )
C
C     SLICOT RELEASE 5.7.
C
C     Copyright (c) 2002-2020 NICONET e.V.
C
C     PURPOSE
C
C     To compute a reduced order model (Ar,Br,Cr,Dr) for an original
C     state-space representation (A,B,C,D) by using the frequency
C     weighted optimal Hankel-norm approximation method.
C     The Hankel norm of the weighted error
C
C           op(V)*(G-Gr)*op(W)
C
C     is minimized, where G and Gr are the transfer-function matrices
C     of the original and reduced systems, respectively, V and W are
C     invertible transfer-function matrices representing the left and
C     right frequency weights, and op(X) denotes X, inv(X), conj(X) or
C     conj(inv(X)). V and W are specified by their state space
C     realizations (AV,BV,CV,DV) and (AW,BW,CW,DW), respectively.
C     When minimizing ||V*(G-Gr)*W||, V and W must be antistable.
C     When minimizing inv(V)*(G-Gr)*inv(W), V and W must have only
C     antistable zeros.
C     When minimizing conj(V)*(G-Gr)*conj(W), V and W must be stable.
C     When minimizing conj(inv(V))*(G-Gr)*conj(inv(W)), V and W must
C     be minimum-phase.
C     If the original system is unstable, then the frequency weighted
C     Hankel-norm approximation is computed only for the
C     ALPHA-stable part of the system.
C
C     For a transfer-function matrix G, conj(G) denotes the conjugate
C     of G given by G'(-s) for a continuous-time system or G'(1/z)
C     for a discrete-time system.
C
C     ARGUMENTS
C
C     Mode Parameters
C
C     JOBV    CHARACTER*1
C             Specifies the left frequency-weighting as follows:
C             = 'N':  V = I;
C             = 'V':  op(V) = V;
C             = 'I':  op(V) = inv(V);
C             = 'C':  op(V) = conj(V);
C             = 'R':  op(V) = conj(inv(V)).
C
C     JOBW    CHARACTER*1
C             Specifies the right frequency-weighting as follows:
C             = 'N':  W = I;
C             = 'W':  op(W) = W;
C             = 'I':  op(W) = inv(W);
C             = 'C':  op(W) = conj(W);
C             = 'R':  op(W) = conj(inv(W)).
C
C     JOBINV  CHARACTER*1
C             Specifies the computational approach to be used as
C             follows:
C             = 'N':  use the inverse free descriptor system approach;
C             = 'I':  use the inversion based standard approach;
C             = 'A':  switch automatically to the inverse free
C                     descriptor approach in case of badly conditioned
C                     feedthrough matrices in V or W (see METHOD).
C
C     DICO    CHARACTER*1
C             Specifies the type of the original system as follows:
C             = 'C':  continuous-time system;
C             = 'D':  discrete-time system.
C
C     EQUIL   CHARACTER*1
C             Specifies whether the user wishes to preliminarily
C             equilibrate the triplet (A,B,C) as follows:
C             = 'S':  perform equilibration (scaling);
C             = 'N':  do not perform equilibration.
C
C     ORDSEL  CHARACTER*1
C             Specifies the order selection method as follows:
C             = 'F':  the resulting order NR is fixed;
C             = 'A':  the resulting order NR is automatically determined
C                     on basis of the given tolerance TOL1.
C
C     Input/Output Parameters
C
C     N       (input) INTEGER
C             The order of the original state-space representation,
C             i.e., the order of the matrix A.  N >= 0.
C
C     NV      (input) INTEGER
C             The order of the realization of the left frequency
C             weighting V, i.e., the order of the matrix AV.  NV >= 0.
C
C     NW      (input) INTEGER
C             The order of the realization of the right frequency
C             weighting W, i.e., the order of the matrix AW.  NW >= 0.
C
C     M       (input) INTEGER
C             The number of system inputs.  M >= 0.
C
C     P       (input) INTEGER
C             The number of system outputs.  P >= 0.
C
C     NR      (input/output) INTEGER
C             On entry with ORDSEL = 'F', NR is the desired order of
C             the resulting reduced order system.  0 <= NR <= N.
C             On exit, if INFO = 0, NR is the order of the resulting
C             reduced order model. For a system with NU ALPHA-unstable
C             eigenvalues and NS ALPHA-stable eigenvalues (NU+NS = N),
C             NR is set as follows: if ORDSEL = 'F', NR is equal to
C             NU+MIN(MAX(0,NR-NU-KR+1),NMIN), where KR is the
C             multiplicity of the Hankel singular value HSV(NR-NU+1),
C             NR is the desired order on entry, and NMIN is the order
C             of a minimal realization of the ALPHA-stable part of the
C             given system; NMIN is determined as the number of Hankel
C             singular values greater than NS*EPS*HNORM(As,Bs,Cs), where
C             EPS is the machine precision (see LAPACK Library Routine
C             DLAMCH) and HNORM(As,Bs,Cs) is the Hankel norm of the
C             ALPHA-stable part of the weighted system (computed in
C             HSV(1));
C             if ORDSEL = 'A', NR is the sum of NU and the number of
C             Hankel singular values greater than
C             MAX(TOL1,NS*EPS*HNORM(As,Bs,Cs)).
C
C     ALPHA   (input) DOUBLE PRECISION
C             Specifies the ALPHA-stability boundary for the eigenvalues
C             of the state dynamics matrix A. For a continuous-time
C             system (DICO = 'C'), ALPHA <= 0 is the boundary value for
C             the real parts of eigenvalues, while for a discrete-time
C             system (DICO = 'D'), 0 <= ALPHA <= 1 represents the
C             boundary value for the moduli of eigenvalues.
C             The ALPHA-stability domain does not include the boundary.
C
C     A       (input/output) DOUBLE PRECISION array, dimension (LDA,N)
C             On entry, the leading N-by-N part of this array must
C             contain the state dynamics matrix A.
C             On exit, if INFO = 0, the leading NR-by-NR part of this
C             array contains the state dynamics matrix Ar of the
C             reduced order system in a real Schur form.
C             The resulting A has a block-diagonal form with two blocks.
C             For a system with NU ALPHA-unstable eigenvalues and
C             NS ALPHA-stable eigenvalues (NU+NS = N), the leading
C             NU-by-NU block contains the unreduced part of A
C             corresponding to ALPHA-unstable eigenvalues.
C             The trailing (NR+NS-N)-by-(NR+NS-N) block contains
C             the reduced part of A corresponding to ALPHA-stable
C             eigenvalues.
C
C     LDA     INTEGER
C             The leading dimension of array A.  LDA >= MAX(1,N).
C
C     B       (input/output) DOUBLE PRECISION array, dimension (LDB,M)
C             On entry, the leading N-by-M part of this array must
C             contain the original input/state matrix B.
C             On exit, if INFO = 0, the leading NR-by-M part of this
C             array contains the input/state matrix Br of the reduced
C             order system.
C
C     LDB     INTEGER
C             The leading dimension of array B.  LDB >= MAX(1,N).
C
C     C       (input/output) DOUBLE PRECISION array, dimension (LDC,N)
C             On entry, the leading P-by-N part of this array must
C             contain the original state/output matrix C.
C             On exit, if INFO = 0, the leading P-by-NR part of this
C             array contains the state/output matrix Cr of the reduced
C             order system.
C
C     LDC     INTEGER
C             The leading dimension of array C.  LDC >= MAX(1,P).
C
C     D       (input/output) DOUBLE PRECISION array, dimension (LDD,M)
C             On entry, the leading P-by-M part of this array must
C             contain the original input/output matrix D.
C             On exit, if INFO = 0, the leading P-by-M part of this
C             array contains the input/output matrix Dr of the reduced
C             order system.
C
C     LDD     INTEGER
C             The leading dimension of array D.  LDD >= MAX(1,P).
C
C     AV      (input/output) DOUBLE PRECISION array, dimension (LDAV,NV)
C             On entry, if JOBV <> 'N', the leading NV-by-NV part of
C             this array must contain the state matrix AV of a state
C             space realization of the left frequency weighting V.
C             On exit, if JOBV <> 'N', and INFO = 0, the leading
C             NV-by-NV part of this array contains the real Schur form
C             of AV.
C             AV is not referenced if JOBV = 'N'.
C
C     LDAV    INTEGER
C             The leading dimension of the array AV.
C             LDAV >= MAX(1,NV), if JOBV <> 'N';
C             LDAV >= 1,         if JOBV =  'N'.
C
C     BV      (input/output) DOUBLE PRECISION array, dimension (LDBV,P)
C             On entry, if JOBV <> 'N', the leading NV-by-P part of
C             this array must contain the input matrix BV of a state
C             space realization of the left frequency weighting V.
C             On exit, if JOBV <> 'N', and INFO = 0, the leading
C             NV-by-P part of this array contains the transformed
C             input matrix BV corresponding to the transformed AV.
C             BV is not referenced if JOBV = 'N'.
C
C     LDBV    INTEGER
C             The leading dimension of the array BV.
C             LDBV >= MAX(1,NV), if JOBV <> 'N';
C             LDBV >= 1,         if JOBV =  'N'.
C
C     CV      (input/output) DOUBLE PRECISION array, dimension (LDCV,NV)
C             On entry, if JOBV <> 'N', the leading P-by-NV part of
C             this array must contain the output matrix CV of a state
C             space realization of the left frequency weighting V.
C             On exit, if JOBV <> 'N', and INFO = 0, the leading
C             P-by-NV part of this array contains the transformed output
C             matrix CV corresponding to the transformed AV.
C             CV is not referenced if JOBV = 'N'.
C
C     LDCV    INTEGER
C             The leading dimension of the array CV.
C             LDCV >= MAX(1,P), if JOBV <> 'N';
C             LDCV >= 1,        if JOBV =  'N'.
C
C     DV      (input) DOUBLE PRECISION array, dimension (LDDV,P)
C             If JOBV <> 'N', the leading P-by-P part of this array
C             must contain the feedthrough matrix DV of a state space
C             realization of the left frequency weighting V.
C             DV is not referenced if JOBV = 'N'.
C
C     LDDV    INTEGER
C             The leading dimension of the array DV.
C             LDDV >= MAX(1,P), if JOBV <> 'N';
C             LDDV >= 1,        if JOBV =  'N'.
C
C     AW      (input/output) DOUBLE PRECISION array, dimension (LDAW,NW)
C             On entry, if JOBW <> 'N', the leading NW-by-NW part of
C             this array must contain the state matrix AW of a state
C             space realization of the right frequency weighting W.
C             On exit, if JOBW <> 'N', and INFO = 0, the leading
C             NW-by-NW part of this array contains the real Schur form
C             of AW.
C             AW is not referenced if JOBW = 'N'.
C
C     LDAW    INTEGER
C             The leading dimension of the array AW.
C             LDAW >= MAX(1,NW), if JOBW <> 'N';
C             LDAW >= 1,         if JOBW =  'N'.
C
C     BW      (input/output) DOUBLE PRECISION array, dimension (LDBW,M)
C             On entry, if JOBW <> 'N', the leading NW-by-M part of
C             this array must contain the input matrix BW of a state
C             space realization of the right frequency weighting W.
C             On exit, if JOBW <> 'N', and INFO = 0, the leading
C             NW-by-M part of this array contains the transformed
C             input matrix BW corresponding to the transformed AW.
C             BW is not referenced if JOBW = 'N'.
C
C     LDBW    INTEGER
C             The leading dimension of the array BW.
C             LDBW >= MAX(1,NW), if JOBW <> 'N';
C             LDBW >= 1,         if JOBW =  'N'.
C
C     CW      (input/output) DOUBLE PRECISION array, dimension (LDCW,NW)
C             On entry, if JOBW <> 'N', the leading M-by-NW part of
C             this array must contain the output matrix CW of a state
C             space realization of the right frequency weighting W.
C             On exit, if JOBW <> 'N', and INFO = 0, the leading
C             M-by-NW part of this array contains the transformed output
C             matrix CW corresponding to the transformed AW.
C             CW is not referenced if JOBW = 'N'.
C
C     LDCW    INTEGER
C             The leading dimension of the array CW.
C             LDCW >= MAX(1,M), if JOBW <> 'N';
C             LDCW >= 1,        if JOBW =  'N'.
C
C     DW      (input) DOUBLE PRECISION array, dimension (LDDW,M)
C             If JOBW <> 'N', the leading M-by-M part of this array
C             must contain the feedthrough matrix DW of a state space
C             realization of the right frequency weighting W.
C             DW is not referenced if JOBW = 'N'.
C
C     LDDW    INTEGER
C             The leading dimension of the array DW.
C             LDDW >= MAX(1,M), if JOBW <> 'N';
C             LDDW >= 1,        if JOBW =  'N'.
C
C     NS      (output) INTEGER
C             The dimension of the ALPHA-stable subsystem.
C
C     HSV     (output) DOUBLE PRECISION array, dimension (N)
C             If INFO = 0, the leading NS elements of this array contain
C             the Hankel singular values, ordered decreasingly, of the
C             projection G1s of op(V)*G1*op(W) (see METHOD), where G1
C             is the ALPHA-stable part of the original system.
C
C     Tolerances
C
C     TOL1    DOUBLE PRECISION
C             If ORDSEL = 'A', TOL1 contains the tolerance for
C             determining the order of reduced system.
C             For model reduction, the recommended value is
C             TOL1 = c*HNORM(G1s), where c is a constant in the
C             interval [0.00001,0.001], and HNORM(G1s) is the
C             Hankel-norm of the projection G1s of op(V)*G1*op(W)
C             (see METHOD), computed in HSV(1).
C             If TOL1 <= 0 on entry, the used default value is
C             TOL1 = NS*EPS*HNORM(G1s), where NS is the number of
C             ALPHA-stable eigenvalues of A and EPS is the machine
C             precision (see LAPACK Library Routine DLAMCH).
C             If ORDSEL = 'F', the value of TOL1 is ignored.
C             TOL1 < 1.
C
C     TOL2    DOUBLE PRECISION
C             The tolerance for determining the order of a minimal
C             realization of the ALPHA-stable part of the given system.
C             The recommended value is TOL2 = NS*EPS*HNORM(G1s).
C             This value is used by default if TOL2 <= 0 on entry.
C             If TOL2 > 0 and ORDSEL = 'A', then TOL2 <= TOL1.
C             TOL2 < 1.
C
C     Workspace
C
C     IWORK   INTEGER array, dimension (LIWORK)
C             LIWORK = MAX(1,M,c,d),    if DICO = 'C',
C             LIWORK = MAX(1,N,M,c,d),  if DICO = 'D', where
C                c = 0,                          if JOBV =  'N',
C                c = MAX(2*P,NV+P+N+6,2*NV+P+2), if JOBV <> 'N',
C                d = 0,                          if JOBW =  'N',
C                d = MAX(2*M,NW+M+N+6,2*NW+M+2), if JOBW <> 'N'.
C
C     DWORK   DOUBLE PRECISION array, dimension (LDWORK)
C             On exit, if INFO = 0, DWORK(1) returns the optimal value
C             of LDWORK.
C
C     LDWORK  INTEGER
C             The length of the array DWORK.
C             LDWORK >= MAX( LDW1, LDW2, LDW3, LDW4 ), where
C             for NVP = NV+P and NWM = NW+M we have
C             LDW1 = 0 if JOBV =  'N' and
C             LDW1 = 2*NVP*(NVP+P) + P*P +
C                    MAX( 2*NVP*NVP + MAX( 11*NVP+16, P*NVP ),
C                          NVP*N + MAX( NVP*N+N*N, P*N, P*M ) )
C                      if JOBV <> 'N',
C             LDW2 = 0 if JOBW =  'N' and
C             LDW2 = 2*NWM*(NWM+M) + M*M +
C                    MAX( 2*NWM*NWM + MAX( 11*NWM+16, M*NWM ),
C                          NWM*N + MAX( NWM*N+N*N, M*N, P*M ) )
C                      if JOBW <> 'N',
C             LDW3 = N*(2*N + MAX(N,M,P) + 5) + N*(N+1)/2,
C             LDW4 = N*(M+P+2) + 2*M*P + MIN(N,M) +
C                    MAX( 3*M+1, MIN(N,M)+P ).
C             For optimum performance LDWORK should be larger.
C
C     Warning Indicator
C
C     IWARN   INTEGER
C             = 0:  no warning;
C             = 1:  with ORDSEL = 'F', the selected order NR is greater
C                   than NSMIN, the sum of the order of the
C                   ALPHA-unstable part and the order of a minimal
C                   realization of the ALPHA-stable part of the given
C                   system. In this case, the resulting NR is set equal
C                   to NSMIN.
C             = 2:  with ORDSEL = 'F', the selected order NR is less
C                   than the order of the ALPHA-unstable part of the
C                   given system. In this case NR is set equal to the
C                   order of the ALPHA-unstable part.
C
C     Error Indicator
C
C     INFO    INTEGER
C             =  0:  successful exit;
C             <  0:  if INFO = -i, the i-th argument had an illegal
C                    value;
C             =  1:  the computation of the ordered real Schur form of A
C                    failed;
C             =  2:  the separation of the ALPHA-stable/unstable
C                    diagonal blocks failed because of very close
C                    eigenvalues;
C             =  3:  the reduction of AV to a real Schur form failed;
C             =  4:  the reduction of AW to a real Schur form failed;
C             =  5:  the reduction to generalized Schur form of the
C                    descriptor pair corresponding to the inverse of V
C                    failed;
C             =  6:  the reduction to generalized Schur form of the
C                    descriptor pair corresponding to the inverse of W
C                    failed;
C             =  7:  the computation of Hankel singular values failed;
C             =  8:  the computation of stable projection in the
C                    Hankel-norm approximation algorithm failed;
C             =  9:  the order of computed stable projection in the
C                    Hankel-norm approximation algorithm differs
C                    from the order of Hankel-norm approximation;
C             = 10:  the reduction of AV-BV*inv(DV)*CV to a
C                    real Schur form failed;
C             = 11:  the reduction of AW-BW*inv(DW)*CW to a
C                    real Schur form failed;
C             = 12:  the solution of the Sylvester equation failed
C                    because the poles of V (if JOBV = 'V') or of
C                    conj(V) (if JOBV = 'C') are not distinct from
C                    the poles of G1 (see METHOD);
C             = 13:  the solution of the Sylvester equation failed
C                    because the poles of W (if JOBW = 'W') or of
C                    conj(W) (if JOBW = 'C') are not distinct from
C                    the poles of G1 (see METHOD);
C             = 14:  the solution of the Sylvester equation failed
C                    because the zeros of V (if JOBV = 'I') or of
C                    conj(V) (if JOBV = 'R') are not distinct from
C                    the poles of G1sr (see METHOD);
C             = 15:  the solution of the Sylvester equation failed
C                    because the zeros of W (if JOBW = 'I') or of
C                    conj(W) (if JOBW = 'R') are not distinct from
C                    the poles of G1sr (see METHOD);
C             = 16:  the solution of the generalized Sylvester system
C                    failed because the zeros of V (if JOBV = 'I') or
C                    of conj(V) (if JOBV = 'R') are not distinct from
C                    the poles of G1sr (see METHOD);
C             = 17:  the solution of the generalized Sylvester system
C                    failed because the zeros of W (if JOBW = 'I') or
C                    of conj(W) (if JOBW = 'R') are not distinct from
C                    the poles of G1sr (see METHOD);
C             = 18:  op(V) is not antistable;
C             = 19:  op(W) is not antistable;
C             = 20:  V is not invertible;
C             = 21:  W is not invertible.
C
C     METHOD
C
C     Let G be the transfer-function matrix of the original
C     linear system
C
C          d[x(t)] = Ax(t) + Bu(t)
C          y(t)    = Cx(t) + Du(t),                          (1)
C
C     where d[x(t)] is dx(t)/dt for a continuous-time system and x(t+1)
C     for a discrete-time system. The subroutine AB09JD determines
C     the matrices of a reduced order system
C
C          d[z(t)] = Ar*z(t) + Br*u(t)
C          yr(t)   = Cr*z(t) + Dr*u(t),                      (2)
C
C     such that the corresponding transfer-function matrix Gr minimizes
C     the Hankel-norm of the frequency-weighted error
C
C             op(V)*(G-Gr)*op(W).                            (3)
C
C     For minimizing (3) with op(V) = V and op(W) = W, V and W are
C     assumed to have poles distinct from those of G, while with
C     op(V) = conj(V) and op(W) = conj(W), conj(V) and conj(W) are
C     assumed to have poles distinct from those of G. For minimizing (3)
C     with op(V) = inv(V) and op(W) = inv(W), V and W are assumed to
C     have zeros distinct from the poles of G, while with
C     op(V) = conj(inv(V)) and op(W) = conj(inv(W)), conj(V) and conj(W)
C     are assumed to have zeros distinct from the poles of G.
C
C     Note: conj(G) = G'(-s) for a continuous-time system and
C           conj(G) = G'(1/z) for a discrete-time system.
C
C     The following procedure is used to reduce G (see [1]):
C
C     1) Decompose additively G as
C
C          G = G1 + G2,
C
C        such that G1 = (A1,B1,C1,D) has only ALPHA-stable poles and
C        G2 = (A2,B2,C2,0) has only ALPHA-unstable poles.
C
C     2) Compute G1s, the projection of op(V)*G1*op(W) containing the
C        poles of G1, using explicit formulas [4] or the inverse-free
C        descriptor system formulas of [5].
C
C     3) Determine G1sr, the optimal Hankel-norm approximation of G1s,
C        of order r.
C
C     4) Compute G1r, the projection of inv(op(V))*G1sr*inv(op(W))
C        containing the poles of G1sr, using explicit formulas [4]
C        or the inverse-free descriptor system formulas of [5].
C
C     5) Assemble the reduced model Gr as
C
C           Gr = G1r + G2.
C
C     To reduce the weighted ALPHA-stable part G1s at step 3, the
C     optimal Hankel-norm approximation method of [2], based on the
C     square-root balancing projection formulas of [3], is employed.
C
C     The optimal weighted approximation error satisfies
C
C          HNORM[op(V)*(G-Gr)*op(W)] >= S(r+1),
C
C     where S(r+1) is the (r+1)-th Hankel singular value of G1s, the
C     transfer-function matrix computed at step 2 of the above
C     procedure, and HNORM(.) denotes the Hankel-norm.
C
C     REFERENCES
C
C     [1] Latham, G.A. and Anderson, B.D.O.
C         Frequency-weighted optimal Hankel-norm approximation of stable
C         transfer functions.
C         Systems & Control Letters, Vol. 5, pp. 229-236, 1985.
C
C     [2] Glover, K.
C         All optimal Hankel norm approximation of linear
C         multivariable systems and their L-infinity error bounds.
C         Int. J. Control, Vol. 36, pp. 1145-1193, 1984.
C
C     [3] Tombs, M.S. and Postlethwaite, I.
C         Truncated balanced realization of stable, non-minimal
C         state-space systems.
C         Int. J. Control, Vol. 46, pp. 1319-1330, 1987.
C
C     [4] Varga, A.
C         Explicit formulas for an efficient implementation
C         of the frequency-weighting model reduction approach.
C         Proc. 1993 European Control Conference, Groningen, NL,
C         pp. 693-696, 1993.
C
C     [5] Varga, A.
C         Efficient and numerically reliable implementation of the
C         frequency-weighted Hankel-norm approximation model reduction
C         approach.
C         Proc. 2001 ECC, Porto, Portugal, 2001.
C
C     NUMERICAL ASPECTS
C
C     The implemented methods rely on an accuracy enhancing square-root
C     technique.
C
C     CONTRIBUTORS
C
C     A. Varga, German Aerospace Center, Oberpfaffenhofen, March 2001.
C     D. Sima, University of Bucharest, April 2001.
C     V. Sima, Research Institute for Informatics, Bucharest, Apr. 2001.
C
C     REVISIONS
C
C     A. Varga, German Aerospace Center, Oberpfaffenhofen, May 2001.
C     V. Sima, Research Institute for Informatics, Bucharest, June 2001,
C     March 2005.
C
C     KEYWORDS
C
C     Frequency weighting, model reduction, multivariable system,
C     state-space model, state-space representation.
C
C     ******************************************************************
C
C     .. Parameters ..
      DOUBLE PRECISION  C100, ONE, P0001, ZERO
      PARAMETER         ( C100 = 100.0D0, ONE = 1.0D0, P0001 = 0.0001D0,
     $                    ZERO = 0.0D0 )
C     .. Scalar Arguments ..
      CHARACTER         DICO, EQUIL, JOBINV, JOBV, JOBW, ORDSEL
      INTEGER           INFO, IWARN, LDA, LDAV, LDAW, LDB, LDBV, LDBW,
     $                  LDC, LDCV, LDCW, LDD, LDDV, LDDW, LDWORK, M, N,
     $                  NR, NS, NV, NW, P
      DOUBLE PRECISION  ALPHA, TOL1, TOL2
C     .. Array Arguments ..
      INTEGER           IWORK(*)
      DOUBLE PRECISION  A(LDA,*), AV(LDAV,*), AW(LDAW,*),
     $                  B(LDB,*), BV(LDBV,*), BW(LDBW,*),
     $                  C(LDC,*), CV(LDCV,*), CW(LDCW,*),
     $                  D(LDD,*), DV(LDDV,*), DW(LDDW,*), DWORK(*),
     $                  HSV(*)
C     .. Local Scalars ..
      CHARACTER         JOBVL, JOBWL
      LOGICAL           AUTOM, CONJV, CONJW, DISCR, FIXORD, INVFR,
     $                  LEFTI, LEFTW, RIGHTI, RIGHTW
      INTEGER           IERR, IWARNL, KAV, KAW, KBV, KBW, KCV, KCW, KDV,
     $                  KDW, KEV, KEW, KI, KL, KU, KW, LDABV, LDABW,
     $                  LDCDV, LDCDW, LW, NRA, NU, NU1, NVP, NWM, RANK
      DOUBLE PRECISION  ALPWRK, MAXRED, RCOND, SQREPS, TOL, WRKOPT
C     .. Local Arrays ..
      DOUBLE PRECISION  TEMP(1)
C     .. External Functions ..
      LOGICAL           LSAME
      DOUBLE PRECISION  DLAMCH
      EXTERNAL          DLAMCH, LSAME
C     .. External Subroutines ..
      EXTERNAL          AB07ND, AB08MD, AB09CX, AB09JV, AB09JW, AG07BD,
     $                  DLACPY, TB01ID, TB01KD, XERBLA
C     .. Intrinsic Functions ..
      INTRINSIC         DBLE, MAX, MIN, SQRT
C     .. Executable Statements ..
C
      INFO   = 0
      IWARN  = 0
      DISCR  = LSAME( DICO,   'D' )
      FIXORD = LSAME( ORDSEL, 'F' )
      LEFTI  = LSAME( JOBV, 'I' ) .OR. LSAME( JOBV, 'R' )
      LEFTW  = LSAME( JOBV, 'V' ) .OR. LSAME( JOBV, 'C' ) .OR. LEFTI
      CONJV  = LSAME( JOBV, 'C' ) .OR. LSAME( JOBV, 'R' )
      RIGHTI = LSAME( JOBW, 'I' ) .OR. LSAME( JOBW, 'R' )
      RIGHTW = LSAME( JOBW, 'W' ) .OR. LSAME( JOBW, 'C' ) .OR. RIGHTI
      CONJW  = LSAME( JOBW, 'C' ) .OR. LSAME( JOBW, 'R' )
      INVFR  = LSAME( JOBINV, 'N' )
      AUTOM  = LSAME( JOBINV, 'A' )
C
      LW = 1
      IF( LEFTW ) THEN
         NVP = NV + P
         LW  = MAX( LW, 2*NVP*( NVP + P ) + P*P +
     $              MAX( 2*NVP*NVP + MAX( 11*NVP + 16, P*NVP ),
     $                   NVP*N + MAX( NVP*N+N*N, P*N, P*M ) ) )
      END IF
      IF( RIGHTW ) THEN
         NWM = NW + M
         LW  = MAX( LW, 2*NWM*( NWM + M ) + M*M +
     $              MAX( 2*NWM*NWM + MAX( 11*NWM + 16, M*NWM ),
     $                   NWM*N + MAX( NWM*N+N*N, M*N, P*M ) ) )
      END IF
      LW = MAX( LW, N*( 2*N + MAX( N, M, P ) + 5 ) + ( N*( N + 1 ) )/2 )
      LW = MAX( LW, N*( M + P + 2 ) + 2*M*P + MIN( N, M ) +
     $                             MAX ( 3*M + 1, MIN( N, M ) + P ) )
C
C     Check the input scalar arguments.
C
      IF( .NOT. ( LSAME( JOBV, 'N' ) .OR. LEFTW ) ) THEN
         INFO = -1
      ELSE IF( .NOT. ( LSAME( JOBW, 'N' ) .OR. RIGHTW ) ) THEN
         INFO = -2
      ELSE IF( .NOT. ( INVFR .OR. AUTOM .OR. LSAME( JOBINV, 'I' ) ) )
     $   THEN
         INFO = -3
      ELSE IF( .NOT. ( LSAME( DICO, 'C' ) .OR. DISCR ) ) THEN
         INFO = -4
      ELSE IF( .NOT. ( LSAME( EQUIL, 'S' ) .OR.
     $                 LSAME( EQUIL, 'N' ) ) ) THEN
         INFO = -5
      ELSE IF( .NOT. ( FIXORD .OR. LSAME( ORDSEL, 'A' ) ) ) THEN
         INFO = -6
      ELSE IF( N.LT.0 ) THEN
         INFO = -7
      ELSE IF( NV.LT.0 ) THEN
         INFO = -8
      ELSE IF( NW.LT.0 ) THEN
         INFO = -9
      ELSE IF( M.LT.0 ) THEN
         INFO = -10
      ELSE IF( P.LT.0 ) THEN
         INFO = -11
      ELSE IF( FIXORD .AND. ( NR.LT.0 .OR. NR.GT.N ) ) THEN
         INFO = -12
      ELSE IF( ( DISCR .AND. ( ALPHA.LT.ZERO .OR. ALPHA.GT.ONE ) ) .OR.
     $    ( .NOT.DISCR .AND.   ALPHA.GT.ZERO ) ) THEN
         INFO = -13
      ELSE IF( LDA.LT.MAX( 1, N ) ) THEN
         INFO = -15
      ELSE IF( LDB.LT.MAX( 1, N ) ) THEN
         INFO = -17
      ELSE IF( LDC.LT.MAX( 1, P ) ) THEN
         INFO = -19
      ELSE IF( LDD.LT.MAX( 1, P ) ) THEN
         INFO = -21
      ELSE IF( LDAV.LT.1 .OR. ( LEFTW  .AND. LDAV.LT.NV ) ) THEN
         INFO = -23
      ELSE IF( LDBV.LT.1 .OR. ( LEFTW  .AND. LDBV.LT.NV ) ) THEN
         INFO = -25
      ELSE IF( LDCV.LT.1 .OR. ( LEFTW  .AND. LDCV.LT.P  ) ) THEN
         INFO = -27
      ELSE IF( LDDV.LT.1 .OR. ( LEFTW  .AND. LDDV.LT.P  ) ) THEN
         INFO = -29
      ELSE IF( LDAW.LT.1 .OR. ( RIGHTW .AND. LDAW.LT.NW ) ) THEN
         INFO = -31
      ELSE IF( LDBW.LT.1 .OR. ( RIGHTW .AND. LDBW.LT.NW ) ) THEN
         INFO = -33
      ELSE IF( LDCW.LT.1 .OR. ( RIGHTW .AND. LDCW.LT.M  ) ) THEN
         INFO = -35
      ELSE IF( LDDW.LT.1 .OR. ( RIGHTW .AND. LDDW.LT.M  ) ) THEN
         INFO = -37
      ELSE IF( TOL1.GE.ONE ) THEN
         INFO = -40
      ELSE IF( ( TOL2.GT.ZERO .AND. .NOT.FIXORD .AND. TOL2.GT.TOL1 )
     $      .OR. TOL2.GE.ONE ) THEN
         INFO = -41
      ELSE IF( LDWORK.LT.LW ) THEN
         INFO = -44
      END IF
C
      IF( INFO.NE.0 ) THEN
C
C        Error return.
C
         CALL XERBLA( 'AB09JD', -INFO )
         RETURN
      END IF
C
C     Quick return if possible.
C
      IF( MIN( N, M, P ).EQ.0 ) THEN
         NR = 0
         NS = 0
         DWORK(1) = ONE
         RETURN
      END IF
C
      IF( LSAME( EQUIL, 'S' ) ) THEN
C
C        Scale simultaneously the matrices A, B and C:
C        A <- inv(D)*A*D,  B <- inv(D)*B  and  C <- C*D,  where D is a
C        diagonal matrix.
C        Workspace: N.
C
         MAXRED = C100
         CALL TB01ID( 'All', N, M, P, MAXRED, A, LDA, B, LDB, C, LDC,
     $                DWORK, INFO )
      END IF
C
C     Correct the value of ALPHA to ensure stability.
C
      ALPWRK = ALPHA
      SQREPS = SQRT( DLAMCH( 'E' ) )
      IF( DISCR ) THEN
         IF( ALPHA.EQ.ONE ) ALPWRK = ONE - SQREPS
      ELSE
         IF( ALPHA.EQ.ZERO ) ALPWRK = -SQREPS
      END IF
C
C     Allocate working storage.
C
      KU = 1
      KL = KU + N*N
      KI = KL + N
      KW = KI + N
C
C     Compute an additive decomposition G = G1 + G2, where G1
C     is the ALPHA-stable projection of G.
C
C     Reduce A to a block-diagonal real Schur form, with the NU-th order
C     ALPHA-unstable part in the leading diagonal position, using a
C     non-orthogonal similarity transformation A <- inv(T)*A*T and
C     apply the transformation to B and C: B <- inv(T)*B and C <- C*T.
C
C     Workspace needed:      N*(N+2);
C     Additional workspace:  need   3*N;
C                            prefer larger.
C
      CALL TB01KD( DICO, 'Unstable', 'General', N, M, P, ALPWRK, A, LDA,
     $             B, LDB, C, LDC, NU, DWORK(KU), N, DWORK(KL),
     $             DWORK(KI), DWORK(KW), LDWORK-KW+1, IERR )
C
      IF( IERR.NE.0 ) THEN
         IF( IERR.NE.3 ) THEN
            INFO = 1
         ELSE
            INFO = 2
         END IF
         RETURN
      END IF
C
      WRKOPT = DWORK(KW) + DBLE( KW-1 )
      IWARNL = 0
C
      NS = N - NU
      IF( FIXORD ) THEN
         NRA = MAX( 0, NR-NU )
         IF( NR.LT.NU )
     $      IWARNL = 2
      ELSE
         NRA = 0
      END IF
C
C     Finish if only unstable part is present.
C
      IF( NS.EQ.0 ) THEN
         NR = NU
         DWORK(1) = WRKOPT
         RETURN
      END IF
C
      NU1 = NU + 1
      IF( CONJV ) THEN
         JOBVL = 'C'
      ELSE
         JOBVL = 'V'
      END IF
      IF( CONJW ) THEN
         JOBWL = 'C'
      ELSE
         JOBWL = 'W'
      END IF
      IF( LEFTW ) THEN
C
C        Check if V is invertible.
C        Real workspace:    need   (NV+P)**2 + MAX( P + MAX(3*P,NV),
C                                  MIN(P+1,NV) + MAX(3*(P+1),NV+P) );
C                           prefer larger.
C        Integer workspace: need   2*NV+P+2.
C
         TOL = ZERO
         CALL AB08MD( 'S', NV, P, P, AV, LDAV, BV, LDBV, CV, LDCV,
     $                DV, LDDV, RANK, TOL, IWORK, DWORK, LDWORK,
     $                IERR )
         IF( RANK.NE.P ) THEN
            INFO = 20
            RETURN
         END IF
         WRKOPT = MAX( WRKOPT, DWORK(1) )
C
         IF( LEFTI ) THEN
            IF( INVFR ) THEN
               IERR = 1
            ELSE
C
C              Allocate storage for a standard inverse of V.
C              Workspace: need  NV*(NV+2*P) + P*P.
C
               KAV = 1
               KBV = KAV + NV*NV
               KCV = KBV + NV*P
               KDV = KCV + P*NV
               KW  = KDV + P*P
C
               LDABV = MAX( NV, 1 )
               LDCDV = P
               CALL DLACPY( 'Full', NV, NV, AV, LDAV,
     $                      DWORK(KAV), LDABV )
               CALL DLACPY( 'Full', NV, P,  BV, LDBV,
     $                      DWORK(KBV), LDABV )
               CALL DLACPY( 'Full', P,  NV, CV, LDCV,
     $                      DWORK(KCV), LDCDV )
               CALL DLACPY( 'Full', P,  P,  DV, LDDV,
     $                      DWORK(KDV), LDCDV )
C
C              Compute the standard inverse of V.
C              Additional real workspace:   need   MAX(1,4*P);
C                                           prefer larger.
C              Integer workspace:           need   2*P.
C
               CALL AB07ND( NV, P, DWORK(KAV), LDABV, DWORK(KBV), LDABV,
     $                      DWORK(KCV), LDCDV, DWORK(KDV), LDCDV,
     $                      RCOND, IWORK, DWORK(KW), LDWORK-KW+1, IERR )
               WRKOPT = MAX( WRKOPT, DWORK(KW) + DBLE( KW-1 ) )
C
C              Check if inversion is accurate.
C
               IF( AUTOM ) THEN
                  IF( IERR.EQ.0 .AND. RCOND.LE.P0001  ) IERR = 1
               ELSE
                  IF( IERR.EQ.0 .AND. RCOND.LE.SQREPS ) IERR = 1
               END IF
               IF( IERR.NE.0 .AND. NV.EQ.0 ) THEN
                  INFO = 20
                  RETURN
               END IF
            END IF
C
            IF( IERR.NE.0 ) THEN
C
C              Allocate storage for a descriptor inverse of V.
C
               KAV = 1
               KEV = KAV + NVP*NVP
               KBV = KEV + NVP*NVP
               KCV = KBV + NVP*P
               KDV = KCV + P*NVP
               KW  = KDV + P*P
C
               LDABV = MAX( NVP, 1 )
               LDCDV = P
C
C              DV is singular or ill-conditioned.
C              Form a descriptor inverse of V.
C              Workspace: need  2*(NV+P)*(NV+2*P) + P*P.
C
               CALL AG07BD( 'I', NV, P, AV, LDAV, TEMP, 1, BV, LDBV,
     $                      CV, LDCV, DV, LDDV, DWORK(KAV), LDABV,
     $                      DWORK(KEV), LDABV, DWORK(KBV), LDABV,
     $                      DWORK(KCV), LDCDV, DWORK(KDV), LDCDV, IERR )
C
C              Compute the projection containing the poles of weighted
C              reduced ALPHA-stable part using descriptor inverse of V
C              of order NVP = NV + P.
C              Additional real workspace: need
C                 MAX( 2*NVP*NVP + MAX( 11*NVP+16, P*NVP ),
C                      NVP*N + MAX( NVP*N+N*N, P*N, P*M ) );
C                 prefer larger.
C              Integer workspace: need NVP+N+6.
C
               CALL AB09JV( JOBVL, DICO, 'G', 'C', NS, M, P, NVP, P,
     $                      A(NU1,NU1), LDA, B(NU1,1), LDB,
     $                      C(1,NU1), LDC, D, LDD,
     $                      DWORK(KAV), LDABV, DWORK(KEV), LDABV,
     $                      DWORK(KBV), LDABV, DWORK(KCV), LDCDV,
     $                      DWORK(KDV), LDCDV, IWORK, DWORK(KW),
     $                      LDWORK-KW+1, IERR )
               IF( IERR.NE.0 ) THEN
                  IF( IERR.EQ.1 ) THEN
                     INFO = 5
                  ELSE IF( IERR.EQ.2 ) THEN
                     INFO = 16
                  ELSE IF( IERR.EQ.4 ) THEN
                     INFO = 18
                  END IF
                  RETURN
               END IF
            ELSE
C
C              Compute the projection containing the poles of weighted
C              reduced ALPHA-stable part using explicit inverse of V.
C              Additional real workspace: need
C                 MAX( NV*(NV+5), NV*N + MAX( a, P*N, P*M ) )
C                      a = 0,    if DICO = 'C' or  JOBVL = 'V',
C                      a = 2*NV, if DICO = 'D' and JOBVL = 'C';
C                 prefer larger.
C
               CALL AB09JV( JOBVL, DICO, 'I', 'C', NS, M, P, NV, P,
     $                      A(NU1,NU1), LDA, B(NU1,1), LDB,
     $                      C(1,NU1), LDC, D, LDD, DWORK(KAV), LDABV,
     $                      TEMP, 1, DWORK(KBV), LDABV,
     $                      DWORK(KCV), LDCDV, DWORK(KDV), LDCDV, IWORK,
     $                      DWORK(KW), LDWORK-KW+1, IERR )
               IF( IERR.NE.0 ) THEN
                  IF( IERR.EQ.1 ) THEN
                     INFO = 10
                  ELSE IF( IERR.EQ.3 ) THEN
                     INFO = 14
                  ELSE IF( IERR.EQ.4 ) THEN
                     INFO = 18
                  END IF
                  RETURN
               END IF
            END IF
C
            WRKOPT = MAX( WRKOPT, DWORK(KW) + DBLE( KW - 1 ) )
         ELSE
C
C           Compute the projection of V*G1 or conj(V)*G1 containing the
C           poles of G.
C
C           Workspace need:
C           real   MAX( 1, NV*(NV+5), NV*N + MAX( a, P*N, P*M ) )
C                       a = 0,    if DICO = 'C' or  JOBVL = 'V',
C                       a = 2*NV, if DICO = 'D' and JOBVL = 'C';
C           prefer larger.
C
            CALL AB09JV( JOBVL, DICO, 'I', 'C', NS, M, P, NV, P,
     $                   A(NU1,NU1), LDA, B(NU1,1), LDB,
     $                   C(1,NU1), LDC, D, LDD, AV, LDAV,
     $                   TEMP, 1, BV, LDBV, CV, LDCV, DV, LDDV, IWORK,
     $                   DWORK, LDWORK, IERR )
            IF( IERR.NE.0 ) THEN
               IF( IERR.EQ.1 ) THEN
                  INFO = 3
               ELSE IF( IERR.EQ.3 ) THEN
                  INFO = 12
               ELSE IF( IERR.EQ.4 ) THEN
                  INFO = 18
               END IF
               RETURN
            END IF
C
            WRKOPT = MAX( WRKOPT, DWORK(1) )
         END IF
      END IF
C
      IF( RIGHTW ) THEN
C
C        Check if W is invertible.
C        Real workspace:    need   (NW+M)**2 + MAX( M + MAX(3*M,NW),
C                                  MIN(M+1,NW) + MAX(3*(M+1),NW+M) );
C                           prefer larger.
C        Integer workspace: need   2*NW+M+2.
C
         TOL = ZERO
         CALL AB08MD( 'S', NW, M, M, AW, LDAW, BW, LDBW, CW, LDCW,
     $                DW, LDDW, RANK, TOL, IWORK, DWORK, LDWORK,
     $                IERR )
         IF( RANK.NE.M ) THEN
            INFO = 21
            RETURN
         END IF
         WRKOPT = MAX( WRKOPT, DWORK(1) )
C
         IF( RIGHTI ) THEN
            IF( INVFR ) THEN
               IERR = 1
            ELSE
C
C              Allocate storage for a standard inverse of W.
C              Workspace: need  NW*(NW+2*M) + M*M.
C
               KAW = 1
               KBW = KAW + NW*NW
               KCW = KBW + NW*M
               KDW = KCW + M*NW
               KW  = KDW + M*M
C
               LDABW = MAX( NW, 1 )
               LDCDW = M
               CALL DLACPY( 'Full', NW, NW, AW, LDAW,
     $                      DWORK(KAW), LDABW )
               CALL DLACPY( 'Full', NW, M,  BW, LDBW,
     $                      DWORK(KBW), LDABW )
               CALL DLACPY( 'Full', M,  NW, CW, LDCW,
     $                      DWORK(KCW), LDCDW )
               CALL DLACPY( 'Full', M,  M,  DW, LDDW,
     $                      DWORK(KDW), LDCDW )
C
C              Compute the standard inverse of W.
C              Additional real workspace:   need   MAX(1,4*M);
C                                           prefer larger.
C              Integer workspace:           need   2*M.
C
               CALL AB07ND( NW, M, DWORK(KAW), LDABW, DWORK(KBW), LDABW,
     $                      DWORK(KCW), LDCDW, DWORK(KDW), LDCDW,
     $                      RCOND, IWORK, DWORK(KW), LDWORK-KW+1, IERR )
               WRKOPT = MAX( WRKOPT, DWORK(KW) + DBLE( KW-1 ) )
C
C              Check if inversion is accurate.
C
               IF( AUTOM ) THEN
                  IF( IERR.EQ.0 .AND. RCOND.LE.P0001  ) IERR = 1
               ELSE
                  IF( IERR.EQ.0 .AND. RCOND.LE.SQREPS ) IERR = 1
               END IF
               IF( IERR.NE.0 .AND. NW.EQ.0 ) THEN
                  INFO = 21
                  RETURN
               END IF
            END IF
C
            IF( IERR.NE.0 ) THEN
C
C              Allocate storage for a descriptor inverse of W.
C
               KAW = 1
               KEW = KAW + NWM*NWM
               KBW = KEW + NWM*NWM
               KCW = KBW + NWM*M
               KDW = KCW + M*NWM
               KW  = KDW + M*M
C
               LDABW = MAX( NWM, 1 )
               LDCDW = M
C
C              DW is singular or ill-conditioned.
C              Form the descriptor inverse of W.
C              Workspace: need  2*(NW+M)*(NW+2*M) + M*M.
C
               CALL AG07BD( 'I', NW, M, AW, LDAW, TEMP, 1, BW, LDBW,
     $                      CW, LDCW, DW, LDDW, DWORK(KAW), LDABW,
     $                      DWORK(KEW), LDABW, DWORK(KBW), LDABW,
     $                      DWORK(KCW), LDCDW, DWORK(KDW), LDCDW, IERR )
C
C              Compute the projection containing the poles of weighted
C              reduced ALPHA-stable part using descriptor inverse of W
C              of order NWM = NW + M.
C              Additional real workspace: need
C                 MAX( 2*NWM*NWM + MAX( 11*NWM+16, M*NWM ),
C                      NWM*N + MAX( NWM*N+N*N, M*N, P*M ) );
C                 prefer larger.
C              Integer workspace: need NWM+N+6.
C
               CALL AB09JW( JOBWL, DICO, 'G', 'C', NS, M, P, NWM, M,
     $                      A(NU1,NU1), LDA, B(NU1,1), LDB,
     $                      C(1,NU1), LDC, D, LDD, DWORK(KAW), LDABW,
     $                      DWORK(KEW), LDABW, DWORK(KBW), LDABW,
     $                      DWORK(KCW), LDCDW, DWORK(KDW), LDCDW,
     $                      IWORK, DWORK(KW), LDWORK-KW+1, IERR )
               IF( IERR.NE.0 ) THEN
                  IF( IERR.EQ.1 ) THEN
                     INFO = 6
                  ELSE IF( IERR.EQ.2 ) THEN
                     INFO = 17
                  ELSE IF( IERR.EQ.4 ) THEN
                     INFO = 19
                  END IF
                  RETURN
               END IF
            ELSE
C
C              Compute the projection containing the poles of weighted
C              reduced ALPHA-stable part using explicit inverse of W.
C              Additional real workspace: need
C                 MAX( NW*(NW+5), NW*N + MAX( a, M*N, P*M ) )
C                      a = 0,    if DICO = 'C' or  JOBWL = 'W',
C                      a = 2*NW, if DICO = 'D' and JOBWL = 'C';
C                 prefer larger.
C
               CALL AB09JW( JOBWL, DICO, 'I', 'C', NS, M, P, NW, M,
     $                      A(NU1,NU1), LDA, B(NU1,1), LDB,
     $                      C(1,NU1), LDC, D, LDD, DWORK(KAW), LDABW,
     $                      TEMP, 1, DWORK(KBW), LDABW,
     $                      DWORK(KCW), LDCDW, DWORK(KDW), LDCDW,
     $                      IWORK, DWORK(KW), LDWORK-KW+1, IERR )
               IF( IERR.NE.0 ) THEN
                  IF( IERR.EQ.1 ) THEN
                     INFO = 11
                  ELSE IF( IERR.EQ.3 ) THEN
                     INFO = 15
                  ELSE IF( IERR.EQ.4 ) THEN
                     INFO = 19
                  END IF
                  RETURN
               END IF
            END IF
C
            WRKOPT = MAX( WRKOPT, DWORK(KW) + DBLE( KW - 1 ) )
         ELSE
C
C           Compute the projection G1s of V*G1*W or conj(V)*G1*conj(W)
C           containing the poles of G.
C
C           Workspace need:
C           real   MAX( 1, NW*(NW+5), NW*N + MAX( b, M*N, P*M ) )
C                    b = 0,    if DICO = 'C' or  JOBWL = 'W',
C                    b = 2*NW, if DICO = 'D' and JOBWL = 'C';
C           prefer larger.
C
            CALL AB09JW( JOBWL, DICO, 'I', 'C', NS, M, P, NW, M,
     $                   A(NU1,NU1), LDA, B(NU1,1), LDB, C(1,NU1), LDC,
     $                   D, LDD, AW, LDAW, TEMP, 1, BW, LDBW, CW, LDCW,
     $                   DW, LDDW, IWORK, DWORK, LDWORK, IERR )
            IF( IERR.NE.0 ) THEN
               IF( IERR.EQ.1 ) THEN
                  INFO = 4
               ELSE IF( IERR.EQ.3 ) THEN
                  INFO = 13
               ELSE IF( IERR.EQ.4 ) THEN
                  INFO = 19
               END IF
               RETURN
            END IF
C
            WRKOPT = MAX( WRKOPT, DWORK(1) )
         END IF
      END IF
C
C     Determine a reduced order approximation G1sr of G1s using the
C     Hankel-norm approximation method. The resulting A(NU1:N,NU1:N)
C     is further in a real Schur form.
C
C     Workspace: need   MAX( LDW3, LDW4 ),
C                LDW3 = N*(2*N + MAX(N,M,P) + 5) + N*(N+1)/2,
C                LDW4 = N*(M+P+2) + 2*M*P + MIN(N,M) +
C                       MAX( 3*M+1, MIN(N,M)+P );
C                prefer larger.
C
      CALL AB09CX( DICO, ORDSEL, NS, M, P, NRA, A(NU1,NU1), LDA,
     $             B(NU1,1), LDB, C(1,NU1), LDC, D, LDD, HSV, TOL1,
     $             TOL2, IWORK, DWORK, LDWORK, IWARN, IERR )
C
      IF( IERR.NE.0 ) THEN
C
C        Set INFO = 7, 8 or 9.
C
         INFO = IERR + 5
         RETURN
      END IF
C
      IWARN  = MAX( IWARNL, IWARN )
      WRKOPT = MAX( WRKOPT, DWORK(1) )
C
      IF( LEFTW ) THEN
         IF( .NOT.LEFTI ) THEN
            IF( INVFR ) THEN
               IERR = 1
            ELSE
C
C              Allocate storage for a standard inverse of V.
C              Workspace: need  NV*(NV+2*P) + P*P.
C
               KAV = 1
               KBV = KAV + NV*NV
               KCV = KBV + NV*P
               KDV = KCV + P*NV
               KW  = KDV + P*P
C
               LDABV = MAX( NV, 1 )
               LDCDV = P
               CALL DLACPY( 'Full', NV, NV, AV, LDAV,
     $                      DWORK(KAV), LDABV )
               CALL DLACPY( 'Full', NV, P,  BV, LDBV,
     $                      DWORK(KBV), LDABV )
               CALL DLACPY( 'Full', P,  NV, CV, LDCV,
     $                      DWORK(KCV), LDCDV )
               CALL DLACPY( 'Full', P,  P,  DV, LDDV,
     $                      DWORK(KDV), LDCDV )
C
C              Compute the standard inverse of V.
C              Additional real workspace:   need   MAX(1,4*P);
C                                           prefer larger.
C              Integer workspace:           need   2*P.
C
               CALL AB07ND( NV, P, DWORK(KAV), LDABV, DWORK(KBV), LDABV,
     $                      DWORK(KCV), LDCDV, DWORK(KDV), LDCDV,
     $                      RCOND, IWORK, DWORK(KW), LDWORK-KW+1, IERR )
               WRKOPT = MAX( WRKOPT, DWORK(KW) + DBLE( KW-1 ) )
C
C              Check if inversion is accurate.
C
               IF( AUTOM ) THEN
                  IF( IERR.EQ.0 .AND. RCOND.LE.P0001  ) IERR = 1
               ELSE
                  IF( IERR.EQ.0 .AND. RCOND.LE.SQREPS ) IERR = 1
               END IF
               IF( IERR.NE.0 .AND. NV.EQ.0 ) THEN
                  INFO = 20
                  RETURN
               END IF
            END IF
C
            IF( IERR.NE.0 ) THEN
C
C              Allocate storage for a descriptor inverse of V.
C
               KAV = 1
               KEV = KAV + NVP*NVP
               KBV = KEV + NVP*NVP
               KCV = KBV + NVP*P
               KDV = KCV + P*NVP
               KW  = KDV + P*P
C
               LDABV = MAX( NVP, 1 )
               LDCDV = P
C
C              DV is singular or ill-conditioned.
C              Form a descriptor inverse of V.
C              Workspace: need  2*(NV+P)*(NV+2*P) + P*P.
C
               CALL AG07BD( 'I', NV, P, AV, LDAV, TEMP, 1, BV, LDBV,
     $                      CV, LDCV, DV, LDDV, DWORK(KAV), LDABV,
     $                      DWORK(KEV), LDABV, DWORK(KBV), LDABV,
     $                      DWORK(KCV), LDCDV, DWORK(KDV), LDCDV, IERR )
C
C              Compute the projection containing the poles of weighted
C              reduced ALPHA-stable part using descriptor inverse of V
C              of order NVP = NV + P.
C              Additional real workspace: need
C                 MAX( 2*NVP*NVP + MAX( 11*NVP+16, P*NVP ),
C                      NVP*N + MAX( NVP*N+N*N, P*N, P*M ) );
C                 prefer larger.
C              Integer workspace: need NVP+N+6.
C
               CALL AB09JV( JOBVL, DICO, 'G', 'N', NRA, M, P, NVP, P,
     $                      A(NU1,NU1), LDA, B(NU1,1), LDB,
     $                      C(1,NU1), LDC, D, LDD,
     $                      DWORK(KAV), LDABV, DWORK(KEV), LDABV,
     $                      DWORK(KBV), LDABV, DWORK(KCV), LDCDV,
     $                      DWORK(KDV), LDCDV, IWORK, DWORK(KW),
     $                      LDWORK-KW+1, IERR )
               IF( IERR.NE.0 ) THEN
                  IF( IERR.EQ.1 ) THEN
                     INFO = 5
                  ELSE IF( IERR.EQ.2 ) THEN
                     INFO = 16
                  END IF
                  RETURN
               END IF
            ELSE
C
C              Compute the projection containing the poles of weighted
C              reduced ALPHA-stable part using explicit inverse of V.
C              Additional real workspace: need
C                 MAX( NV*(NV+5), NV*N + MAX( a, P*N, P*M ) )
C                      a = 0,    if DICO = 'C' or  JOBVL = 'V',
C                      a = 2*NV, if DICO = 'D' and JOBVL = 'C';
C                 prefer larger.
C
               CALL AB09JV( JOBVL, DICO, 'I', 'N', NRA, M, P, NV, P,
     $                      A(NU1,NU1), LDA, B(NU1,1), LDB,
     $                      C(1,NU1), LDC, D, LDD, DWORK(KAV), LDABV,
     $                      TEMP, 1, DWORK(KBV), LDABV,
     $                      DWORK(KCV), LDCDV, DWORK(KDV), LDCDV, IWORK,
     $                      DWORK(KW), LDWORK-KW+1, IERR )
               IF( IERR.NE.0 ) THEN
                  IF( IERR.EQ.1 ) THEN
                     INFO = 10
                  ELSE IF( IERR.EQ.3 ) THEN
                     INFO = 14
                  END IF
                  RETURN
               END IF
            END IF
C
            WRKOPT = MAX( WRKOPT, DWORK(KW) + DBLE( KW - 1 ) )
         ELSE
C
C           Compute the projection of V*G1sr or conj(V)*G1sr containing
C           the poles of G.
C
C           Workspace need:
C           real    MAX( 1, NV*(NV+5), NV*N + MAX( a, P*N, P*M ) )
C                        a = 0,    if DICO = 'C' or  JOBVL = 'V',
C                        a = 2*NV, if DICO = 'D' and JOBVL = 'C';
C           prefer larger.
C
            CALL AB09JV( JOBVL, DICO, 'I', 'N', NRA, M, P, NV, P,
     $                   A(NU1,NU1), LDA, B(NU1,1), LDB,
     $                   C(1,NU1), LDC, D, LDD, AV, LDAV,
     $                   TEMP, 1, BV, LDBV, CV, LDCV, DV, LDDV, IWORK,
     $                   DWORK, LDWORK, IERR )
            IF( IERR.NE.0 ) THEN
               IF( IERR.EQ.1 ) THEN
                  INFO = 3
               ELSE IF( IERR.EQ.3 ) THEN
                  INFO = 12
               END IF
               RETURN
            END IF
C
            WRKOPT = MAX( WRKOPT, DWORK(1) )
         END IF
      END IF
C
      IF( RIGHTW ) THEN
         IF( .NOT.RIGHTI ) THEN
            IF( INVFR ) THEN
               IERR = 1
            ELSE
C
C              Allocate storage for a standard inverse of W.
C              Workspace: need  NW*(NW+2*M) + M*M.
C
               KAW = 1
               KBW = KAW + NW*NW
               KCW = KBW + NW*M
               KDW = KCW + M*NW
               KW  = KDW + M*M
C
               LDABW = MAX( NW, 1 )
               LDCDW = M
               CALL DLACPY( 'Full', NW, NW, AW, LDAW,
     $                      DWORK(KAW), LDABW )
               CALL DLACPY( 'Full', NW, M,  BW, LDBW,
     $                      DWORK(KBW), LDABW )
               CALL DLACPY( 'Full', M,  NW, CW, LDCW,
     $                      DWORK(KCW), LDCDW )
               CALL DLACPY( 'Full', M,  M,  DW, LDDW,
     $                      DWORK(KDW), LDCDW )
C
C              Compute the standard inverse of W.
C              Additional real workspace:   need   MAX(1,4*M);
C                                           prefer larger.
C              Integer workspace:           need   2*M.
C
               CALL AB07ND( NW, M, DWORK(KAW), LDABW, DWORK(KBW), LDABW,
     $                      DWORK(KCW), LDCDW, DWORK(KDW), LDCDW,
     $                      RCOND, IWORK, DWORK(KW), LDWORK-KW+1, IERR )
               WRKOPT = MAX( WRKOPT, DWORK(KW) + DBLE( KW-1 ) )
C
C              Check if inversion is accurate.
C
               IF( AUTOM ) THEN
                  IF( IERR.EQ.0 .AND. RCOND.LE.P0001  ) IERR = 1
               ELSE
                  IF( IERR.EQ.0 .AND. RCOND.LE.SQREPS ) IERR = 1
               END IF
               IF( IERR.NE.0 .AND. NW.EQ.0 ) THEN
                  INFO = 21
                  RETURN
               END IF
            END IF
C
            IF( IERR.NE.0 ) THEN
C
C              Allocate storage for a descriptor inverse of W.
C
               KAW = 1
               KEW = KAW + NWM*NWM
               KBW = KEW + NWM*NWM
               KCW = KBW + NWM*M
               KDW = KCW + M*NWM
               KW  = KDW + M*M
C
               LDABW = MAX( NWM, 1 )
               LDCDW = M
C
C              DW is singular or ill-conditioned.
C              Form the descriptor inverse of W.
C              Workspace: need  2*(NW+M)*(NW+2*M) + M*M.
C
               CALL AG07BD( 'I', NW, M, AW, LDAW, TEMP, 1, BW, LDBW,
     $                      CW, LDCW, DW, LDDW, DWORK(KAW), LDABW,
     $                      DWORK(KEW), LDABW, DWORK(KBW), LDABW,
     $                      DWORK(KCW), LDCDW, DWORK(KDW), LDCDW, IERR )
C
C              Compute the projection containing the poles of weighted
C              reduced ALPHA-stable part using descriptor inverse of W
C              of order NWM = NW + M.
C              Additional real workspace: need
C                 MAX( 2*NWM*NWM + MAX( 11*NWM+16, M*NWM ),
C                      NWM*N + MAX( NWM*N+N*N, M*N, P*M ) );
C                 prefer larger.
C              Integer workspace: need NWM+N+6.
C
               CALL AB09JW( JOBWL, DICO, 'G', 'N', NRA, M, P, NWM, M,
     $                      A(NU1,NU1), LDA, B(NU1,1), LDB,
     $                      C(1,NU1), LDC, D, LDD, DWORK(KAW), LDABW,
     $                      DWORK(KEW), LDABW, DWORK(KBW), LDABW,
     $                      DWORK(KCW), LDCDW, DWORK(KDW), LDCDW,
     $                      IWORK, DWORK(KW), LDWORK-KW+1, IERR )
               IF( IERR.NE.0 ) THEN
                  IF( IERR.EQ.1 ) THEN
                     INFO = 6
                  ELSE IF( IERR.EQ.2 ) THEN
                     INFO = 17
                  END IF
                  RETURN
               END IF
            ELSE
C
C              Compute the projection containing the poles of weighted
C              reduced ALPHA-stable part using explicit inverse of W.
C              Additional real workspace: need
C                 MAX( NW*(NW+5), NW*N + MAX( a, M*N, P*M ) )
C                      a = 0,    if DICO = 'C' or  JOBWL = 'W',
C                      a = 2*NW, if DICO = 'D' and JOBWL = 'C';
C                 prefer larger.
C
               CALL AB09JW( JOBWL, DICO, 'I', 'N', NRA, M, P, NW, M,
     $                      A(NU1,NU1), LDA, B(NU1,1), LDB,
     $                      C(1,NU1), LDC, D, LDD, DWORK(KAW), LDABW,
     $                      TEMP, 1, DWORK(KBW), LDABW,
     $                      DWORK(KCW), LDCDW, DWORK(KDW), LDCDW,
     $                      IWORK, DWORK(KW), LDWORK-KW+1, IERR )
               IF( IERR.NE.0 ) THEN
                  IF( IERR.EQ.1 ) THEN
                     INFO = 11
                  ELSE IF( IERR.EQ.3 ) THEN
                     INFO = 15
                  END IF
                  RETURN
               END IF
            END IF
C
            WRKOPT = MAX( WRKOPT, DWORK(KW) + DBLE( KW - 1 ) )
         ELSE
C
C           Compute the projection G1r of V*G1sr*W or
C           conj(V)*G1sr*conj(W) containing the poles of G.
C
C           Workspace need:
C           real   MAX( 1, NW*(NW+5), NW*N + MAX( b, M*N, P*M ) )
C                    b = 0,    if DICO = 'C' or  JOBWL = 'W',
C                    b = 2*NW, if DICO = 'D' and JOBWL = 'C';
C           prefer larger.
C
            CALL AB09JW( JOBWL, DICO, 'I', 'N', NRA, M, P, NW, M,
     $                   A(NU1,NU1), LDA, B(NU1,1), LDB, C(1,NU1), LDC,
     $                   D, LDD, AW, LDAW, TEMP, 1, BW, LDBW, CW, LDCW,
     $                   DW, LDDW, IWORK, DWORK, LDWORK, IERR )
C
            IF( IERR.NE.0 ) THEN
               IF( IERR.EQ.1 ) THEN
                  INFO = 4
               ELSE IF( IERR.EQ.3 ) THEN
                  INFO = 13
               END IF
               RETURN
            END IF
C
            WRKOPT = MAX( WRKOPT, DWORK(1) )
         END IF
      END IF
C
      NR = NRA + NU
      DWORK(1) = WRKOPT
C
      RETURN
C *** Last line of AB09JD ***
      END


! mpiexec -np 4 bin/Debug/WGFM_test2.exe
program matrices_test
    use meshread_mod
    use EFIE_RWG_matrices
    use MFIEDuffy_functions
    use linalg_mod
    use spherePEC_mod
    use WMFIE_matrices
    use WGFM_matrices
    use mpi
    implicit none

    real(8), parameter :: pi = 4d0 * atan(1d0)
    complex(8), parameter :: IU = (0d0, 1d0)

    ! Variables
    type(Mesh) :: msh
    integer, parameter :: nNS = 6           ! number of quadrature points for EFIE

    complex(8), allocatable :: K1Mat(:, :)   ! MFIE K_1 operator
    complex(8), allocatable :: K2Mat(:, :)   ! MFIE K_2 operator
    complex(8), allocatable :: T1Mat(:, :)   ! EFIE T_1 operator
    complex(8), allocatable :: T2Mat(:, :)   ! EFIE T_2 operator

    complex(8), allocatable :: A1(:, :)
    complex(8), allocatable :: A2(:, :)
    complex(8), allocatable :: A3(:, :)
    complex(8), allocatable :: Z1(:, :)
    complex(8), allocatable :: Z2(:, :)
    complex(8), allocatable :: Z3(:, :)

    ! MPI variables
    integer :: ierr, N_procs, id

    ! Parameters
    real(8), parameter :: ep0 = 1d0 / (35950207149.4727056d0 * PI)  ! vacuum permittivity [F/m]
    real(8), parameter :: mu0 = PI * 4d-7                           ! vacuum permeability [H/m]

    real(8), parameter :: k = 0.1d0 * PI          ! free-space wavenumber [1/m]
    real(8), parameter :: ep1 = ep0             ! upper half-space permittivity [F/m]
    real(8), parameter :: mu1 = mu0             ! upper half-space permeability [H/m]
    real(8), parameter :: ep2 = ep0 * 2.5d0     ! lower half-space permittivity [F/m]
    real(8), parameter :: mu2 = mu0 * 5.3       ! lower half-space permeability [H/m]

    real(8), parameter :: w = k / sqrt(ep0 * mu0)   ! angular frequency [rad/s]
    real(8), parameter :: k1 = w * sqrt(ep1 * mu1)  ! upper half-space wavenumber [1/m]
    real(8), parameter :: k2 = w * sqrt(ep2 * mu2)  ! lower half-space wavenumber [1/m]

    character(len=100) :: file_msh = 'meshes/half_sphere_plane/half_sphere_plane_a5_h04_t20.msh'
    !character(len=100) :: file_msh = 'meshes/convergence_sphere/simple_mesh.msh'

    ! Set window (just to test the program)
    call set_circ_window(Lr=4d0, c_in=0.7d0)

    ! MPI init
    call mpi_init(ierr)
    call mpi_comm_size(MPI_COMM_WORLD, N_procs, ierr)
    call mpi_comm_rank(MPI_COMM_WORLD, id, ierr)
    print *, "Total processes:", N_procs, "Process id:", id

    ! Load mesh
    call load_gmsh(file_msh, msh)

    ! Compute MFIE matrices
    if (id == 0) print *, "MFIE"
    call genMFIESauterSchwabMat(K1Mat, msh, k1)
    call genMFIESauterSchwabMat(K2Mat, msh, k2)

    ! Compute EFIE matrices
    if (id == 0) print *, "EFIE"
    call genEFIESauterSchwabMat_RWG(T1Mat, msh, k1, nNS, nNS)
    call genEFIESauterSchwabMat_RWG(T2Mat, msh, k2, nNS, nNS)

    ! Compute WGFM matrices
    if (id == 0) print *, "WGFM"
    call genWGFMMat(msh, k1, k2, ep1, ep2, mu1, mu2, Z1, Z2, Z3)

    if (id == 0) then
        ! Compute WGFM matrices
        allocate(A1(msh%nbEdg, msh%nbEdg))
        allocate(A2(msh%nbEdg, msh%nbEdg))
        allocate(A3(msh%nbEdg, msh%nbEdg))
        A1 = mu2 * K2Mat - mu1 * K1Mat
        A2 = k2**2 * T2Mat - k1**2 * T1Mat
        A3 = ep2 * K2Mat - ep1 * K1Mat

        ! Compute matrices norm
        print *, "size", msh%nbEdg
        print *, "k", k
        print *, "w", w
        print *, "A1", sqrt(sum(abs(A1) ** 2))
        print *, "A2", sqrt(sum(abs(A2) ** 2))
        print *, "A3", sqrt(sum(abs(A3) ** 2))
        print *, "Z1", sqrt(sum(abs(Z1) ** 2))
        print *, "Z2", sqrt(sum(abs(Z2) ** 2))
        print *, "Z3", sqrt(sum(abs(Z3) ** 2))
        print *, "A1-Z1", sqrt(sum(abs(A1-Z1) ** 2))
        print *, "A2-Z2", sqrt(sum(abs(A2-Z2) ** 2))
        print *, "A3-Z3", sqrt(sum(abs(A3-Z3) ** 2))

    end if

    call MPI_Finalize(ierr)
end program


program potential
 implicit none
 integer::i,j,n =108
 real(8)::rx(200),ry(200),rz(200),boxl,sigsq,epslon,rxij,ryij,rzij,rijsq,sr2,sr6,sr12,rcutoffsq,rcutoff,v,sig,kb,a

 dimension a(200,200)
 open(1,file='argon2.init')
 do  i=1,n
  read(1,*) (a(i,j),j=1,3)
  write(10,*)(a(i,j),j=1,3)
  rx(i) =a(i,1)
  ry(i) =a(i,2)
  rz(i) =a(i,3)

 end do

 boxl =17.158d0
 sig = 3.405d0
 sigsq = sig * sig
 kb = 1.38E-23
 epslon = 120.0d0 !* kb

 rcutoff = 0.50d0 * boxl
 rcutoffsq = rcutoff * rcutoff

 do i=1,n
  rx(i) = rx(i) - (boxl * anint(rx(i)/boxl))
  ry(i) = ry(i) - (boxl * anint(ry(i)/boxl))
  rz(i) = rz(i) - (boxl * anint(rz(i)/boxl))
 end do

 v=0.0d0
 do i=1,n-1
  do j=i+1,n
   rxij = rx(i) - rx(j)
   ryij = ry(i) - ry(j)
   rzij = rz(i) - rz(j)

   rxij = rxij - (boxl * anint(rxij/boxl))
   ryij = ryij - (boxl * anint(ryij/boxl))
   rzij = rzij - (boxl * anint(rzij/boxl))
  !write(18,*)rxij,ryij,rzij

   rijsq = rxij**2 + ryij**2 + rzij**2
  !write(19,*)rijsq
   sr2 = sigsq/rijsq
   sr6 = sr2 * sr2 * sr2
   sr12 = sr6 * sr6
   if(rijsq<rcutoffsq) then
    v = v + sr12 -sr6
   endif
  end do
 end do
 v = 4.0d0*epslon*v
 write(*,*)v

 end


module operator_overloading_01_overload_comp_m
    implicit none
    public operator (>)

    interface operator (>)
        module procedure greater_than_inverse
    end interface

    interface operator (<)
        module procedure less_than_inverse
    end interface
contains
    pure logical function greater_than_inverse(log1, log2)
        logical, intent (in) :: log1, log2

        if( log1 .eqv. .true. .and. log2 .eqv. .false. ) then
            greater_than_inverse = .true.
        else
            greater_than_inverse = .false.
        end if
    end function

    pure logical function less_than_inverse(log1, log2)
        logical, intent (in) :: log1, log2

        if( log1 .eqv. .false. .and. log2 .eqv. .true. ) then
            less_than_inverse = .true.
        else
            less_than_inverse = .false.
        end if
    end function
end module

program operator_overloading_01
  use operator_overloading_01_overload_comp_m
  implicit none
  logical, parameter :: T = .true., F = .false.

  print *, "T>T:", T>T  ! Yields: F
  print *, "T>F:", T>F  ! Yields: F
  print *, "F>T:", F>T  ! Yields: T
  print *, "F>F:", F>F  ! Yields: F
  print *, "T<T:", T<T  ! Yields: F
  print *, "T<F:", T<F  ! Yields: T
  print *, "F<T:", F<T  ! Yields: F
  print *, "F<F:", F<F  ! Yields: F
end program


module mlfv_mod

private

public :: mlfv, mlfvderiv

contains

complex(8) recursive function mlfv(alpha,beta,z,fi)  result(res)
! ============================================================================
! MLFV -- Mittag-Leffler function.
!           MLFV (alpha,beta,Z,P) is the Mittag-Leffler function E{alpha,beta}(Z)
!           evaluated with accuracy 10^(-fi) for Z.
!           alpha and beta are real scalars, P is integer ::, Z is complex.
!
!   Created by Davide Verotta on 3/11/10.
!   After MatLAB code C (C) 2001-2009 Igor Podlubny, Martin Kacenak
!   Copyright 2010 UCSF. All rights reserved.
!
!   Modified by Eduardo Mendes (with the permission of Davide Verotta) on 5/14/15.
!
!          The function is update following the newest matlab code version and
!                       nows deals with complex numbers.
!
!          The function has been tested with gfortran under Yosemite.
!
! ============================================================================
implicit none

! Declaration of Variables
!
real(8) :: alpha,beta
complex(8) :: z,newsum,term,aux,a1,a2,oldsum
integer :: fi
real(8) :: r0,rc,angz
real(8) :: eps,aaz
complex(8) :: zn
real(8), parameter :: pi = 3.1415926535897932384626434D0
complex(8), parameter :: ic=(0.d0,1.d0)
logical :: l1,l2,l3,l4
integer :: k,m,h
character(1) :: PN,KN
!
! Initiliazation of some variables
a1=0d0
a2=0d0
newsum=0d0
oldsum=0d0
res=0d0

if (alpha.lt.0)then
  print *,"alpha must be greater than zero"
  return
else if (beta.gt.5) then
  print *,"beta must be smaller than 5"
  return
else if (alpha.gt.5) then
  print *,"alpha must be smaller than 5"
  return
endif
!
PN='P'
KN='K'
!
if (beta.LT.0) then
  rc=log(10.d0**(-fi)*pi/(6.D0*(-beta+2)*(-beta*2)**(-beta)))
  rc=(-2.D0*rc)**alpha
else
  rc=(-2.D0*log(10.d0**(-fi)*pi/6.D0))**alpha
end if
r0=max(1.d0,2.d0*abs(z),rc)
angz=atan2(dimag(z),dble(z))
aaz=abs(angz)
if (alpha.EQ.1d0 .AND. beta.EQ.1d0) then
  res=exp(z)
  return
endif
l1=((alpha.LT.1 .AND. abs(z).LE.1))
l2=(1.LE.alpha.AND.alpha.lt.2)
l3=(abs(z).LE.floor(20/(2.1-alpha)**(5.5-2*alpha)))
l4=(alpha.GE.2d0) .AND. (abs(z).LE.50d0)
!
if (l1.OR.l2.AND.L3.OR.l4) then
  oldsum=dcmplx(0d0,0d0)
  k=0
  do while ((alpha*k+beta).LE.0d0)
    k=k+1
  end do
  newsum=z**k/gamma(alpha*k+beta)
! double summation because z can be negative
  do while(newsum .NE. oldsum)
    oldsum=newsum
    k=k+1
    term=z**k/gamma(alpha*k+beta)
    newsum=newsum+term
    k=k+1
    term=z**k/gamma(alpha*k+beta)
    newsum=newsum+term
  end do
  res=newsum
  return
endif
! the matlab function fix rounds toward zero, can  use floor since alpha is positive
if (alpha.LE.1.AND.abs(z).LE.floor(5*alpha+10)) then
!		print *,"below at alpha ;ess than 1 z bigger",angz
  if ((aaz.GT.pi*alpha).AND.(abs(aaz-(pi*alpha)).GT.10**(-fi)))then
    if (beta.LE.1) then
!				print *,"here 1",fi
    res=rombint(KN,0.D0,r0,fi,alpha,beta,z,0.d0)
    else
!				print *,"here 2"
      eps=1
      aux=rombint(PN,-pi*alpha,pi*alpha,fi,alpha,beta,z,eps)
      res=rombint(KN,eps,r0,fi,alpha,beta,z,0.d0)+aux
    end if
  else if (aaz.LT.pi*alpha.AND.abs(aaz-(pi*alpha)).GT.10**(-fi))then
    if (beta.LE.1) then
!				print *,"here 3"
      aux=(z**((1-beta)/alpha))*(exp(z**(1/alpha))/alpha)
      res=rombint(KN,0.D0,r0,fi,alpha,beta,z,0.d0)+aux
    else
!				print *,"here 4"
      eps=abs(z)/2d0
      aux=rombint(KN,eps,r0,fi,alpha,beta,z,0.d0)
      aux=aux+rombint(PN,-pi*alpha,pi*alpha,fi,alpha,beta,z,eps)
      res=aux+(z**((1.D0-beta)/alpha))*(exp(z**(1.D0/alpha))/alpha)
    end if
  else
!    print *,"here 5"
    eps=abs(z)+0.5D0
    aux=rombint(PN,-pi*alpha,pi*alpha,fi,alpha,beta,z,eps)
    res=rombint(KN,eps,r0,fi,alpha,beta,z,0.d0)+aux
  end if
  return
endif
!
if (alpha.LE.1) then
!  print *,"here 6",aaz
  if (aaz<(pi*alpha/2.D0+min(pi,pi*alpha))/2.D0) then
    newsum=(z**((1.D0-beta)/alpha))*exp(z**(1.D0/alpha))/alpha
!    print *, newsum
    do k=1,floor(fi/log10(abs(z)))
! There is a need to avoid gamma of negative numbers. NaN
       if (ceiling(beta-alpha*k)/=floor(beta-alpha*k)) then
!      print *,k,z**(-k),alpha,beta,beta-alpha*k,gamma(beta-alpha*k)
         newsum=newsum-((z**(-k))/gamma(beta-alpha*k))
!       else
!         print *,'beta-alpha*k', beta-alpha*k
       end if
    end do
!    print *,newsum
    res=newsum
  else
!    print *,"here 7"
    newsum=0d0
    do k=1,floor(fi/log10(abs(z)))
! There is a need to avoid gamma of negative numbers.
       if (ceiling(beta-alpha*k)/=floor(beta-alpha*k)) then
          newsum=newsum-((z**(-k))/gamma(beta-alpha*k))
!       else
!         print *,'beta-alpha*k', beta-alpha*k
       end if
    end do
    res=newsum
  end if
else
  if (alpha.GE.2) then
!    print *,"here 8"
    m=floor(alpha/2.D0)
    aux=0d0
! recursive call
    do h=0,m
      zn=(z**(1.D0/(m+1)))*exp((2.D0*pi*ic*h)/(m+1))
      aux=aux+mlfv(alpha/(m+1),beta,zn,fi)
    end do
    res=(1.D0/(m+1))*aux
  else
! recursive call
!
!  I had to use sqrt instead of **(1/2) since fortran returns real values
!      the latter.
!
!    print *,"here 9"
    a1=mlfv(alpha/2,beta,sqrt(z),fi)
    a2=mlfv(alpha/2,beta,-sqrt(z),fi)
    res=(a1+a2)/2d0
  end if
end if

end function mlfv

! ============================================================================
! Romber Integration For Auxillary functions
! ============================================================================
complex(8) function rombint(funfcn,a,b,order,v1,v2,v3,v4)
implicit none
!
character(1) :: funfcn
integer :: order,iorder,ipower,i,j,k
real(8) :: a,b,v1,v2,v4,hh
complex(8) :: v3,a1,a2,auxsum
complex(8), dimension(2,8) :: rom
!
iorder=order
!
if(funfcn.EQ."K") iorder = 6
if(order.gt.8)then
  print *,"need to increase size of matrix r which is 8, order is",iorder
  stop
end if
!
do i=1,2
  do j=1,iorder
    rom(i,j)=0.D0
  end do
end do
hh=b-a
if(funfcn.EQ.'K')then
  a1=kk(a,v1,v2,v3)
  a2=kk(b,v1,v2,v3)
else
  a1=pp(a,v1,v2,v3,v4)
  a2=pp(b,v1,v2,v3,v4)
end if
rom(1,1)=hh*(a1+a2)/2.d0
!
ipower=1
do i=2,iorder
  auxsum=0.d0
  do j=1,ipower
    if(funfcn.EQ.'K')then
      a1=kk((a+hh*(j-0.5)),v1,v2,v3)
    else
      a1=pp((a+hh*(j-0.5)),v1,v2,v3,v4)
    endif
    auxsum=auxsum+a1
  end do
  rom(2,1)=(rom(1,1)+hh*auxsum)/2.d0
  do k=1,(i-1)
    rom(2,k+1)=((4**k)*rom(2,k)-rom(1,k))/((4**k)-1)
  end do
  do j=0,(i-1)
    rom(1,j+1)=rom(2,j+1)
  end do
  ipower=ipower*2
  hh=hh/2
end do
rombint=rom(1,iorder)
!	  order=iorder
end function rombint
! ============================================================================
complex(8) function kk(r,alfa,beta,z)
implicit none
real(8) :: r,alfa,beta
complex(8) :: z,w
real(8), parameter :: pi = 3.1415926535897932384626434D0
!
!  This part has been modified and updated following the matlab newest package code.
!
w=r**((1-beta)/alfa)*exp(-r**(1/alfa))*(r*sin(pi*(1.d0-beta))-z*sin(pi*(1.d0-beta+alfa)))&
   &/(pi*alfa*(r**2-2.d0*r*z*cos(pi*alfa)+z**2))
kk=w
end function kk
! ============================================================================
complex(8) function pp(r,alpha,beta,z,epsn)
implicit none
real(8) :: r,alpha,beta,epsn
complex(8) :: z,w
real(8), parameter :: pi = 3.1415926535897932384626434D0
complex(8), parameter :: ic=(0.d0,1.d0)
!
w=(epsn**(1.d0/alpha))*sin(r/alpha)+r*(1.d0+(1.d0-beta)/alpha)
pp=((epsn**(1.d0+(1.d0-beta)/alpha))/(2.d0*pi*alpha))*((exp((epsn**(1/alpha))*cos(r/alpha))*&
   &(cos(w)+ic*sin(w))))/(epsn*exp(ic*r)-z)
!
end function pp

! ============================================================================
complex(8) function mlfvderiv(alpha,beta,z,fi)
implicit none
real(8) :: alpha,beta
integer :: fi
complex(8) :: z,newsum
real(8) :: d,w,aux,k1
integer :: k,k0
!
newsum=dcmplx(0d0,0d0)
w=alpha+beta-3d0/2d0
d=alpha*alpha-4d0*alpha*beta+6d0*alpha+1

! I had to add the following conditional statement to avoid log(1)
if (abs(log(abs(z))) < 10d-6) then
   aux=100000d0
else
   aux=abs(log(fi*(1-abs(z)))/log(abs(z)))
end if

if (abs(z) >0 .AND. abs(z) < 1) then
   if (alpha > 1) then
      k1=abs((2d0-alpha-beta)/(alpha-1))+1
   else
     if (alpha > 0 .AND. alpha <= 1 .AND. d <= 0) then
        k1=abs((3d0-alpha-beta)/alpha)+1
     else
        k1=max(abs((3d0-alpha-beta)/alpha)+1,abs((1d0-2d0*w*alpha+sqrt(d))/(2d0*alpha*alpha))+1)
     end if
   end if

   k0=ceiling(max(k1,aux))

   do k=0,k0
     newsum=newsum+((k+1)*z**k)/gamma(alpha+beta+alpha*k)
   end do
else if (abs(z)==0d0) then
   aux=-2d0
   newsum=gamma(aux)
else
   newsum=(mlfv(alpha,beta-1d0,z,fi)-(beta-1d0)*mlfv(alpha,beta,z,fi))/(alpha*z)
end if

mlfvderiv=newsum

end function mlfvderiv

end module mlfv_mod