! Computes water content and temperature every time step
subroutine SMPP
use declarations
implicit none
real(dp) :: mass_conservation, &              ! Mass conservation coefficient (=1 if mass is conserved)
        &   volume_water, &                   ! Volume of liquid water within the whole snowpack [m3]
        &   time , &                          ! Time since beginning of simulation [s]
        &   Tss_ini(N-1), &                   ! Initial snow surface temperature at each time step
        &   volume_water_ini, &               ! Initial volume of liquid water at time = 0 [m3]
        &   volume_water_frozen               ! Volume of liquid water that refreezes during each time step [m3]

volume_water_frozen = 0._dp
mass_conservation = 0._dp
time = 0._dp
outflow  = 0.0_dp
sum_fluxes = 0.0_dp
volume_water_ini = sum(water_content(:,1:M-1,1) * Vol(:,1:M-1))

!======= Convert classical grain size into optical grain size ==============
call conversion_grain

!======== Create the initial output files ==============================
call write_outputs(time,mass_conservation)

!============================ Main iterations ==========================================
do while (time .lt. tf)

   Tss_ini = Tss

   !========= Convert classical grain size into optical grain size ================
   call conversion_grain

   !============ Compute of hydraulic and thermal parameters ====================
   call calc_parameters

   !============ Compute time step (Dt) with CFL condition ===========================
   call timestep

   time = time+Dt

   !========= Compute of snowpack thinning and infiltration rate for melt case ==================
   call thinning_melt(Tss_ini,time,mass_conservation)

   !========= Compute mass and energy fluxes at the boundaries ====================
   call boundaries

   !========= Compute mass and energy fluxes in internal cells ====================
   if (M .gt. 2) then
      if (beta .gt. 0.0001) then  ! sloping snowpack
         do j = 2,M-2
            do i = 2,N-2
               !=========== Mass flux due to water pressure gradient ===================
               Fpresw(i,j) = K_west(i,j) * (P(i-1,j)-P(i,j)) * &
                  & ( Sx_west(i,j) / dabs(xv(i,j)-xv(i-1,j)) + &
                  & Sy_west(i,j) / dabs(yv(i,j)-yv(i-1,j)))

               Fprese(i,j) = K_east(i,j) * (P(i+1,j)-P(i,j)) * &
                  & ( Sx_east(i,j) / dabs(xv(i+1,j)-xv(i,j)) + &
                  & Sy_east(i,j) / dabs(yv(i+1,j)-yv(i,j)))

               Fpress(i,j) = K_south(i,j) * (P(i,j-1)-P(i,j)) * &
                  & ( Sx_south(i,j) / dabs(xv(i,j-1)-xv(i,j)) + &
                  & Sy_south(i,j) / dabs(yv(i,j-1)-yv(i,j)))

               Fpresn(i,j) = K_north(i,j) * (P(i,j+1)-P(i,j)) * &
                  & ( Sx_north(i,j) / dabs(xv(i,j+1)-xv(i,j)) + &
                  & Sy_north(i,j) / dabs(yv(i,j+1)-yv(i,j)))

               !============ Mass flux due to gravity force =============================
               Fgravw(i,j) = K_west(i,j) * Sy_west(i,j)
               Fgrave(i,j) = -K_east(i,j) * Sy_east(i,j)
               Fgravn(i,j) = K_north(i,j) * Sy_north(i,j)
               Fgravs(i,j) = -K_south(i,j) * Sy_south(i,j)

               !=========================== Heat flux ===================================
               Fconds(i,j) = k_eff_south(i,j) * (T(i,j-1,1)-T(i,j,1)) * &
                  & (Sy_south(i,j) / dabs(yv(i,j)-yv(i,j-1)) + &
                  & Sx_south(i,j) / dabs(xv(i,j)-xv(i,j-1)))

               Fcondn(i,j) = k_eff_north(i,j) * (T(i,j+1,1)-T(i,j,1)) * &
                  & (Sy_north(i,j) / dabs(yv(i,j+1)-yv(i,j)) + &
                  & Sx_north(i,j) / dabs(xv(i,j+1)-xv(i,j)))

               Fconde(i,j) = k_eff_east(i,j) * (T(i+1,j,1)-T(i,j,1)) * &
                  & (Sy_east(i,j) / dabs(yv(i+1,j)-yv(i,j)) + &
                  & Sx_east(i,j) / dabs(xv(i+1,j)-xv(i,j)))

               Fcondw(i,j) = k_eff_west(i,j) * (T(i-1,j,1)-T(i,j,1)) * &
                  & (Sy_west(i,j) / dabs(yv(i-1,j)-yv(i,j)) + &
                  & Sx_west(i,j) / dabs(xv(i-1,j)-xv(i,j)))

            enddo
         enddo
      else   ! beta=0, i.e. flat ground
         do j = 2,M-2
            do i = 2,N-2
               !================ Mass flux due to water pressure gradients =========================
               Fpresw(i,j) = Sx_west(i,j) * K_west(i,j) * &
                  & (P(i-1,j)-P(i,j)) / dabs(xv(i,j)-xv(i-1,j))

               Fprese(i,j) = Sx_east(i,j) * K_east(i,j) * &
                  & (P(i+1,j)-P(i,j)) / dabs(xv(i+1,j)-xv(i,j))

               Fpress(i,j) = Sy_south(i,j) * K_south(i,j) * &
                  & (P(i,j-1)-P(i,j)) / dabs(yv(i,j)-yv(i,j-1))

               Fpresn(i,j) = Sy_north(i,j) * K_north(i,j) * &
                  & (P(i,j+1)-P(i,j)) / dabs(yv(i,j+1)-yv(i,j))

               !================== Mass flux due to gravity force ===========================
               Fgravw(i,j) = K_west(i,j) * Sy_west(i,j)
               Fgrave(i,j) = -K_east(i,j) * Sy_east(i,j)
               Fgravn(i,j) = K_north(i,j) * Sy_north(i,j)
               Fgravs(i,j) = -K_south(i,j) * Sy_south(i,j)

               !====================== Heat fluxes =========================================
               Fconds(i,j) = Sy_south(i,j) * k_eff_south(i,j) * &
                  & (T(i,j-1,1)-T(i,j,1)) / dabs(yv(i,j)-yv(i,j-1))

               Fcondn(i,j) = Sy_north(i,j) * k_eff_north(i,j) * &
                  & (T(i,j+1,1)-T(i,j,1)) / dabs(yv(i,j)-yv(i,j+1))

               Fconde(i,j) = Sx_east(i,j) * k_eff_east(i,j) * &
                  & (T(i+1,j,1)-T(i,j,1)) / dabs(xv(i,j)-xv(i+1,j))

               Fcondw(i,j) = Sx_west(i,j) * k_eff_west(i,j) * &
                  & (T(i-1,j,1)-T(i,j,1)) / dabs(xv(i,j)-xv(i-1,j))

            enddo
         enddo
      endif
   endif

   !========== Condition to avoid mass flow from dry to wet cells ==========
   call condition_Darcy

   !========== Compute mass and heat fluxes coming into each cell
   do j = 1,M-1
      do i = 1,N-1
            Fpres(i,j) = Fpresn(i,j) + Fpress(i,j) + Fpresw(i,j) + Fprese(i,j)
            Fgrav(i,j) = Fgravn(i,j) + Fgravs(i,j) + Fgravw(i,j) + Fgrave(i,j)
            Fcond(i,j) = Fcondw(i,j) + Fconde(i,j) + Fconds(i,j) + Fcondn(i,j)
      enddo
   enddo

   !============= Solve mass and heat equations using FVM =========================
   call solver_mass_heat(volume_water_frozen)

   !============= Check if water content computed is NaN ===========================
   call check_nan(time, mass_conservation)

   !============= Compute total volume of liquid water and mass conservation ================
   sum_fluxes = sum_fluxes + (sum(Fgravs(:,1) + Fgravn(:,M-1)) + sum(Fgrave(N-1,1:M-1) + Fgravw(1,1:M-1))) * Dt
   volume_water = sum(water_content(:,1:M-1,1) * Vol(:,1:M-1)) - volume_water_ini + volume_water_frozen
   mass_conservation = volume_water / sum_fluxes

   !========================= Write ouputs in files ===================================
   call write_outputs(time,mass_conservation)

enddo

!================== write the final outputs ===========================
call write_outputs(time,mass_conservation)

return
end


module rotate

use arrays

contains

subroutine rotate_cube(mu, pivot, nx, ny, nz, dx, dy, dz)

   implicit none
   integer, intent(in) :: nx, ny, nz

   integer  Nzcut
   integer  i,j,jj,k, xn, xnp
   real(kind=8), intent(in) :: mu, pivot, dx, dy, dz
   real(kind=8)  theta, pivotdx,  newdx

   theta = acos(mu)
   pivotdx = tan(theta) * pivot
   newdx = dz * sin(theta)

   Nzcut = Nz * int((1.0d0/mu))

!   ---  allocate rotation arrays

   call set_muarray(Nzcut)

!!!!!!!!!!!!!!!!!!!!!!!!!!!
       zgrid(1)=1.0d0

        do k=2,Nzcut
         zgrid(k)=zgrid(k-1)+DZ*mu

        end do

! if mu not equal 1 we need new z indices!

        do k =1,Nzcut
          zf(k) = zgrid(k)/dz
          zl(k) = int(zf(k))
          zf(k) = zf(k) - dble(zl(k))
!  this is for new x gird for Nx = 1, for any other Nx one has to add nx to x_low

          xf(k) = ((k-1)*newdx - pivotdx)/dx
          xl(k) = int(xf(k))
          xf(k) = abs( xf(k) - dble(xl(k)) )
        end do

!---- start to do the whole cube
!--- over the x-y plane
      do i = 1, Nx
        do k = 1, Ny
           do j = 1, Nzcut
!             jj = (Nzcut -j +1)

             xn = xl(j)+(k-1)

             if (xn .lt. 1) then
              xn = xn + Ny
             else if (xn .gt. Ny) then
              xn = mod(xn, Ny)
             end if

             xnp = xn+1
             if(xnp .gt. Ny) xnp = mod(xnp, Ny)

          newT(i,k,j) = (T(i, xn, zl(j)) * (1.0d0-xf(j)) + xf(j)*T(i, xnp,  zl(j))) *(1.0d0+ zf(j))
          newT(i,k,j) = newT(i,k,j) -  zf(j)*(T(i, xn, zl(j)+1)*(1.0d0-xf(j))+ xf(j)*T(i, xnp,zl(j)+1))
!
          newP(i,k,j) = (P(i, xn, zl(j)) * (1.0d0-xf(j)) + xf(j)*P(i, xnp,  zl(j))) *(1.0d0+ zf(j))
          newP(i,k,j) = newP(i,k,j) -  zf(j)*(P(i, xn, zl(j)+1)*(1.0d0-xf(j))+ xf(j)*P(i, xnp,zl(j)+1))
!
          newrho(i,k,j) = (rho(i, xn, zl(j)) * (1.0d0-xf(j)) + xf(j)*rho(i, xnp,  zl(j))) *(1.0d0+ zf(j))
          newrho(i,k,j) = newrho(i,k,j) -  zf(j)*(rho(i, xn, zl(j)+1)*(1.0d0-xf(j))+ xf(j)*rho(i, xnp,zl(j)+1))
!

           end do
         end do
       end do

end subroutine

end module


      subroutine eiusle

!!    ~ ~ ~ PURPOSE ~ ~ ~
!!    This subroutine computes the USLE erosion index (EI)

!!    ~ ~ ~ INCOMING VARIABLES ~ ~ ~
!!    name        |units       |definition
!!    ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
!!    amp_r(:,:)  |none        |alpha factor for rain (mo max 0.5h rain)
!!    idg(:)      |none        |array location of random number seed
!!                             |used for a given process
!!    ihru        |none        |HRU number
!!    i_mo        |none        |month being simulated
!!    ovrlnd(:)   |mm H2O      |overland flow onto HRU from upstream
!!                             |routing unit
!!    precipday   |mm H2O      |amount of water reaching soil surface
!!    rndseed(:,:)|none        |random number generator seed
!!    snomlt      |mm H2O      |amount of snow melt in HRU on current day
!!    tconc(:)    |hr          |time of concentration
!!    ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

!!    ~ ~ ~ OUTGOING VARIABLES ~ ~ ~
!!    name        |units                  |definition
!!    ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
!!    usle_ei     |100(ft-tn in)/(acre-hr)|USLE rainfall erosion index
!!    ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

!!    ~ ~ ~ LOCAL DEFINITIONS ~ ~ ~
!!    name        |units       |definition
!!    ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
!!    ab          |mm H2O      |lowest value xa can have
!!    ajp         |mm H2O      |highest value xa can have
!!    j           |none        |HRU number
!!    pkrf        |none        |intermediate calculation
!!    pkrf30      |mm/hr       |maximum 30-min. storm intensity
!!    preceff     |mm H2O      |amount of rainfall impacting ground surface
!!                             |on day in HRU
!!    xa          |none        |fraction of daily rainfall occuring during
!!                             |half-hour of max intensity rain
!!    xb          |none        |intermediate calculation
!!    ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

!!    ~ ~ ~ SUBROUTINES/FUNCTIONS CALLED ~ ~ ~
!!    Intrinsic: Log, Log10
!!    SWAT: Expo, Atri

!!    ~ ~ ~ ~ ~ ~ END SPECIFICATIONS ~ ~ ~ ~ ~ ~

      use parm

      integer :: j
      real :: ab, xa, preceff, ajp, xb, pkrf, pkrf30

      j = 0
      j = ihru

      ab = 0.02083
      pkrf = 0.
      pkrf30 = 0.
      preceff = 0.
      xa = 0.
      xb = 0.

      preceff = precipday - snomlt - ovrlnd(j)
      if (preceff > 1.e-4) then
        ajp = 1. - Expo(-125. / preceff)
        xa = Atri(ab, amp_r(i_mo,hru_sub(j)), ajp, rndseed(idg(4),j))
        xb = -2. * Log(1. - xa)
        pkrf30 = 2. * preceff * xa
        pkrf = xb * preceff
        usle_ei = preceff * (12.1 + 8.9 * (Log10(pkrf) - .4343)) *
     &    pkrf30 / 1000.
!    *    peakr / 10.
        if (usle_ei < 1.e-4) usle_ei = 0.
        usle_eifac(j) = usle_ei
      endif

      return
      end


      SUBROUTINE MB03IZ( COMPQ, COMPU, N, A, LDA, C, LDC, D, LDD, B,
     $                   LDB, F, LDF, Q, LDQ, U1, LDU1, U2, LDU2, NEIG,
     $                   TOL, INFO )
C
C     SLICOT RELEASE 5.5.
C
C     Copyright (c) 2002-2012 NICONET e.V.
C
C     PURPOSE
C
C     To move the eigenvalues with strictly negative real parts of an
C     N-by-N complex skew-Hamiltonian/Hamiltonian pencil aS - bH in
C     structured Schur form, with
C
C                                (  0  I  )
C       S = J Z' J' Z, where J = (        ),
C                                ( -I  0  )
C
C     to the leading principal subpencil, while keeping the triangular
C     form. On entry, we have
C
C           (  A  D  )      (  B  F  )
C       Z = (        ), H = (        ),
C           (  0  C  )      (  0 -B' )
C
C     where A and B are upper triangular and C is lower triangular.
C     Z and H are transformed by a unitary symplectic matrix U and a
C     unitary matrix Q such that
C
C                       (  Aout  Dout  )
C       Zout = U' Z Q = (              ), and
C                       (    0   Cout  )
C                                                                    (1)
C                            (  Bout  Fout  )
C       Hout = J Q' J' H Q = (              ),
C                            (    0  -Bout' )
C
C     where Aout, Bout and Cout remain in triangular form. The notation
C     M' denotes the conjugate transpose of the matrix M.
C     Optionally, if COMPQ = 'I' or COMPQ = 'U', the unitary matrix Q
C     that fulfills (1) is computed.
C     Optionally, if COMPU = 'I' or COMPU = 'U', the unitary symplectic
C     matrix
C
C           (  U1  U2  )
C       U = (          )
C           ( -U2  U1  )
C
C     that fulfills (1) is computed.
C
C     ARGUMENTS
C
C     Mode Parameters
C
C     COMPQ   CHARACTER*1
C             Specifies whether or not the unitary transformations
C             should be accumulated in the array Q, as follows:
C             = 'N':  Q is not computed;
C             = 'I':  the array Q is initialized internally to the unit
C                     matrix, and the unitary matrix Q is returned;
C             = 'U':  the array Q contains a unitary matrix Q0 on
C                     entry, and the matrix Q0*Q is returned, where Q
C                     is the product of the unitary transformations
C                     that are applied to the pencil aS - bH to reorder
C                     the eigenvalues.
C
C     COMPU   CHARACTER*1
C             Specifies whether or not the unitary symplectic
C             transformations should be accumulated in the arrays U1 and
C             U2, as follows:
C             = 'N':  U1 and U2 are not computed;
C             = 'I':  the arrays U1 and U2 are initialized internally,
C                     and the submatrices U1 and U2 defining the
C                     unitary symplectic matrix U are returned;
C             = 'U':  the arrays U1 and U2 contain the corresponding
C                     submatrices of a unitary symplectic matrix U0
C                     on entry, and the updated submatrices U1 and U2
C                     of the matrix product U0*U are returned, where U
C                     is the product of the unitary symplectic
C                     transformations that are applied to the pencil
C                     aS - bH to reorder the eigenvalues.
C
C     Input/Output Parameters
C
C     N       (input) INTEGER
C             The order of the pencil aS - bH.  N >= 0, even.
C
C     A       (input/output) COMPLEX*16 array, dimension (LDA, N/2)
C             On entry, the leading N/2-by-N/2 part of this array must
C             contain the upper triangular matrix A.
C             On exit, the leading  N/2-by-N/2 part of this array
C             contains the transformed matrix Aout.
C             The strictly lower triangular part of this array is not
C             referenced.
C
C     LDA     INTEGER
C             The leading dimension of the array A.  LDA >= MAX(1, N/2).
C
C     C       (input/output) COMPLEX*16 array, dimension (LDC, N/2)
C             On entry, the leading N/2-by-N/2 part of this array must
C             contain the lower triangular matrix C.
C             On exit, the leading  N/2-by-N/2 part of this array
C             contains the transformed matrix Cout.
C             The strictly upper triangular part of this array is not
C             referenced.
C
C     LDC     INTEGER
C             The leading dimension of the array C.  LDC >= MAX(1, N/2).
C
C     D       (input/output) COMPLEX*16 array, dimension (LDD, N/2)
C             On entry, the leading N/2-by-N/2 part of this array must
C             contain the matrix D.
C             On exit, the leading  N/2-by-N/2 part of this array
C             contains the transformed matrix Dout.
C
C     LDD     INTEGER
C             The leading dimension of the array D.  LDD >= MAX(1, N/2).
C
C     B       (input/output) COMPLEX*16 array, dimension (LDB, N/2)
C             On entry, the leading N/2-by-N/2 part of this array must
C             contain the upper triangular matrix B.
C             On exit, the leading  N/2-by-N/2 part of this array
C             contains the transformed matrix Bout.
C             The strictly lower triangular part of this array is not
C             referenced.
C
C     LDB     INTEGER
C             The leading dimension of the array B.  LDB >= MAX(1, N/2).
C
C     F       (input/output) COMPLEX*16 array, dimension (LDF, N/2)
C             On entry, the leading N/2-by-N/2 part of this array must
C             contain the upper triangular part of the Hermitian matrix
C             F.
C             On exit, the leading  N/2-by-N/2 part of this array
C             contains the transformed matrix Fout.
C             The strictly lower triangular part of this array is not
C             referenced.
C
C     LDF     INTEGER
C             The leading dimension of the array F.  LDF >= MAX(1, N/2).
C
C     Q       (input/output) COMPLEX*16 array, dimension (LDQ, N)
C             On entry, if COMPQ = 'U', then the leading N-by-N part of
C             this array must contain a given matrix Q0, and on exit,
C             the leading N-by-N part of this array contains the product
C             of the input matrix Q0 and the transformation matrix Q
C             used to transform the matrices S and H.
C             On exit, if COMPQ = 'I', then the leading N-by-N part of
C             this array contains the unitary transformation matrix Q.
C             If COMPQ = 'N' this array is not referenced.
C
C     LDQ     INTEGER
C             The leading dimension of the array Q.
C             LDQ >= 1,         if COMPQ = 'N';
C             LDQ >= MAX(1, N), if COMPQ = 'I' or COMPQ = 'U'.
C
C     U1      (input/output) COMPLEX*16 array, dimension (LDU1, N/2)
C             On entry, if COMPU = 'U', then the leading N/2-by-N/2 part
C             of this array must contain the upper left block of a
C             given matrix U0, and on exit, the leading N/2-by-N/2 part
C             of this array contains the updated upper left block U1 of
C             the product of the input matrix U0 and the transformation
C             matrix U used to transform the matrices S and H.
C             On exit, if COMPU = 'I', then the leading N/2-by-N/2 part
C             of this array contains the upper left block U1 of the
C             unitary symplectic transformation matrix U.
C             If COMPU = 'N' this array is not referenced.
C
C     LDU1    INTEGER
C             The leading dimension of the array U1.
C             LDU1 >= 1,           if COMPU = 'N';
C             LDU1 >= MAX(1, N/2), if COMPU = 'I' or COMPU = 'U'.
C
C     U2      (input/output) COMPLEX*16 array, dimension (LDU2, N/2)
C             On entry, if COMPU = 'U', then the leading N/2-by-N/2 part
C             of this array must contain the upper right block of a
C             given matrix U0, and on exit, the leading N/2-by-N/2 part
C             of this array contains the updated upper right block U2 of
C             the product of the input matrix U0 and the transformation
C             matrix U used to transform the matrices S and H.
C             On exit, if COMPU = 'I', then the leading N/2-by-N/2 part
C             of this array contains the upper right block U2 of the
C             unitary symplectic transformation matrix U.
C             If COMPU = 'N' this array is not referenced.
C
C     LDU2    INTEGER
C             The leading dimension of the array U2.
C             LDU2 >= 1,           if COMPU = 'N';
C             LDU2 >= MAX(1, N/2), if COMPU = 'I' or COMPU = 'U'.
C
C     NEIG    (output) INTEGER
C             The number of eigenvalues in aS - bH with strictly
C             negative real part.
C
C     Tolerances
C
C     TOL     DOUBLE PRECISION
C             The tolerance used to decide the sign of the eigenvalues.
C             If the user sets TOL > 0, then the given value of TOL is
C             used. If the user sets TOL <= 0, then an implicitly
C             computed, default tolerance, defined by MIN(N,10)*EPS, is
C             used instead, where EPS is the machine precision (see
C             LAPACK Library routine DLAMCH). A larger value might be
C             needed for pencils with multiple eigenvalues.
C
C     Error Indicator
C
C     INFO    INTEGER
C             = 0: succesful exit;
C             < 0: if INFO = -i, the i-th argument had an illegal value.
C
C     METHOD
C
C     The algorithm reorders the eigenvalues like the following scheme:
C
C     Step 1: Reorder the eigenvalues in the subpencil aC'*A - bB.
C          I. Reorder the eigenvalues with negative real parts to the
C             top.
C         II. Reorder the eigenvalues with positive real parts to the
C             bottom.
C
C     Step 2: Reorder the remaining eigenvalues with negative real
C             parts.
C          I. Exchange the eigenvalues between the last diagonal block
C             in aC'*A - bB and the last diagonal block in aS - bH.
C         II. Move the eigenvalues in the N/2-th place to the (MM+1)-th
C             place, where MM denotes the current number of eigenvalues
C             with negative real parts in aC'*A - bB.
C
C     The algorithm uses a sequence of unitary transformations as
C     described on page 38 in [1]. To achieve those transformations the
C     elementary SLICOT Library subroutines MB03CZ and MB03GZ are called
C     for the corresponding matrix structures.
C
C     REFERENCES
C
C     [1] Benner, P., Byers, R., Mehrmann, V. and Xu, H.
C         Numerical Computation of Deflating Subspaces of Embedded
C         Hamiltonian Pencils.
C         Tech. Rep. SFB393/99-15, Technical University Chemnitz,
C         Germany, June 1999.
C
C     NUMERICAL ASPECTS
C                                                               3
C     The algorithm is numerically backward stable and needs O(N )
C     complex floating point operations.
C
C     CONTRIBUTOR
C
C     Matthias Voigt, Fakultaet fuer Mathematik, Technische Universitaet
C     Chemnitz, April 29, 2009.
C     V. Sima, Aug. 2009 (SLICOT version of the routine ZHAFNX).
C
C     REVISIONS
C
C     V. Sima, Dec. 2010, Jan. 2011.
C     M. Voigt, Jan. 2012.
C
C     KEYWORDS
C
C     Eigenvalue reordering, upper triangular matrix,
C     skew-Hamiltonian/Hamiltonian pencil, structured Schur form.
C
C     ******************************************************************
C
C     .. Parameters ..
      DOUBLE PRECISION   ZERO, TEN
      PARAMETER          ( ZERO = 0.0D+0, TEN = 1.0D+1 )
      COMPLEX*16         CZERO, CONE
      PARAMETER          ( CZERO = ( 0.0D+0, 0.0D+0 ),
     $                     CONE  = ( 1.0D+0, 0.0D+0 ) )
C
C     .. Scalar Arguments ..
      CHARACTER          COMPQ, COMPU
      INTEGER            INFO, LDA, LDB, LDC, LDD, LDF, LDQ, LDU1, LDU2,
     $                   N, NEIG
      DOUBLE PRECISION   TOL
C
C     .. Array Arguments ..
      COMPLEX*16         A( LDA, * ), B( LDB, * ), C( LDC, * ),
     $                   D( LDD, * ), F( LDF, * ), Q( LDQ, * ),
     $                   U1( LDU1, * ), U2( LDU2, * )
C
C     .. Local Scalars ..
      LOGICAL            LCMPQ, LCMPU, LINIQ, LINIU, LUPDQ, LUPDU
      INTEGER            IUPD, J, K, M, MM, MP, UPDS
      DOUBLE PRECISION   CO1, CO2, CO3, EPS, NRMA, NRMB
      COMPLEX*16         CJF, SI1, SI2, SI3, TMP
C
C     .. Local Arrays ..
      DOUBLE PRECISION   DUM( 1 )
      COMPLEX*16         HLP( 2, 2 )
C
C     .. External Functions ..
      LOGICAL            LSAME
      DOUBLE PRECISION   DLAMCH, ZLANTR
      EXTERNAL           DLAMCH, LSAME, ZLANTR
C
C     .. External Subroutines ..
      EXTERNAL           MB03CZ, MB03GZ, XERBLA, ZLASET, ZROT
C
C     .. Intrinsic Functions ..
      INTRINSIC          CONJG, DBLE, MAX, MIN, MOD
C
C     .. Executable Statements ..
C
C     Decode the input arguments.
C
      M     = N/2
      NEIG  = 0
      LINIQ = LSAME( COMPQ, 'I' )
      LUPDQ = LSAME( COMPQ, 'U' )
      LCMPQ = LINIQ .OR. LUPDQ
      LINIU = LSAME( COMPU, 'I' )
      LUPDU = LSAME( COMPU, 'U' )
      LCMPU = LINIU .OR. LUPDU
C
C     Test the input arguments.
C
      INFO = 0
      IF( .NOT.( LSAME( COMPQ, 'N' ) .OR. LCMPQ ) ) THEN
         INFO = -1
      ELSE IF( .NOT.( LSAME( COMPU, 'N' ) .OR. LCMPU ) ) THEN
         INFO = -2
      ELSE IF( N.LT.0 .OR. MOD( N, 2 ).NE.0 ) THEN
         INFO = -3
      ELSE IF( LDA.LT.MAX( 1, M ) ) THEN
         INFO = -5
      ELSE IF( LDC.LT.MAX( 1, M ) ) THEN
         INFO = -7
      ELSE IF( LDD.LT.MAX( 1, M ) ) THEN
         INFO = -9
      ELSE IF( LDB.LT.MAX( 1, M ) ) THEN
         INFO = -11
      ELSE IF( LDF.LT.MAX( 1, M ) ) THEN
         INFO = -13
      ELSE IF( LDQ.LT.1  .OR. ( LCMPQ .AND. LDQ.LT.N  ) ) THEN
         INFO = -15
      ELSE IF( LDU1.LT.1 .OR. ( LCMPU .AND. LDU1.LT.M ) ) THEN
         INFO = -17
      ELSE IF( LDU2.LT.1 .OR. ( LCMPU .AND. LDU2.LT.M ) ) THEN
         INFO = -19
      END IF
      IF( INFO.NE.0 ) THEN
         CALL XERBLA( 'MB03IZ', -INFO )
         RETURN
      END IF
C
C     Quick return if possible.
C
      IF( N.EQ.0 ) THEN
         RETURN
      END IF
C
      EPS = TOL
      IF ( EPS.LE.ZERO ) THEN
C
C        Use the default tolerance.
C
         EPS = MIN( DBLE( N ), TEN )*DLAMCH( 'Precision' )
      END IF
C
C     STEP 0. Initializations.
C
      IF( LINIQ ) THEN
         IUPD = M + 1
         UPDS = M
         CALL ZLASET( 'Full', N, N, CZERO, CONE, Q, LDQ )
      ELSE IF( LUPDQ ) THEN
         IUPD = 1
         UPDS = N
      END IF
C
      IF( LINIU ) THEN
         CALL ZLASET( 'Full', M, M, CZERO, CONE,  U1, LDU1 )
         CALL ZLASET( 'Full', M, M, CZERO, CZERO, U2, LDU2 )
      END IF
C
C     STEP 1. Reorder the eigenvalues in the subpencil aC'*A - bB.
C
      MM = 0
      MP = M + 1
      NRMA = ZLANTR( 'One', 'Upper', 'Non-Unit', M, M, A, LDA, DUM )*
     $       ZLANTR( 'One', 'Lower', 'Non-Unit', M, M, C, LDC, DUM )
      NRMB = ZLANTR( 'One', 'Upper', 'Non-Unit', M, M, B, LDB, DUM )
C
C     I. Reorder the eigenvalues with negative real parts to the top.
C
      DO 20 K = 1, M
         IF( DBLE( B( K, K )*C( K, K )*CONJG( A( K, K ) ) )*NRMB.LE.
     $      -EPS*NRMA ) THEN
            DO 10 J = K - 1, MM + 1, -1
C
C              Perform eigenvalue exchange.
C
               HLP( 1, 1 ) = CONJG( C( J, J ) )
               HLP( 1, 2 ) = CONJG( C( J+1, J ) )
               HLP( 2, 2 ) = CONJG( C( J+1, J+1 ) )
C
               CALL MB03CZ( HLP, 2, A( J, J ), LDA, B( J, J ),
     $                      LDB, CO1, SI1, CO2, SI2, CO3, SI3 )
C
C              Update A, C, and D.
C
               CALL ZROT( J, A( 1, J+1 ), 1, A( 1, J ), 1, CO1, SI1 )
               A( J, J )     = CO2*A( J, J ) +
     $                         SI2*A( J+1, J+1 )*CONJG( SI1 )
               A( J+1, J+1 ) = CO1*A( J+1, J+1 )
               CALL ZROT( M-J, A( J, J+1 ), LDA, A( J+1, J+1 ), LDA,
     $                    CO2, -SI2 )
C
               CALL ZROT( M, D( 1, J+1 ), 1, D( 1, J ), 1, CO3, SI3 )
               CALL ZROT( M, D( J, 1 ), LDD, D( J+1, 1 ), LDD, CO2, -SI2
     $                     )
C
               CALL ZROT( M-J, C( J+1, J+1 ), 1, C( J+1, J ), 1, CO3,
     $                    SI3 )
               C( J+1, J+1 ) = CO2*C( J+1, J+1 ) +
     $                         SI3*C( J, J )*CONJG( SI2 )
               C( J, J )     = CO3*C( J, J )
               CALL ZROT( J, C( J, 1 ), LDC, C( J+1, 1 ), LDC, CO2,
     $                    -SI2 )
C
C              Update B and F.
C
               CALL ZROT( J, B( 1, J+1 ), 1, B( 1, J ), 1, CO1, SI1 )
               B( J, J )     = CO3*B( J, J ) +
     $                         SI3*B( J+1, J+1 )*CONJG( SI1 )
               B( J+1, J+1 ) = CO1*B( J+1, J+1 )
               CALL ZROT( M-J, B( J, J+1 ), LDB, B( J+1, J+1 ), LDB,
     $                    CO3, -SI3 )
C
               CJF = CONJG( F( J, J+1 ) )
               TMP = CO3*CJF - CONJG( SI3 )*F( J+1, J+1 )
               CALL ZROT( J, F( 1, J+1 ), 1, F( 1, J ), 1, CO3, SI3 )
               F( J, J )     = CO3*F( J, J )     - SI3*TMP
               F( J+1, J+1 ) = CO3*F( J+1, J+1 ) + SI3*CJF
               CALL ZROT( M-J, F( J, J+1 ), LDF, F( J+1, J+1 ), LDF,
     $                    CO3, -SI3 )
C
               IF( LCMPQ ) THEN
C
C                 Update Q.
C
                  CALL ZROT( UPDS, Q( 1, J+1 ), 1, Q( 1, J ), 1, CO1,
     $                       SI1 )
                  CALL ZROT( UPDS, Q( IUPD, M+J+1 ), 1, Q( IUPD, M+J ),
     $                       1, CO3, SI3 )
               END IF
C
               IF( LCMPU ) THEN
C
C                 Update U.
C
                  CALL ZROT( M, U1( 1, J+1 ), 1, U1( 1, J ), 1, CO2, SI2
     $                        )
                  IF( LUPDU ) THEN
                     CALL ZROT( M, U2( 1, J+1 ), 1, U2( 1, J ), 1, CO2,
     $                          SI2 )
                  END IF
               END IF
   10       CONTINUE
            MM = MM + 1
         END IF
   20 CONTINUE
C
C     II. Reorder the eigenvalues with positive real parts to the bottom.
C
      DO 40 K = M, MM + 1, -1
         IF( DBLE( B( K, K )*C( K, K )*CONJG( A( K, K ) ) )*NRMB.GE.
     $       EPS*NRMA ) THEN
            DO 30 J = K, MP - 2
C
C              Perform eigenvalue exchange.
C
               HLP( 1, 1 ) = CONJG( C( J, J ) )
               HLP( 1, 2 ) = CONJG( C( J+1, J ) )
               HLP( 2, 2 ) = CONJG( C( J+1, J+1 ) )
C
               CALL MB03CZ( HLP, 2, A( J, J ), LDA, B( J, J ),
     $                      LDB, CO1, SI1, CO2, SI2, CO3, SI3 )
C
C              Update A, C, and D.
C
               CALL ZROT( J, A( 1, J+1 ), 1, A( 1, J ), 1, CO1, SI1 )
               A( J, J )     = CO2*A( J, J ) +
     $                         SI2*A( J+1, J+1 )*CONJG( SI1 )
               A( J+1, J+1 ) = CO1*A( J+1, J+1 )
               CALL ZROT( M-J, A( J, J+1 ), LDA, A( J+1, J+1 ), LDA,
     $                    CO2, -SI2 )
C
               CALL ZROT( M, D( 1, J+1 ), 1, D( 1, J ), 1, CO3, SI3 )
               CALL ZROT( M, D( J, 1 ), LDD, D( J+1, 1 ), LDD, CO2, -SI2
     $                     )
C
               CALL ZROT( M-J, C( J+1, J+1 ), 1, C( J+1, J ), 1, CO3,
     $                    SI3 )
               C( J+1, J+1 ) = CO2*C( J+1, J+1 ) +
     $                         SI3*C( J, J )*CONJG( SI2 )
               C( J, J )     = CO3*C( J, J )
               CALL ZROT( J, C( J, 1 ), LDC, C( J+1, 1 ), LDC, CO2,
     $                    -SI2 )
C
C              Update B and F.
C
               CALL ZROT( J, B( 1, J+1 ), 1, B( 1, J ), 1, CO1, SI1 )
               B( J, J )     = CO3*B( J, J ) +
     $                         SI3*B( J+1, J+1 )*CONJG( SI1 )
               B( J+1, J+1 ) = CO1*B( J+1, J+1 )
               CALL ZROT( M-J, B( J, J+1 ), LDB, B( J+1, J+1 ), LDB,
     $                    CO3, -SI3 )
C
               CJF = CONJG( F( J, J+1 ) )
               TMP = CO3*CJF - CONJG( SI3 )*F( J+1, J+1 )
               CALL ZROT( J, F( 1, J+1 ), 1, F( 1, J ), 1, CO3, SI3 )
               F( J, J )     = CO3*F( J, J )     - SI3*TMP
               F( J+1, J+1 ) = CO3*F( J+1, J+1 ) + SI3*CJF
               CALL ZROT( M-J, F( J, J+1 ), LDF, F( J+1, J+1 ), LDF,
     $                    CO3, -SI3 )
C
               IF( LCMPQ ) THEN
C
C                 Update Q.
C
                  CALL ZROT( UPDS, Q( 1, J+1 ), 1, Q( 1, J ), 1, CO1,
     $                       SI1 )
                  CALL ZROT( UPDS, Q( IUPD, M+J+1 ), 1, Q( IUPD, M+J ),
     $                       1, CO3, SI3 )
               END IF
C
               IF( LCMPU ) THEN
C
C                 Update U.
C
                  CALL ZROT( M, U1( 1, J+1 ), 1, U1( 1, J ), 1, CO2, SI2
     $                        )
                  IF( LUPDU ) THEN
                     CALL ZROT( M, U2( 1, J+1 ), 1, U2( 1, J ), 1, CO2,
     $                          SI2 )
                  END IF
               END IF
   30       CONTINUE
            MP = MP - 1
         END IF
   40 CONTINUE
C
C     The remaining M-MP+1 eigenvalues with negative real part are now in
C     the bottom right subpencil of aS - bH.
C
C     STEP 2. Reorder the remaining M-MP+1 eigenvalues.
C
      DO 60 K = M, MP, -1
C
C        I. Exchange the eigenvalues between two diagonal blocks.
C
C        Perform eigenvalue exchange.
C
         CALL MB03GZ( A( M, M ), D( M, M ), C( M, M ), B( M, M ),
     $                F( M, M ), CO1, SI1, CO2, SI2 )
C
C        Update A, C, and D.
C
         CALL ZROT( M, D( 1, M ), 1, A( 1, M ), 1, CO1, SI1 )
         TMP = -CONJG( SI1 )*C( M, M )
         C( M, M ) = CO1*C( M, M )
         CALL ZROT( M, D( M, 1 ), LDD, C( M, 1 ), LDC, CO2,
     $              -CONJG( SI2 ) )
         A( M, M ) = CO2*A( M, M ) - CONJG( SI2 )*TMP
C
C        Update B and F.
C
         TMP = -CONJG( B( M, M ) )
         CALL ZROT( M, F( 1, M ), 1, B( 1, M ), 1, CO1, SI1 )
         B( M, M ) = B( M, M )*CO1 + TMP*CONJG( SI1 )**2
         F( M, M ) = F( M, M )*CO1 - TMP*CONJG( SI1 )*CO1
C
         IF( LCMPQ ) THEN
C
C           Update Q.
C
            CALL ZROT( N, Q( 1, N ), 1, Q( 1, M ), 1, CO1, SI1 )
         END IF
C
         IF( LCMPU ) THEN
C
C           Update U.
C
            CALL ZROT( M, U2( 1, M ), 1, U1( 1, M ), 1, CO2, SI2 )
         END IF
C
C        II. Move the eigenvalue in the M-th diagonal position to the
C            (MM+1)-th position.
C
         MM = MM + 1
         DO 50 J = M - 1, MM, -1
C
C           Perform eigenvalue exchange.
C
            HLP( 1, 1 ) = CONJG( C( J, J ) )
            HLP( 1, 2 ) = CONJG( C( J+1, J ) )
            HLP( 2, 2 ) = CONJG( C( J+1, J+1 ) )
C
            CALL MB03CZ( HLP, 2, A( J, J ), LDA, B( J, J ), LDB, CO1,
     $                   SI1, CO2, SI2, CO3, SI3 )
C
C           Update A, C, and D.
C
            CALL ZROT( J, A( 1, J+1 ), 1, A( 1, J ), 1, CO1, SI1 )
            A( J, J )     = CO2*A( J, J ) +
     $                      SI2*A( J+1, J+1 )*CONJG( SI1 )
            A( J+1, J+1 ) = CO1*A( J+1, J+1 )
            CALL ZROT( M-J, A( J, J+1 ), LDA, A( J+1, J+1 ), LDA, CO2,
     $                 -SI2 )
C
            CALL ZROT( M, D( 1, J+1 ), 1, D( 1, J ), 1, CO3, SI3 )
            CALL ZROT( M, D( J, 1 ), LDD, D( J+1, 1 ), LDD, CO2, -SI2 )
C
            CALL ZROT( M-J, C( J+1, J+1 ), 1, C( J+1, J ), 1, CO3, SI3 )
            C( J+1, J+1 ) = CO2*C( J+1, J+1 ) +
     $                      SI3*C( J, J )*CONJG( SI2 )
            C( J, J )     = CO3*C( J, J )
            CALL ZROT( J, C( J, 1 ), LDC, C( J+1, 1 ), LDC, CO2, -SI2 )
C
C           Update B and F.
C
            CALL ZROT( J, B( 1, J+1 ), 1, B( 1, J ), 1, CO1, SI1 )
            B( J, J )     = CO3*B( J, J ) +
     $                      SI3*B( J+1, J+1 )*CONJG( SI1 )
            B( J+1, J+1 ) = CO1*B( J+1, J+1 )
            CALL ZROT( M-J, B( J, J+1 ), LDB, B( J+1, J+1 ), LDB, CO3,
     $                 -SI3 )
C
            CJF = CONJG( F( J, J+1 ) )
            TMP = CO3*CJF - CONJG( SI3 )*F( J+1, J+1 )
            CALL ZROT( J, F( 1, J+1 ), 1, F( 1, J ), 1, CO3, SI3 )
            F( J, J )     = CO3*F( J, J )     - SI3*TMP
            F( J+1, J+1 ) = CO3*F( J+1, J+1 ) + SI3*CJF
            CALL ZROT( M-J, F( J, J+1 ), LDF, F( J+1, J+1 ), LDF, CO3,
     $                 -SI3 )
C
            IF( LCMPQ ) THEN
C
C              Update Q.
C
               CALL ZROT( N, Q( 1, J+1 ), 1, Q( 1, J ), 1, CO1, SI1 )
               CALL ZROT( N, Q( 1, M+J+1 ), 1, Q( 1, M+J ), 1, CO3, SI3
     $                     )
            END IF
C
            IF( LCMPU ) THEN
C
C              Update U.
C
               CALL ZROT( M, U1( 1, J+1 ), 1, U1( 1, J ), 1, CO2, SI2 )
               CALL ZROT( M, U2( 1, J+1 ), 1, U2( 1, J ), 1, CO2, SI2 )
            END IF
   50    CONTINUE
   60 CONTINUE
C
      NEIG = MM
C
      RETURN
C *** Last line of MB03IZ ***
      END


      subroutine ascrv(x1,x2,x3,x4,x5,x6)

!!    ~ ~ ~ PURPOSE ~ ~ ~
!!    this subroutine computes shape parameters x5 and x6 for the S curve
!!    equation x = y/(y + exp(x5 + x6*y)) given 2 (x,y) points along the curve.
!!    x5 is determined by solving the equation with x and y values measured
!!    around the midpoint of the curve (approx. 50% of the maximum value for x)
!!    and x6 is determined by solving the equation with x and y values measured
!!    close to one of the endpoints of the curve (100% of the maximum value for
!!    x) This subroutine is called from readbsn.f and readcrop.f

!!    ~ ~ ~ INCOMING VARIABLES ~ ~ ~
!!    name        |units         |definition
!!    ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
!!    x1          |none          |value for x in the above equation for first
!!                               |datapoint, x1 should be close to 0.5 (the
!!                               |midpoint of the curve)
!!    x2          |none          |value for x in the above equation for second
!!                               |datapoint, x2 should be close to 0.0 or 1.0
!!    x3          |none          |value for y in the above equation correspond-
!!                               |ing to x1
!!    x4          |none          |value for y in the above equation correspond-
!!                               |ing to x2
!!    ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

!!    ~ ~ ~ OUTGOING VARIABLES ~ ~ ~
!!    name        |units         |definition
!!    ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
!!    x5          |none          |1st shape parameter for S curve equation
!!                               |characterizing the midpoint of the curve
!!    x6          |none          |2nd shape parameter for S curve equation
!!                               |characterizing the regions close to the
!!                               |endpoints of the curve
!!    ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

!!    ~ ~ ~ LOCAL DEFINITIONS ~ ~ ~
!!    name        |units         |definition
!!    ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
!!    xx          |none          |temp variable, used to hold calculated
!!                               |value needed in later equations
!!    ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

!!    ~ ~ ~ SUBROUTINES/FUNCTIONS CALLED ~ ~ ~
!!    Intrinsic: Log

!!    ~ ~ ~ ~ ~ ~ END SPECIFICATIONS ~ ~ ~ ~ ~ ~
      real*8 :: xx

      real*8, intent (in) :: x1, x2, x3, x4
      real*8, intent (out) :: x5, x6

      xx = 0.0
      x5 = 0.0
      x6 = 0.0

      xx = Log(x3/x1 - x3)
      x6 = (xx - Log(x4/x2 - x4)) / (x4 - x3)
      x5 = xx + (x3 * x6)

      return
      end


! Program to test handling of reduced rank array sections.  This uncovered
! bugs in simplify_shape and the scalarization of array sections.
program test_slice
  implicit none

  real (kind = 8), dimension(2, 2, 2) :: x
  real (kind = 8) :: min, max

  x = 1.0
  if (minval(x(1, 1:2, 1:1)) .ne. 1.0) call abort ()
  if (maxval(x(1, 1:2, 1:1)) .ne. 1.0) call abort ()
  if (any (shape(x(1, 1:2, 1:1)) .ne. (/2, 1/))) call abort ()

  if (any (shape(x(1, 1:2, 1)) .ne. (/2/))) call abort ()
  if (any (shape(x(1:1, 1:2, 1:1)) .ne. (/1, 2, 1/))) call abort ()

end program test_slice


program bc

  use blackbody_module, only : BGroup

  implicit none

  integer :: ngroups, igroup
  real(rt)        , allocatable :: xnu(:)
  real(rt)         :: T

  integer :: n
  character(len=256) :: line
  integer :: ipos

  ! open the file
  open(unit=10,file="group_structure.dat")

  ! read in the number of groups
  read(10,fmt='(a256)') line
  ipos = index(line, "=") + 1
  read (line(ipos:),*) ngroups

  allocate (xnu(0:ngroups))

  ! skip lines
  do n=1,ngroups+3
     read(10,fmt='(a256)') line
  end do

  do igroup = 0, ngroups
     read(10,fmt='(a256)') line
     ipos = index(line, "=") + 1
     read (line(ipos:),*) xnu(igroup)
  enddo

  print *, 'T = ?'
  read(*,*) T

  print *, "T = ", T
  print *, ((BGroup(T, xnu(igroup), xnu(igroup+1))), igroup=0,ngroups-1)

end program bc


\ From: John Hayes S1I
\ Subject: core.fr
\ Date: Mon, 27 Nov 95 13:10

\ (C) 1995 JOHNS HOPKINS UNIVERSITY / APPLIED PHYSICS LABORATORY
\ MAY BE DISTRIBUTED FREELY AS LONG AS THIS COPYRIGHT NOTICE REMAINS.
\ VERSION 1.2
\ THIS PROGRAM TESTS THE CORE WORDS OF AN ANS FORTH SYSTEM.
\ THE PROGRAM ASSUMES A TWO'S COMPLEMENT IMPLEMENTATION WHERE
\ THE RANGE OF SIGNED NUMBERS IS -2^(N-1) ... 2^(N-1)-1 AND
\ THE RANGE OF UNSIGNED NUMBERS IS 0 ... 2^(N)-1.
\ I HAVEN'T FIGURED OUT HOW TO TEST KEY, QUIT, ABORT, OR ABORT"...
\ I ALSO HAVEN'T THOUGHT OF A WAY TO TEST ENVIRONMENT?...

TESTING CORE WORD
HEX

\ ------------------------------------------------------------------------
TESTING BASIC ASSUMPTIONS

{ -> }					\ START WITH CLEAN SLATE
( TEST IF ANY BITS ARE SET; ANSWER IN BASE 1 )
{ : BITSSET? IF 0 0 ELSE 0 THEN ; -> }
{  0 BITSSET? -> 0 }		( ZERO IS ALL BITS CLEAR )
{  1 BITSSET? -> 0 0 }		( OTHER NUMBER HAVE AT LEAST ONE BIT )
{ -1 BITSSET? -> 0 0 }

\ ------------------------------------------------------------------------
TESTING BOOLEANS: INVERT AND OR XOR

{ 0 0 AND -> 0 }
{ 0 1 AND -> 0 }
{ 1 0 AND -> 0 }
{ 1 1 AND -> 1 }

{ 0 INVERT 1 AND -> 1 }
{ 1 INVERT 1 AND -> 0 }

0	 CONSTANT 0S
0 INVERT CONSTANT 1S

{ 0S INVERT -> 1S }
{ 1S INVERT -> 0S }

{ 0S 0S AND -> 0S }
{ 0S 1S AND -> 0S }
{ 1S 0S AND -> 0S }
{ 1S 1S AND -> 1S }

{ 0S 0S OR -> 0S }
{ 0S 1S OR -> 1S }
{ 1S 0S OR -> 1S }
{ 1S 1S OR -> 1S }

{ 0S 0S XOR -> 0S }
{ 0S 1S XOR -> 1S }
{ 1S 0S XOR -> 1S }
{ 1S 1S XOR -> 0S }

\ ------------------------------------------------------------------------
TESTING 2* 2/ LSHIFT RSHIFT

( WE TRUST 1S, INVERT, AND BITSSET?; WE WILL CONFIRM RSHIFT LATER )
1S 1 RSHIFT INVERT CONSTANT MSB
{ MSB BITSSET? -> 0 0 }

{ 0S 2* -> 0S }
{ 1 2* -> 2 }
{ 4000 2* -> 8000 }
{ 1S 2* 1 XOR -> 1S }
{ MSB 2* -> 0S }

{ 0S 2/ -> 0S }
{ 1 2/ -> 0 }
{ 4000 2/ -> 2000 }
{ 1S 2/ -> 1S }				\ MSB PROPOGATED
{ 1S 1 XOR 2/ -> 1S }
{ MSB 2/ MSB AND -> MSB }

{ 1 0 LSHIFT -> 1 }
{ 1 1 LSHIFT -> 2 }
{ 1 2 LSHIFT -> 4 }
{ 1 F LSHIFT -> 8000 }			\ BIGGEST GUARANTEED SHIFT
{ 1S 1 LSHIFT 1 XOR -> 1S }
{ MSB 1 LSHIFT -> 0 }

{ 1 0 RSHIFT -> 1 }
{ 1 1 RSHIFT -> 0 }
{ 2 1 RSHIFT -> 1 }
{ 4 2 RSHIFT -> 1 }
{ 8000 F RSHIFT -> 1 }			\ BIGGEST
{ MSB 1 RSHIFT MSB AND -> 0 }		\ RSHIFT ZERO FILLS MSBS
{ MSB 1 RSHIFT 2* -> MSB }

\ ------------------------------------------------------------------------
TESTING COMPARISONS: 0= = 0< < > U< MIN MAX
0 INVERT			CONSTANT MAX-UINT
0 INVERT 1 RSHIFT		CONSTANT MAX-INT
0 INVERT 1 RSHIFT INVERT	CONSTANT MIN-INT
0 INVERT 1 RSHIFT		CONSTANT MID-UINT
0 INVERT 1 RSHIFT INVERT	CONSTANT MID-UINT+1

0S CONSTANT <FALSE>
1S CONSTANT <TRUE>

{ 0 0= -> <TRUE> }
{ 1 0= -> <FALSE> }
{ 2 0= -> <FALSE> }
{ -1 0= -> <FALSE> }
{ MAX-UINT 0= -> <FALSE> }
{ MIN-INT 0= -> <FALSE> }
{ MAX-INT 0= -> <FALSE> }

{ 0 0 = -> <TRUE> }
{ 1 1 = -> <TRUE> }
{ -1 -1 = -> <TRUE> }
{ 1 0 = -> <FALSE> }
{ -1 0 = -> <FALSE> }
{ 0 1 = -> <FALSE> }
{ 0 -1 = -> <FALSE> }

{ 0 0< -> <FALSE> }
{ -1 0< -> <TRUE> }
{ MIN-INT 0< -> <TRUE> }
{ 1 0< -> <FALSE> }
{ MAX-INT 0< -> <FALSE> }

{ 0 1 < -> <TRUE> }
{ 1 2 < -> <TRUE> }
{ -1 0 < -> <TRUE> }
{ -1 1 < -> <TRUE> }
{ MIN-INT 0 < -> <TRUE> }
{ MIN-INT MAX-INT < -> <TRUE> }
{ 0 MAX-INT < -> <TRUE> }
{ 0 0 < -> <FALSE> }
{ 1 1 < -> <FALSE> }
{ 1 0 < -> <FALSE> }
{ 2 1 < -> <FALSE> }
{ 0 -1 < -> <FALSE> }
{ 1 -1 < -> <FALSE> }
{ 0 MIN-INT < -> <FALSE> }
{ MAX-INT MIN-INT < -> <FALSE> }
{ MAX-INT 0 < -> <FALSE> }

{ 0 1 > -> <FALSE> }
{ 1 2 > -> <FALSE> }
{ -1 0 > -> <FALSE> }
{ -1 1 > -> <FALSE> }
{ MIN-INT 0 > -> <FALSE> }
{ MIN-INT MAX-INT > -> <FALSE> }
{ 0 MAX-INT > -> <FALSE> }
{ 0 0 > -> <FALSE> }
{ 1 1 > -> <FALSE> }
{ 1 0 > -> <TRUE> }
{ 2 1 > -> <TRUE> }
{ 0 -1 > -> <TRUE> }
{ 1 -1 > -> <TRUE> }
{ 0 MIN-INT > -> <TRUE> }
{ MAX-INT MIN-INT > -> <TRUE> }
{ MAX-INT 0 > -> <TRUE> }

{ 0 1 U< -> <TRUE> }
{ 1 2 U< -> <TRUE> }
{ 0 MID-UINT U< -> <TRUE> }
{ 0 MAX-UINT U< -> <TRUE> }
{ MID-UINT MAX-UINT U< -> <TRUE> }
{ 0 0 U< -> <FALSE> }
{ 1 1 U< -> <FALSE> }
{ 1 0 U< -> <FALSE> }
{ 2 1 U< -> <FALSE> }
{ MID-UINT 0 U< -> <FALSE> }
{ MAX-UINT 0 U< -> <FALSE> }
{ MAX-UINT MID-UINT U< -> <FALSE> }

{ 0 1 MIN -> 0 }
{ 1 2 MIN -> 1 }
{ -1 0 MIN -> -1 }
{ -1 1 MIN -> -1 }
{ MIN-INT 0 MIN -> MIN-INT }
{ MIN-INT MAX-INT MIN -> MIN-INT }
{ 0 MAX-INT MIN -> 0 }
{ 0 0 MIN -> 0 }
{ 1 1 MIN -> 1 }
{ 1 0 MIN -> 0 }
{ 2 1 MIN -> 1 }
{ 0 -1 MIN -> -1 }
{ 1 -1 MIN -> -1 }
{ 0 MIN-INT MIN -> MIN-INT }
{ MAX-INT MIN-INT MIN -> MIN-INT }
{ MAX-INT 0 MIN -> 0 }

{ 0 1 MAX -> 1 }
{ 1 2 MAX -> 2 }
{ -1 0 MAX -> 0 }
{ -1 1 MAX -> 1 }
{ MIN-INT 0 MAX -> 0 }
{ MIN-INT MAX-INT MAX -> MAX-INT }
{ 0 MAX-INT MAX -> MAX-INT }
{ 0 0 MAX -> 0 }
{ 1 1 MAX -> 1 }
{ 1 0 MAX -> 1 }
{ 2 1 MAX -> 2 }
{ 0 -1 MAX -> 0 }
{ 1 -1 MAX -> 1 }
{ 0 MIN-INT MAX -> 0 }
{ MAX-INT MIN-INT MAX -> MAX-INT }
{ MAX-INT 0 MAX -> MAX-INT }

\ ------------------------------------------------------------------------
TESTING STACK OPS: 2DROP 2DUP 2OVER 2SWAP ?DUP DEPTH DROP DUP OVER ROT SWAP

{ 1 2 2DROP -> }
{ 1 2 2DUP -> 1 2 1 2 }
{ 1 2 3 4 2OVER -> 1 2 3 4 1 2 }
{ 1 2 3 4 2SWAP -> 3 4 1 2 }
{ 0 ?DUP -> 0 }
{ 1 ?DUP -> 1 1 }
{ -1 ?DUP -> -1 -1 }
{ DEPTH -> 0 }
{ 0 DEPTH -> 0 1 }
{ 0 1 DEPTH -> 0 1 2 }
{ 0 DROP -> }
{ 1 2 DROP -> 1 }
{ 1 DUP -> 1 1 }
{ 1 2 OVER -> 1 2 1 }
{ 1 2 3 ROT -> 2 3 1 }
{ 1 2 SWAP -> 2 1 }

\ ------------------------------------------------------------------------
TESTING >R R> R@

{ : GR1 >R R> ; -> }
{ : GR2 >R R@ R> DROP ; -> }
{ 123 GR1 -> 123 }
{ 123 GR2 -> 123 }
{ 1S GR1 -> 1S }   ( RETURN STACK HOLDS CELLS )

\ ------------------------------------------------------------------------
TESTING ADD/SUBTRACT: + - 1+ 1- ABS NEGATE

{ 0 5 + -> 5 }
{ 5 0 + -> 5 }
{ 0 -5 + -> -5 }
{ -5 0 + -> -5 }
{ 1 2 + -> 3 }
{ 1 -2 + -> -1 }
{ -1 2 + -> 1 }
{ -1 -2 + -> -3 }
{ -1 1 + -> 0 }
{ MID-UINT 1 + -> MID-UINT+1 }

{ 0 5 - -> -5 }
{ 5 0 - -> 5 }
{ 0 -5 - -> 5 }
{ -5 0 - -> -5 }
{ 1 2 - -> -1 }
{ 1 -2 - -> 3 }
{ -1 2 - -> -3 }
{ -1 -2 - -> 1 }
{ 0 1 - -> -1 }
{ MID-UINT+1 1 - -> MID-UINT }

{ 0 1+ -> 1 }
{ -1 1+ -> 0 }
{ 1 1+ -> 2 }
{ MID-UINT 1+ -> MID-UINT+1 }

{ 2 1- -> 1 }
{ 1 1- -> 0 }
{ 0 1- -> -1 }
{ MID-UINT+1 1- -> MID-UINT }

{ 0 NEGATE -> 0 }
{ 1 NEGATE -> -1 }
{ -1 NEGATE -> 1 }
{ 2 NEGATE -> -2 }
{ -2 NEGATE -> 2 }

{ 0 ABS -> 0 }
{ 1 ABS -> 1 }
{ -1 ABS -> 1 }
{ MIN-INT ABS -> MID-UINT+1 }

\ ------------------------------------------------------------------------
TESTING MULTIPLY: S>D * M* UM*

{ 0 S>D -> 0 0 }
{ 1 S>D -> 1 0 }
{ 2 S>D -> 2 0 }
{ -1 S>D -> -1 -1 }
{ -2 S>D -> -2 -1 }
{ MIN-INT S>D -> MIN-INT -1 }
{ MAX-INT S>D -> MAX-INT 0 }

{ 0 0 M* -> 0 S>D }
{ 0 1 M* -> 0 S>D }
{ 1 0 M* -> 0 S>D }
{ 1 2 M* -> 2 S>D }
{ 2 1 M* -> 2 S>D }
{ 3 3 M* -> 9 S>D }
{ -3 3 M* -> -9 S>D }
{ 3 -3 M* -> -9 S>D }
{ -3 -3 M* -> 9 S>D }
{ 0 MIN-INT M* -> 0 S>D }
{ 1 MIN-INT M* -> MIN-INT S>D }
{ 2 MIN-INT M* -> 0 1S }
{ 0 MAX-INT M* -> 0 S>D }
{ 1 MAX-INT M* -> MAX-INT S>D }
{ 2 MAX-INT M* -> MAX-INT 1 LSHIFT 0 }
{ MIN-INT MIN-INT M* -> 0 MSB 1 RSHIFT }
{ MAX-INT MIN-INT M* -> MSB MSB 2/ }
{ MAX-INT MAX-INT M* -> 1 MSB 2/ INVERT }

{ 0 0 * -> 0 }				\ TEST IDENTITIES
{ 0 1 * -> 0 }
{ 1 0 * -> 0 }
{ 1 2 * -> 2 }
{ 2 1 * -> 2 }
{ 3 3 * -> 9 }
{ -3 3 * -> -9 }
{ 3 -3 * -> -9 }
{ -3 -3 * -> 9 }

{ MID-UINT+1 1 RSHIFT 2 * -> MID-UINT+1 }
{ MID-UINT+1 2 RSHIFT 4 * -> MID-UINT+1 }
{ MID-UINT+1 1 RSHIFT MID-UINT+1 OR 2 * -> MID-UINT+1 }

{ 0 0 UM* -> 0 0 }
{ 0 1 UM* -> 0 0 }
{ 1 0 UM* -> 0 0 }
{ 1 2 UM* -> 2 0 }
{ 2 1 UM* -> 2 0 }
{ 3 3 UM* -> 9 0 }

{ MID-UINT+1 1 RSHIFT 2 UM* -> MID-UINT+1 0 }
{ MID-UINT+1 2 UM* -> 0 1 }
{ MID-UINT+1 4 UM* -> 0 2 }
{ 1S 2 UM* -> 1S 1 LSHIFT 1 }
{ MAX-UINT MAX-UINT UM* -> 1 1 INVERT }

\ ------------------------------------------------------------------------
TESTING DIVIDE: FM/MOD SM/REM UM/MOD */ */MOD / /MOD MOD

{ 0 S>D 1 FM/MOD -> 0 0 }
{ 1 S>D 1 FM/MOD -> 0 1 }
{ 2 S>D 1 FM/MOD -> 0 2 }
{ -1 S>D 1 FM/MOD -> 0 -1 }
{ -2 S>D 1 FM/MOD -> 0 -2 }
{ 0 S>D -1 FM/MOD -> 0 0 }
{ 1 S>D -1 FM/MOD -> 0 -1 }
{ 2 S>D -1 FM/MOD -> 0 -2 }
{ -1 S>D -1 FM/MOD -> 0 1 }
{ -2 S>D -1 FM/MOD -> 0 2 }
{ 2 S>D 2 FM/MOD -> 0 1 }
{ -1 S>D -1 FM/MOD -> 0 1 }
{ -2 S>D -2 FM/MOD -> 0 1 }
{  7 S>D  3 FM/MOD -> 1 2 }
{  7 S>D -3 FM/MOD -> -2 -3 }
{ -7 S>D  3 FM/MOD -> 2 -3 }
{ -7 S>D -3 FM/MOD -> -1 2 }
{ MAX-INT S>D 1 FM/MOD -> 0 MAX-INT }
{ MIN-INT S>D 1 FM/MOD -> 0 MIN-INT }
{ MAX-INT S>D MAX-INT FM/MOD -> 0 1 }
{ MIN-INT S>D MIN-INT FM/MOD -> 0 1 }
{ 1S 1 4 FM/MOD -> 3 MAX-INT }
{ 1 MIN-INT M* 1 FM/MOD -> 0 MIN-INT }
{ 1 MIN-INT M* MIN-INT FM/MOD -> 0 1 }
{ 2 MIN-INT M* 2 FM/MOD -> 0 MIN-INT }
{ 2 MIN-INT M* MIN-INT FM/MOD -> 0 2 }
{ 1 MAX-INT M* 1 FM/MOD -> 0 MAX-INT }
{ 1 MAX-INT M* MAX-INT FM/MOD -> 0 1 }
{ 2 MAX-INT M* 2 FM/MOD -> 0 MAX-INT }
{ 2 MAX-INT M* MAX-INT FM/MOD -> 0 2 }
{ MIN-INT MIN-INT M* MIN-INT FM/MOD -> 0 MIN-INT }
{ MIN-INT MAX-INT M* MIN-INT FM/MOD -> 0 MAX-INT }
{ MIN-INT MAX-INT M* MAX-INT FM/MOD -> 0 MIN-INT }
{ MAX-INT MAX-INT M* MAX-INT FM/MOD -> 0 MAX-INT }

{ 0 S>D 1 SM/REM -> 0 0 }
{ 1 S>D 1 SM/REM -> 0 1 }
{ 2 S>D 1 SM/REM -> 0 2 }
{ -1 S>D 1 SM/REM -> 0 -1 }
{ -2 S>D 1 SM/REM -> 0 -2 }
{ 0 S>D -1 SM/REM -> 0 0 }
{ 1 S>D -1 SM/REM -> 0 -1 }
{ 2 S>D -1 SM/REM -> 0 -2 }
{ -1 S>D -1 SM/REM -> 0 1 }
{ -2 S>D -1 SM/REM -> 0 2 }
{ 2 S>D 2 SM/REM -> 0 1 }
{ -1 S>D -1 SM/REM -> 0 1 }
{ -2 S>D -2 SM/REM -> 0 1 }
{  7 S>D  3 SM/REM -> 1 2 }
{  7 S>D -3 SM/REM -> 1 -2 }
{ -7 S>D  3 SM/REM -> -1 -2 }
{ -7 S>D -3 SM/REM -> -1 2 }
{ MAX-INT S>D 1 SM/REM -> 0 MAX-INT }
{ MIN-INT S>D 1 SM/REM -> 0 MIN-INT }
{ MAX-INT S>D MAX-INT SM/REM -> 0 1 }
{ MIN-INT S>D MIN-INT SM/REM -> 0 1 }
{ 1S 1 4 SM/REM -> 3 MAX-INT }
{ 2 MIN-INT M* 2 SM/REM -> 0 MIN-INT }
{ 2 MIN-INT M* MIN-INT SM/REM -> 0 2 }
{ 2 MAX-INT M* 2 SM/REM -> 0 MAX-INT }
{ 2 MAX-INT M* MAX-INT SM/REM -> 0 2 }
{ MIN-INT MIN-INT M* MIN-INT SM/REM -> 0 MIN-INT }
{ MIN-INT MAX-INT M* MIN-INT SM/REM -> 0 MAX-INT }
{ MIN-INT MAX-INT M* MAX-INT SM/REM -> 0 MIN-INT }
{ MAX-INT MAX-INT M* MAX-INT SM/REM -> 0 MAX-INT }

{ 0 0 1 UM/MOD -> 0 0 }
{ 1 0 1 UM/MOD -> 0 1 }
{ 1 0 2 UM/MOD -> 1 0 }
{ 3 0 2 UM/MOD -> 1 1 }
{ MAX-UINT 2 UM* 2 UM/MOD -> 0 MAX-UINT }
{ MAX-UINT 2 UM* MAX-UINT UM/MOD -> 0 2 }
{ MAX-UINT MAX-UINT UM* MAX-UINT UM/MOD -> 0 MAX-UINT }

: IFFLOORED
   [ -3 2 / -2 = INVERT ] LITERAL IF POSTPONE \ THEN ;
: IFSYM
   [ -3 2 / -1 = INVERT ] LITERAL IF POSTPONE \ THEN ;

\ THE SYSTEM MIGHT DO EITHER FLOORED OR SYMMETRIC DIVISION.
\ SINCE WE HAVE ALREADY TESTED M*, FM/MOD, AND SM/REM WE CAN USE THEM IN TEST.
IFFLOORED : T/MOD  >R S>D R> FM/MOD ;
IFFLOORED : T/     T/MOD SWAP DROP ;
IFFLOORED : TMOD   T/MOD DROP ;
IFFLOORED : T*/MOD >R M* R> FM/MOD ;
IFFLOORED : T*/    T*/MOD SWAP DROP ;
IFSYM     : T/MOD  >R S>D R> SM/REM ;
IFSYM     : T/     T/MOD SWAP DROP ;
IFSYM     : TMOD   T/MOD DROP ;
IFSYM     : T*/MOD >R M* R> SM/REM ;
IFSYM     : T*/    T*/MOD SWAP DROP ;

{ 0 1 /MOD -> 0 1 T/MOD }
{ 1 1 /MOD -> 1 1 T/MOD }
{ 2 1 /MOD -> 2 1 T/MOD }
{ -1 1 /MOD -> -1 1 T/MOD }
{ -2 1 /MOD -> -2 1 T/MOD }
{ 0 -1 /MOD -> 0 -1 T/MOD }
{ 1 -1 /MOD -> 1 -1 T/MOD }
{ 2 -1 /MOD -> 2 -1 T/MOD }
{ -1 -1 /MOD -> -1 -1 T/MOD }
{ -2 -1 /MOD -> -2 -1 T/MOD }
{ 2 2 /MOD -> 2 2 T/MOD }
{ -1 -1 /MOD -> -1 -1 T/MOD }
{ -2 -2 /MOD -> -2 -2 T/MOD }
{ 7 3 /MOD -> 7 3 T/MOD }
{ 7 -3 /MOD -> 7 -3 T/MOD }
{ -7 3 /MOD -> -7 3 T/MOD }
{ -7 -3 /MOD -> -7 -3 T/MOD }
{ MAX-INT 1 /MOD -> MAX-INT 1 T/MOD }
{ MIN-INT 1 /MOD -> MIN-INT 1 T/MOD }
{ MAX-INT MAX-INT /MOD -> MAX-INT MAX-INT T/MOD }
{ MIN-INT MIN-INT /MOD -> MIN-INT MIN-INT T/MOD }

{ 0 1 / -> 0 1 T/ }
{ 1 1 / -> 1 1 T/ }
{ 2 1 / -> 2 1 T/ }
{ -1 1 / -> -1 1 T/ }
{ -2 1 / -> -2 1 T/ }
{ 0 -1 / -> 0 -1 T/ }
{ 1 -1 / -> 1 -1 T/ }
{ 2 -1 / -> 2 -1 T/ }
{ -1 -1 / -> -1 -1 T/ }
{ -2 -1 / -> -2 -1 T/ }
{ 2 2 / -> 2 2 T/ }
{ -1 -1 / -> -1 -1 T/ }
{ -2 -2 / -> -2 -2 T/ }
{ 7 3 / -> 7 3 T/ }
{ 7 -3 / -> 7 -3 T/ }
{ -7 3 / -> -7 3 T/ }
{ -7 -3 / -> -7 -3 T/ }
{ MAX-INT 1 / -> MAX-INT 1 T/ }
{ MIN-INT 1 / -> MIN-INT 1 T/ }
{ MAX-INT MAX-INT / -> MAX-INT MAX-INT T/ }
{ MIN-INT MIN-INT / -> MIN-INT MIN-INT T/ }

{ 0 1 MOD -> 0 1 TMOD }
{ 1 1 MOD -> 1 1 TMOD }
{ 2 1 MOD -> 2 1 TMOD }
{ -1 1 MOD -> -1 1 TMOD }
{ -2 1 MOD -> -2 1 TMOD }
{ 0 -1 MOD -> 0 -1 TMOD }
{ 1 -1 MOD -> 1 -1 TMOD }
{ 2 -1 MOD -> 2 -1 TMOD }
{ -1 -1 MOD -> -1 -1 TMOD }
{ -2 -1 MOD -> -2 -1 TMOD }
{ 2 2 MOD -> 2 2 TMOD }
{ -1 -1 MOD -> -1 -1 TMOD }
{ -2 -2 MOD -> -2 -2 TMOD }
{ 7 3 MOD -> 7 3 TMOD }
{ 7 -3 MOD -> 7 -3 TMOD }
{ -7 3 MOD -> -7 3 TMOD }
{ -7 -3 MOD -> -7 -3 TMOD }
{ MAX-INT 1 MOD -> MAX-INT 1 TMOD }
{ MIN-INT 1 MOD -> MIN-INT 1 TMOD }
{ MAX-INT MAX-INT MOD -> MAX-INT MAX-INT TMOD }
{ MIN-INT MIN-INT MOD -> MIN-INT MIN-INT TMOD }

{ 0 2 1 */ -> 0 2 1 T*/ }
{ 1 2 1 */ -> 1 2 1 T*/ }
{ 2 2 1 */ -> 2 2 1 T*/ }
{ -1 2 1 */ -> -1 2 1 T*/ }
{ -2 2 1 */ -> -2 2 1 T*/ }
{ 0 2 -1 */ -> 0 2 -1 T*/ }
{ 1 2 -1 */ -> 1 2 -1 T*/ }
{ 2 2 -1 */ -> 2 2 -1 T*/ }
{ -1 2 -1 */ -> -1 2 -1 T*/ }
{ -2 2 -1 */ -> -2 2 -1 T*/ }
{ 2 2 2 */ -> 2 2 2 T*/ }
{ -1 2 -1 */ -> -1 2 -1 T*/ }
{ -2 2 -2 */ -> -2 2 -2 T*/ }
{ 7 2 3 */ -> 7 2 3 T*/ }
{ 7 2 -3 */ -> 7 2 -3 T*/ }
{ -7 2 3 */ -> -7 2 3 T*/ }
{ -7 2 -3 */ -> -7 2 -3 T*/ }
{ MAX-INT 2 MAX-INT */ -> MAX-INT 2 MAX-INT T*/ }
{ MIN-INT 2 MIN-INT */ -> MIN-INT 2 MIN-INT T*/ }

{ 0 2 1 */MOD -> 0 2 1 T*/MOD }
{ 1 2 1 */MOD -> 1 2 1 T*/MOD }
{ 2 2 1 */MOD -> 2 2 1 T*/MOD }
{ -1 2 1 */MOD -> -1 2 1 T*/MOD }
{ -2 2 1 */MOD -> -2 2 1 T*/MOD }
{ 0 2 -1 */MOD -> 0 2 -1 T*/MOD }
{ 1 2 -1 */MOD -> 1 2 -1 T*/MOD }
{ 2 2 -1 */MOD -> 2 2 -1 T*/MOD }
{ -1 2 -1 */MOD -> -1 2 -1 T*/MOD }
{ -2 2 -1 */MOD -> -2 2 -1 T*/MOD }
{ 2 2 2 */MOD -> 2 2 2 T*/MOD }
{ -1 2 -1 */MOD -> -1 2 -1 T*/MOD }
{ -2 2 -2 */MOD -> -2 2 -2 T*/MOD }
{ 7 2 3 */MOD -> 7 2 3 T*/MOD }
{ 7 2 -3 */MOD -> 7 2 -3 T*/MOD }
{ -7 2 3 */MOD -> -7 2 3 T*/MOD }
{ -7 2 -3 */MOD -> -7 2 -3 T*/MOD }
{ MAX-INT 2 MAX-INT */MOD -> MAX-INT 2 MAX-INT T*/MOD }
{ MIN-INT 2 MIN-INT */MOD -> MIN-INT 2 MIN-INT T*/MOD }

\ ------------------------------------------------------------------------
TESTING HERE , @ ! CELL+ CELLS C, C@ C! CHARS 2@ 2! ALIGN ALIGNED +! ALLOT

HERE 1 ALLOT
HERE
CONSTANT 2NDA
CONSTANT 1STA
{ 1STA 2NDA U< -> <TRUE> }		\ HERE MUST GROW WITH ALLOT
{ 1STA 1+ -> 2NDA }			\ ... BY ONE ADDRESS UNIT
( MISSING TEST: NEGATIVE ALLOT )

HERE 1 ,
HERE 2 ,
CONSTANT 2ND
CONSTANT 1ST
{ 1ST 2ND U< -> <TRUE> }			\ HERE MUST GROW WITH ALLOT
{ 1ST CELL+ -> 2ND }			\ ... BY ONE CELL
{ 1ST 1 CELLS + -> 2ND }
{ 1ST @ 2ND @ -> 1 2 }
{ 5 1ST ! -> }
{ 1ST @ 2ND @ -> 5 2 }
{ 6 2ND ! -> }
{ 1ST @ 2ND @ -> 5 6 }
{ 1ST 2@ -> 6 5 }
{ 2 1 1ST 2! -> }
{ 1ST 2@ -> 2 1 }
{ 1S 1ST !  1ST @ -> 1S }		\ CAN STORE CELL-WIDE VALUE

HERE 1 C,
HERE 2 C,
CONSTANT 2NDC
CONSTANT 1STC
{ 1STC 2NDC U< -> <TRUE> }		\ HERE MUST GROW WITH ALLOT
{ 1STC CHAR+ -> 2NDC }			\ ... BY ONE CHAR
{ 1STC 1 CHARS + -> 2NDC }
{ 1STC C@ 2NDC C@ -> 1 2 }
{ 3 1STC C! -> }
{ 1STC C@ 2NDC C@ -> 3 2 }
{ 4 2NDC C! -> }
{ 1STC C@ 2NDC C@ -> 3 4 }

ALIGN 1 ALLOT HERE ALIGN HERE 3 CELLS ALLOT
CONSTANT A-ADDR  CONSTANT UA-ADDR
{ UA-ADDR ALIGNED -> A-ADDR }
{    1 A-ADDR C!  A-ADDR C@ ->    1 }
{ 1234 A-ADDR  !  A-ADDR  @ -> 1234 }
{ 123 456 A-ADDR 2!  A-ADDR 2@ -> 123 456 }
{ 2 A-ADDR CHAR+ C!  A-ADDR CHAR+ C@ -> 2 }
{ 3 A-ADDR CELL+ C!  A-ADDR CELL+ C@ -> 3 }
{ 1234 A-ADDR CELL+ !  A-ADDR CELL+ @ -> 1234 }
{ 123 456 A-ADDR CELL+ 2!  A-ADDR CELL+ 2@ -> 123 456 }

: BITS ( X -- U )
   0 SWAP BEGIN DUP WHILE DUP MSB AND IF >R 1+ R> THEN 2* REPEAT DROP ;
( CHARACTERS >= 1 AU, <= SIZE OF CELL, >= 8 BITS )
{ 1 CHARS 1 < -> <FALSE> }
{ 1 CHARS 1 CELLS > -> <FALSE> }
( TBD: HOW TO FIND NUMBER OF BITS? )

( CELLS >= 1 AU, INTEGRAL MULTIPLE OF CHAR SIZE, >= 16 BITS )
{ 1 CELLS 1 < -> <FALSE> }
{ 1 CELLS 1 CHARS MOD -> 0 }
{ 1S BITS 10 < -> <FALSE> }

{ 0 1ST ! -> }
{ 1 1ST +! -> }
{ 1ST @ -> 1 }
{ -1 1ST +! 1ST @ -> 0 }

\ ------------------------------------------------------------------------
TESTING CHAR [CHAR] [ ] BL S"

{ BL -> 20 }
{ CHAR X -> 58 }
{ CHAR HELLO -> 48 }
{ : GC1 [CHAR] X ; -> }
{ : GC2 [CHAR] HELLO ; -> }
{ GC1 -> 58 }
{ GC2 -> 48 }
{ : GC3 [ GC1 ] LITERAL ; -> }
{ GC3 -> 58 }
{ : GC4 S" XY" ; -> }
{ GC4 SWAP DROP -> 2 }
{ GC4 DROP DUP C@ SWAP CHAR+ C@ -> 58 59 }

\ ------------------------------------------------------------------------
TESTING ' ['] FIND EXECUTE IMMEDIATE COUNT LITERAL POSTPONE STATE

{ : GT1 123 ; -> }
{ ' GT1 EXECUTE -> 123 }
{ : GT2 ['] GT1 ; IMMEDIATE -> }
{ GT2 EXECUTE -> 123 }
HERE 3 C, CHAR G C, CHAR T C, CHAR 1 C, CONSTANT GT1STRING
HERE 3 C, CHAR G C, CHAR T C, CHAR 2 C, CONSTANT GT2STRING
{ GT1STRING FIND -> ' GT1 -1 }
{ GT2STRING FIND -> ' GT2 1 }
( HOW TO SEARCH FOR NON-EXISTENT WORD? )
{ : GT3 GT2 LITERAL ; -> }
{ GT3 -> ' GT1 }
{ GT1STRING COUNT -> GT1STRING CHAR+ 3 }

{ : GT4 POSTPONE GT1 ; IMMEDIATE -> }
{ : GT5 GT4 ; -> }
{ GT5 -> 123 }
{ : GT6 345 ; IMMEDIATE -> }
{ : GT7 POSTPONE GT6 ; -> }
{ GT7 -> 345 }

{ : GT8 STATE @ ; IMMEDIATE -> }
{ GT8 -> 0 }
{ : GT9 GT8 LITERAL ; -> }
{ GT9 0= -> <FALSE> }

\ ------------------------------------------------------------------------
TESTING IF ELSE THEN BEGIN WHILE REPEAT UNTIL RECURSE

{ : GI1 IF 123 THEN ; -> }
{ : GI2 IF 123 ELSE 234 THEN ; -> }
{ 0 GI1 -> }
{ 1 GI1 -> 123 }
{ -1 GI1 -> 123 }
{ 0 GI2 -> 234 }
{ 1 GI2 -> 123 }
{ -1 GI1 -> 123 }

{ : GI3 BEGIN DUP 5 < WHILE DUP 1+ REPEAT ; -> }
{ 0 GI3 -> 0 1 2 3 4 5 }
{ 4 GI3 -> 4 5 }
{ 5 GI3 -> 5 }
{ 6 GI3 -> 6 }

{ : GI4 BEGIN DUP 1+ DUP 5 > UNTIL ; -> }
{ 3 GI4 -> 3 4 5 6 }
{ 5 GI4 -> 5 6 }
{ 6 GI4 -> 6 7 }

{ : GI5 BEGIN DUP 2 > WHILE DUP 5 < WHILE DUP 1+ REPEAT 123 ELSE 345 THEN ; -> }
{ 1 GI5 -> 1 345 }
{ 2 GI5 -> 2 345 }
{ 3 GI5 -> 3 4 5 123 }
{ 4 GI5 -> 4 5 123 }
{ 5 GI5 -> 5 123 }

{ : GI6 ( N -- 0,1,..N ) DUP IF DUP >R 1- RECURSE R> THEN ; -> }
{ 0 GI6 -> 0 }
{ 1 GI6 -> 0 1 }
{ 2 GI6 -> 0 1 2 }
{ 3 GI6 -> 0 1 2 3 }
{ 4 GI6 -> 0 1 2 3 4 }

\ ------------------------------------------------------------------------
TESTING DO LOOP +LOOP I J UNLOOP LEAVE EXIT

{ : GD1 DO I LOOP ; -> }
{ 4 1 GD1 -> 1 2 3 }
{ 2 -1 GD1 -> -1 0 1 }
{ MID-UINT+1 MID-UINT GD1 -> MID-UINT }

{ : GD2 DO I -1 +LOOP ; -> }
{ 1 4 GD2 -> 4 3 2 1 }
{ -1 2 GD2 -> 2 1 0 -1 }
{ MID-UINT MID-UINT+1 GD2 -> MID-UINT+1 MID-UINT }

{ : GD3 DO 1 0 DO J LOOP LOOP ; -> }
{ 4 1 GD3 -> 1 2 3 }
{ 2 -1 GD3 -> -1 0 1 }
{ MID-UINT+1 MID-UINT GD3 -> MID-UINT }

{ : GD4 DO 1 0 DO J LOOP -1 +LOOP ; -> }
{ 1 4 GD4 -> 4 3 2 1 }
{ -1 2 GD4 -> 2 1 0 -1 }
{ MID-UINT MID-UINT+1 GD4 -> MID-UINT+1 MID-UINT }

{ : GD5 123 SWAP 0 DO I 4 > IF DROP 234 LEAVE THEN LOOP ; -> }
{ 1 GD5 -> 123 }
{ 5 GD5 -> 123 }
{ 6 GD5 -> 234 }

{ : GD6  ( PAT: {0 0},{0 0}{1 0}{1 1},{0 0}{1 0}{1 1}{2 0}{2 1}{2 2} )
   0 SWAP 0 DO
      I 1+ 0 DO I J + 3 = IF I UNLOOP I UNLOOP EXIT THEN 1+ LOOP
    LOOP ; -> }
{ 1 GD6 -> 1 }
{ 2 GD6 -> 3 }
{ 3 GD6 -> 4 1 2 }

\ ------------------------------------------------------------------------
TESTING TWO's COMPLIMENT

0 INVERT 8 RSHIFT 1+ CONSTANT STEP
STEP NEGATE CONSTANT -STEP

{ : GD7 DO 1+ STEP +LOOP ; -> }
{ 0 0 0 GD7 -> 100 }
{ : GD8 DO 1+ -STEP +LOOP ; -> }
{ 0 0 -1 GD8 -> 100 }
{ 0 0 0 GD8 -> 1 }

\ ------------------------------------------------------------------------
TESTING DEFINING WORDS: : ; CONSTANT VARIABLE CREATE DOES> >BODY

{ 123 CONSTANT X123 -> }
{ X123 -> 123 }
{ : EQU CONSTANT ; -> }
{ X123 EQU Y123 -> }
{ Y123 -> 123 }

{ VARIABLE V1 -> }
{ 123 V1 ! -> }
{ V1 @ -> 123 }

{ : NOP : POSTPONE ; ; -> }
{ NOP NOP1 NOP NOP2 -> }
{ NOP1 -> }
{ NOP2 -> }

{ : DOES1 DOES> @ 1 + ; -> }
{ : DOES2 DOES> @ 2 + ; -> }
{ CREATE CR1 -> }
{ CR1 -> HERE }
{ ' CR1 >BODY -> HERE }
{ 1 , -> }
{ CR1 @ -> 1 }
{ DOES1 -> }
{ CR1 -> 2 }
{ DOES2 -> }
{ CR1 -> 3 }

{ : WEIRD: CREATE DOES> 1 + DOES> 2 + ; -> }
{ WEIRD: W1 -> }
{ ' W1 >BODY -> HERE }
{ W1 -> HERE 1 + }
{ W1 -> HERE 2 + }

\ ------------------------------------------------------------------------
TESTING EVALUATE

: GE1 S" 123" ; IMMEDIATE
: GE2 S" 123 1+" ; IMMEDIATE
: GE3 S" : GE4 345 ;" ;
: GE5 EVALUATE ; IMMEDIATE

{ GE1 EVALUATE -> 123 }			( TEST EVALUATE IN INTERP. STATE )
{ GE2 EVALUATE -> 124 }
{ GE3 EVALUATE -> }
{ GE4 -> 345 }

{ : GE6 GE1 GE5 ; -> }			( TEST EVALUATE IN COMPILE STATE )
{ GE6 -> 123 }
{ : GE7 GE2 GE5 ; -> }
{ GE7 -> 124 }

\ ------------------------------------------------------------------------
TESTING SOURCE >IN WORD

: GS1 S" SOURCE" 2DUP EVALUATE
       >R SWAP >R = R> R> = ;
{ GS1 -> <TRUE> <TRUE> }

VARIABLE SCANS
: RESCAN?  -1 SCANS +! SCANS @ IF 0 >IN ! THEN ;

{ 2 SCANS !
345 RESCAN?
-> 345 345 }

: GS2  5 SCANS ! S" 123 RESCAN?" EVALUATE ;
{ GS2 -> 123 123 123 123 123 }

: GS3 WORD COUNT SWAP C@ ;
{ BL GS3 HELLO -> 5 CHAR H }
{ CHAR " GS3 GOODBYE" -> 7 CHAR G }
{ BL GS3
DROP -> 0 }				\ BLANK LINE RETURN ZERO-LENGTH STRING

: GS4 SOURCE >IN ! DROP ;
{ GS4 123 456
-> }

\ ------------------------------------------------------------------------
TESTING FILL MOVE

CREATE FBUF 00 C, 00 C, 00 C,
CREATE SBUF 12 C, 34 C, 56 C,
: SEEBUF FBUF C@  FBUF CHAR+ C@  FBUF CHAR+ CHAR+ C@ ;

{ FBUF 0 20 FILL -> }
{ SEEBUF -> 00 00 00 }

{ FBUF 1 20 FILL -> }
{ SEEBUF -> 20 00 00 }

{ FBUF 3 20 FILL -> }
{ SEEBUF -> 20 20 20 }

{ FBUF FBUF 3 CHARS MOVE -> }		\ BIZARRE SPECIAL CASE
{ SEEBUF -> 20 20 20 }

{ SBUF FBUF 0 CHARS MOVE -> }
{ SEEBUF -> 20 20 20 }

{ SBUF FBUF 1 CHARS MOVE -> }
{ SEEBUF -> 12 20 20 }

{ SBUF FBUF 3 CHARS MOVE -> }
{ SEEBUF -> 12 34 56 }

{ FBUF FBUF CHAR+ 2 CHARS MOVE -> }
{ SEEBUF -> 12 12 34 }

{ FBUF CHAR+ FBUF 2 CHARS MOVE -> }
{ SEEBUF -> 12 34 34 }

\ ------------------------------------------------------------------------
TESTING DICTIONARY SEARCH RULES

{ : GDX   123 ; : GDX   GDX 234 ; -> }
{ GDX -> 123 234 }

\ ------------------------------------------------------------------------
TESTING EXEPTIONS

DECIMAL

: t1 9 ;
: c1 1 2 3 ['] t1 CATCH ;
{ c1 -> 1 2 3 9 0 }	\ No THROW executed

: t2 8 0 THROW ;
: c2 1 2 ['] t2 CATCH ;
{ c2 -> 1 2 8 0 }	\ 0 THROW does nothing

: t3 7 8 9 99 THROW ;
: c3 1 2 ['] t3 CATCH ;
{ c3 -> 1 2 99 }	\ restore stack to CATCH depth

: t4 1- DUP 0> IF RECURSE ELSE 999 THROW -222 THEN ;
: c4 3 4 5 10 ['] t4 CATCH -111 ;
{ c4 -> 3 4 5 0 999 -111 }	\ return stack unwinding

: t5 2DROP 2DROP 9999 THROW ;
: c5 1 2 3 4 ['] t5 CATCH DEPTH >R DROP 2DROP 2DROP R> ;
{ c5 -> 5 }

HEX

\ ------------------------------------------------------------------------
TESTING OUTPUT: . ." CR EMIT SPACE SPACES TYPE U.

: OUTPUT-TEST
   ." YOU SHOULD SEE THE STANDARD GRAPHIC CHARACTERS:" CR
   41 BL DO I EMIT LOOP CR
   61 41 DO I EMIT LOOP CR
   7F 61 DO I EMIT LOOP CR
   ." YOU SHOULD SEE 0-9 SEPARATED BY A SPACE:" CR
   9 1+ 0 DO I . LOOP CR
   ." YOU SHOULD SEE 0-9 (WITH NO SPACES):" CR
   [CHAR] 9 1+ [CHAR] 0 DO I 0 SPACES EMIT LOOP CR
   ." YOU SHOULD SEE A-G SEPARATED BY A SPACE:" CR
   [CHAR] G 1+ [CHAR] A DO I EMIT SPACE LOOP CR
   ." YOU SHOULD SEE 0-5 SEPARATED BY TWO SPACES:" CR
   5 1+ 0 DO I [CHAR] 0 + EMIT 2 SPACES LOOP CR
   ." YOU SHOULD SEE TWO SEPARATE LINES:" CR
   S" LINE 1" TYPE CR S" LINE 2" TYPE CR
   ." YOU SHOULD SEE THE NUMBER RANGES OF SIGNED AND UNSIGNED NUMBERS:" CR
   ."   SIGNED: " MIN-INT . MAX-INT . CR
   ." UNSIGNED: " 0 U. MAX-UINT U. CR
;

{ OUTPUT-TEST -> }

\ ------------------------------------------------------------------------
TESTING <# # #S #> HOLD SIGN BASE >NUMBER HEX DECIMAL

: S=  \ ( ADDR1 C1 ADDR2 C2 -- T/F ) COMPARE TWO STRINGS.
   >R SWAP R@ = IF			\ MAKE SURE STRINGS HAVE SAME LENGTH
      R> ?DUP IF			\ IF NON-EMPTY STRINGS
	 0 DO
	    OVER C@ OVER C@ - IF 2DROP <FALSE> UNLOOP EXIT THEN
	    SWAP CHAR+ SWAP CHAR+
         LOOP
      THEN
      2DROP <TRUE>			\ IF WE GET HERE, STRINGS MATCH
   ELSE
      R> DROP 2DROP <FALSE>		\ LENGTHS MISMATCH
   THEN ;

: GP1  <# 41 HOLD 42 HOLD 0 0 #> S" BA" S= ;
{ GP1 -> <TRUE> }

: GP2  <# -1 SIGN 0 SIGN -1 SIGN 0 0 #> S" --" S= ;
{ GP2 -> <TRUE> }

: GP3  <# 1 0 # # #> S" 01" S= ;
{ GP3 -> <TRUE> }

: GP4  <# 1 0 #S #> S" 1" S= ;
{ GP4 -> <TRUE> }

24 CONSTANT MAX-BASE			\ BASE 2 .. 36
: COUNT-BITS
   0 0 INVERT BEGIN DUP WHILE >R 1+ R> 2* REPEAT DROP ;
COUNT-BITS 2* CONSTANT #BITS-UD		\ NUMBER OF BITS IN UD

: GP5
   BASE @ <TRUE>
   MAX-BASE 1+ 2 DO			\ FOR EACH POSSIBLE BASE
      I BASE !				\ TBD: ASSUMES BASE WORKS
      I 0 <# #S #> S" 10" S= AND
   LOOP
   SWAP BASE ! ;
{ GP5 -> <TRUE> }

: GP6
   BASE @ >R  2 BASE !
   MAX-UINT MAX-UINT <# #S #>		\ MAXIMUM UD TO BINARY
   R> BASE !				\ S: C-ADDR U
   DUP #BITS-UD = SWAP
   0 DO					\ S: C-ADDR FLAG
      OVER C@ [CHAR] 1 = AND		\ ALL ONES
      >R CHAR+ R>
   LOOP SWAP DROP ;
{ GP6 -> <TRUE> }

: GP7
   BASE @ >R    MAX-BASE BASE !
   <TRUE>
   A 0 DO
      I 0 <# #S #>
      1 = SWAP C@ I 30 + = AND AND
   LOOP
   MAX-BASE A DO
      I 0 <# #S #>
      1 = SWAP C@ 41 I A - + = AND AND
   LOOP
   R> BASE ! ;

{ GP7 -> <TRUE> }

\ >NUMBER TESTS
CREATE GN-BUF 0 C,
: GN-STRING	GN-BUF 1 ;
: GN-CONSUMED	GN-BUF CHAR+ 0 ;
: GN'		[CHAR] ' WORD CHAR+ C@ GN-BUF C!  GN-STRING ;

{ 0 0 GN' 0' >NUMBER -> 0 0 GN-CONSUMED }
{ 0 0 GN' 1' >NUMBER -> 1 0 GN-CONSUMED }
{ 1 0 GN' 1' >NUMBER -> BASE @ 1+ 0 GN-CONSUMED }
{ 0 0 GN' -' >NUMBER -> 0 0 GN-STRING }	\ SHOULD FAIL TO CONVERT THESE
{ 0 0 GN' +' >NUMBER -> 0 0 GN-STRING }
{ 0 0 GN' .' >NUMBER -> 0 0 GN-STRING }

: >NUMBER-BASED
   BASE @ >R BASE ! >NUMBER R> BASE ! ;

{ 0 0 GN' 2' 10 >NUMBER-BASED -> 2 0 GN-CONSUMED }
{ 0 0 GN' 2'  2 >NUMBER-BASED -> 0 0 GN-STRING }
{ 0 0 GN' F' 10 >NUMBER-BASED -> F 0 GN-CONSUMED }
{ 0 0 GN' G' 10 >NUMBER-BASED -> 0 0 GN-STRING }
{ 0 0 GN' G' MAX-BASE >NUMBER-BASED -> 10 0 GN-CONSUMED }
{ 0 0 GN' Z' MAX-BASE >NUMBER-BASED -> 23 0 GN-CONSUMED }

: GN1	\ ( UD BASE -- UD' LEN ) UD SHOULD EQUAL UD' AND LEN SHOULD BE ZERO.
   BASE @ >R BASE !
   <# #S #>
   0 0 2SWAP >NUMBER SWAP DROP		\ RETURN LENGTH ONLY
   R> BASE ! ;
{ 0 0 2 GN1 -> 0 0 0 }
{ MAX-UINT 0 2 GN1 -> MAX-UINT 0 0 }
{ MAX-UINT DUP 2 GN1 -> MAX-UINT DUP 0 }
{ 0 0 MAX-BASE GN1 -> 0 0 0 }
{ MAX-UINT 0 MAX-BASE GN1 -> MAX-UINT 0 0 }
{ MAX-UINT DUP MAX-BASE GN1 -> MAX-UINT DUP 0 }

: GN2	\ ( -- 16 10 )
   BASE @ >R  HEX BASE @  DECIMAL BASE @  R> BASE ! ;
{ GN2 -> 10 A }

\ ------------------------------------------------------------------------
TESTING INPUT: ACCEPT

CREATE ABUF 80 CHARS ALLOT

: ACCEPT-TEST
   CR ." PLEASE TYPE UP TO 80 CHARACTERS:" CR
   ABUF 80 ACCEPT
   CR ." RECEIVED: " [CHAR] " EMIT
   ABUF SWAP TYPE [CHAR] " EMIT CR
;

{ ACCEPT-TEST -> }

DECIMAL


! ------------------------------------------------------------
!     This program illustrates the following points:
!     (1)  The exponential trap:
!          That is, A**B**C is equal to A**(B**C) rather
!          than (A**B)**C.
!     (2)  The integer division trap:
!          That is, 4/6 is ZERO in Fortran rather than
!          a real number 0.666666
!          Function REAL() is used to illustrate the
!          differences.
!     (3)  The string truncation trap:
!          What if the length assigned to a CHARACTER
!          is shorter than the length of the string you
!          expect the identifier to have?  The third part
!          shows you the effect.
! ------------------------------------------------------------

! gfortran -c fortran_traps.f90
! gfortran fortran_traps.o -o fortran_traps

PROGRAM fortran_traps
   IMPLICIT NONE

   INTEGER, PARAMETER          :: A = 2, B = 2, H = 3
   INTEGER, PARAMETER          :: O = 4, P = 6
   CHARACTER(LEN=5), PARAMETER :: M = 'Smith', N = 'TEXAS'
   CHARACTER(LEN=4), PARAMETER :: X = 'Smith'
   CHARACTER(LEN=6), PARAMETER :: Y = 'TEXAS'

!  The exponential trap

   WRITE(*,*)   "First, the exponential trap:"
   WRITE(*,*)   A, ' ** ', B, ' ** ', H, ' = ', A**B**H
   WRITE(*,*)   '( ', A, ' ** ', B, ' ) **', H, ' = ', (A**B)**H
   WRITE(*,*)   A, ' ** ( ', B, ' ** ', H, ' ) = ', A**(B**H)
   WRITE(*,*)

!  The integer division trap.  Intrinsic function REAL() converts
!  an integer to a real number

   WRITE(*,*)   "Second, the integer division trap:"
   WRITE(*,*)
   WRITE(*,*)   O, ' / ', P, ' = ', O/P
   WRITE(*,*)   'REAL( ', O, ' ) / ', P, ' = ', REAL(O)/P
   WRITE(*,*)   O, ' / REAL( ', P, ' ) = ', O/REAL(P)
   WRITE(*,*)

!  The string truncation trap

   WRITE(*,*)   "Third, the string truncation trap:"
   WRITE(*,*)   'IS ', M, ' STILL IN ', N, '?'
   WRITE(*,*)   'IS ', X, ' STILL IN ', Y, '?'

END PROGRAM fortran_traps


program urutangka
    implicit none
    real :: data(3), store
    integer :: i,j,n

    data = [3,4,1]
    n = size(data)
    do i = 1,n
        do j = 1,n-1
            if (data(j) > data(j+1)) then
                store = data(j)
                data(j) = data(j+1)
                data(j+1) = store
            end if
        end do
    end do
    write(*,*) data
end program


*DECK TRBAK1
      SUBROUTINE TRBAK1 (NM, N, A, E, M, Z)
C***BEGIN PROLOGUE  TRBAK1
C***PURPOSE  Form the eigenvectors of real symmetric matrix from
C            the eigenvectors of a symmetric tridiagonal matrix formed
C            by TRED1.
C***LIBRARY   SLATEC (EISPACK)
C***CATEGORY  D4C4
C***TYPE      SINGLE PRECISION (TRBAK1-S)
C***KEYWORDS  EIGENVECTORS OF A REAL SYMMETRIC MATRIX, EISPACK
C***AUTHOR  Smith, B. T., et al.
C***DESCRIPTION
C
C     This subroutine is a translation of the ALGOL procedure TRBAK1,
C     NUM. MATH. 11, 181-195(1968) by Martin, Reinsch, and Wilkinson.
C     HANDBOOK FOR AUTO. COMP., VOL.II-LINEAR ALGEBRA, 212-226(1971).
C
C     This subroutine forms the eigenvectors of a REAL SYMMETRIC
C     matrix by back transforming those of the corresponding
C     symmetric tridiagonal matrix determined by  TRED1.
C
C     On Input
C
C        NM must be set to the row dimension of the two-dimensional
C          array parameters, A and Z, as declared in the calling
C          program dimension statement.  NM is an INTEGER variable.
C
C        N is the order of the matrix.  N is an INTEGER variable.
C          N must be less than or equal to NM.
C
C        A contains information about the orthogonal transformations
C          used in the reduction by  TRED1  in its strict lower
C          triangle.  A is a two-dimensional REAL array, dimensioned
C          A(NM,N).
C
C        E contains the subdiagonal elements of the tridiagonal matrix
C          in its last N-1 positions.  E(1) is arbitrary.  These
C          elements provide the remaining information about the
C          orthogonal transformations.  E is a one-dimensional REAL
C          array, dimensioned E(N).
C
C        M is the number of columns of Z to be back transformed.
C          M is an INTEGER variable.
C
C        Z contains the eigenvectors to be back transformed in its
C          first M columns.  Z is a two-dimensional REAL array,
C          dimensioned Z(NM,M).
C
C     On Output
C
C        Z contains the transformed eigenvectors in its first M columns.
C
C     Note that TRBAK1 preserves vector Euclidean norms.
C
C     Questions and comments should be directed to B. S. Garbow,
C     APPLIED MATHEMATICS DIVISION, ARGONNE NATIONAL LABORATORY
C     ------------------------------------------------------------------
C
C***REFERENCES  B. T. Smith, J. M. Boyle, J. J. Dongarra, B. S. Garbow,
C                 Y. Ikebe, V. C. Klema and C. B. Moler, Matrix Eigen-
C                 system Routines - EISPACK Guide, Springer-Verlag,
C                 1976.
C***ROUTINES CALLED  (NONE)
C***REVISION HISTORY  (YYMMDD)
C   760101  DATE WRITTEN
C   890831  Modified array declarations.  (WRB)
C   890831  REVISION DATE from Version 3.2
C   891214  Prologue converted to Version 4.0 format.  (BAB)
C   920501  Reformatted the REFERENCES section.  (WRB)
C***END PROLOGUE  TRBAK1
C
      INTEGER I,J,K,L,M,N,NM
      REAL A(NM,*),E(*),Z(NM,*)
      REAL S
C
C***FIRST EXECUTABLE STATEMENT  TRBAK1
      IF (M .EQ. 0) GO TO 200
      IF (N .EQ. 1) GO TO 200
C
      DO 140 I = 2, N
         L = I - 1
         IF (E(I) .EQ. 0.0E0) GO TO 140
C
         DO 130 J = 1, M
            S = 0.0E0
C
            DO 110 K = 1, L
  110       S = S + A(I,K) * Z(K,J)
C     .......... DIVISOR BELOW IS NEGATIVE OF H FORMED IN TRED1.
C                DOUBLE DIVISION AVOIDS POSSIBLE UNDERFLOW ..........
            S = (S / A(I,L)) / E(I)
C
            DO 120 K = 1, L
  120       Z(K,J) = Z(K,J) + S * A(I,K)
C
  130    CONTINUE
C
  140 CONTINUE
C
  200 RETURN
      END


program test

    use omp_lib

    use quadrature2, only: simpson, error_table
    use functions, only: f, fevals, k

    implicit none
    real(kind=8) :: a,b,int_true
    integer :: nvals(12)
    integer :: i, nthreads

    real(kind=8) :: t1, t2, elapsed_time
    integer(kind=8) :: tclock1, tclock2, clock_rate

    nthreads = 1      ! for serial mode
    !$ nthreads = 4   ! for openmp
    !$ call omp_set_num_threads(nthreads)
    print 100, nthreads
100 format("Using ",i2," threads")

    fevals = 0

    k = 1.d3   ! functions module variable for function f2
    a = 0.d0
    b = 2.d0
    int_true = (b-a) + (b**4 - a**4) / 4.d0 - (1.d0/k) * (cos(k*b) - cos(k*a))

    print 10, int_true
 10 format("true integral: ", es22.14)
    print *, " "  ! blank line

    ! values of n to test:   (larger values than before)
    do i=1,12
        nvals(i) = 50 * 2**(i-1)
        enddo

    ! time the call to error_table:
    call system_clock(tclock1)
    call cpu_time(t1)
    call error_table(f, a, b, nvals, int_true, simpson)
    call cpu_time(t2)
    call system_clock(tclock2, clock_rate)

    elapsed_time = float(tclock2 - tclock1) / float(clock_rate)
    print *, " "
    print 11, elapsed_time
 11 format("Elapsed time = ",f12.8, " seconds")

    print 12, t2-t1
 12 format("CPU time = ",f12.8, " seconds")

    ! print the number of function evaluations by each thread:
    do i=0,nthreads-1
        print 101,  i, fevals(i)
101     format("fevals by thread ",i2,": ",i13)
        enddo

    print 102, sum(fevals)
102 format("Total number of fevals: ",i10)

end program test


MODULE m_rand_knuth

    ! Random number generator

    ! Code converted using TO_F90 by Alan Miller
    ! Date: 2000-09-10  Time: 16:37:48
    ! Latest revision - 16 January 2003

    ! FORTRAN 77 version of "ran_array"
    ! from Seminumerical Algorithms by D E Knuth, 3rd edition (1997)
    ! including the MODIFICATIONS made in the 9th printing (2002)
    ! ********* see the book for explanations and caveats! *********
    ! Author: Steve Kifowit
    ! http://ourworld.compuserve.com/homepages/steve_kifowit
    ! with modifications by Alan Miller to rnarry and rnstrt based upon
    ! Knuth's code.

    ! For Donald Knuth's Fortran 77 versions, go to:
    ! http://www-cs-faculty.stanford.edu/~knuth/programs
    ! Look for frng.f and frngdb.f

    IMPLICIT NONE
    INTEGER, PARAMETER  :: kk = 100, ll = 37, mm = 2**30, tt = 70, kkk = kk + kk - 1
    INTEGER, SAVE       :: ranx(kk)

CONTAINS

    SUBROUTINE rand_knuth(u, n)

        ! Generate an array of n real values between 0 and 1.

        REAL, INTENT(OUT)    :: u(:)
        INTEGER, INTENT(IN)  :: n

        ! Local array
        INTEGER  :: aa(n)

        CALL rnarry(aa, n)
        u(1:n) = SCALE(REAL(aa), -30)

        RETURN
    END SUBROUTINE rand_knuth

    SUBROUTINE rnarry(aa, n)

        ! Generate an array of n integers between 0 and 2^30-1.

        INTEGER, INTENT(OUT)  :: aa(:)
        INTEGER, INTENT(IN)   :: n

        ! Local variables
        INTEGER  :: j

        aa(1:kk) = ranx(1:kk)
        DO j = kk + 1, n
            aa(j) = aa(j - kk) - aa(j - ll)
            IF (aa(j) < 0) aa(j) = aa(j) + mm
        END DO
        DO j = 1, ll
            ranx(j) = aa(n + j - kk) - aa(n + j - ll)
            IF (ranx(j) < 0) ranx(j) = ranx(j) + mm
        END DO
        DO j = ll + 1, kk
            ranx(j) = aa(n + j - kk) - ranx(j - ll)
            IF (ranx(j) < 0) ranx(j) = ranx(j) + mm
        END DO

        RETURN
    END SUBROUTINE rnarry

    SUBROUTINE rand_knuth_start(seed)

        ! Initialize integer array ranx using the input seed.

        INTEGER*8, INTENT(IN)  :: seed

        ! Local variables
        INTEGER  :: x(kkk), j, ss, sseed, t

        IF (seed < 0) THEN
            sseed = mm - 1 - MOD(-1 - seed, mm)
        ELSE
            sseed = MOD(seed, mm)
        END IF
        ss = sseed - MOD(sseed, 2) + 2
        DO j = 1, kk
            x(j) = ss
            ss = ISHFT(ss, 1)
            IF (ss >= mm) ss = ss - mm + 2
        END DO
        x(kk + 1:kkk) = 0
        x(2) = x(2) + 1
        ss = sseed
        t = tt - 1
10      DO j = kk, 2, -1
            x(j + j - 1) = x(j)
        END DO
        DO j = kkk, kk + 1, -1
            x(j - (kk - ll)) = x(j - (kk - ll)) - x(j)
            IF (x(j - (kk - ll)) < 0) x(j - (kk - ll)) = x(j - (kk - ll)) + mm
            x(j - kk) = x(j - kk) - x(j)
            IF (x(j - kk) < 0) x(j - kk) = x(j - kk) + mm
        END DO
        IF (MOD(ss, 2) == 1) THEN
            DO j = kk, 1, -1
                x(j + 1) = x(j)
            END DO
            x(1) = x(kk + 1)
            x(ll + 1) = x(ll + 1) - x(kk + 1)
            IF (x(ll + 1) < 0) x(ll + 1) = x(ll + 1) + mm
        END IF
        IF (ss /= 0) THEN
            ss = ISHFT(ss, -1)
        ELSE
            t = t - 1
        END IF
        IF (t > 0) GO TO 10

        DO j = 1, ll
            ranx(j + kk - ll) = x(j)
        END DO
        DO j = ll + 1, kk
            ranx(j - ll) = x(j)
        END DO

        DO j = 1, 10
            CALL rnarry(x, kkk)
        END DO

        RETURN
    END SUBROUTINE rand_knuth_start

    ! Initialization subroutine

    subroutine rand_knuth_init(seed1)

        integer*8 :: seed1

        call rand_knuth_start(seed1)

        return
    end subroutine rand_knuth_init

END MODULE m_rand_knuth


!==============================================================================!
  subroutine Prec_Form(ni, a, d, prec)
!------------------------------------------------------------------------------!
!   Forms preconditioning matrix "d" from provided matrix "a".                 !
!------------------------------------------------------------------------------!
  implicit none
!---------------------------------[Arguments]----------------------------------!
  integer           :: ni
  type(Matrix_Type) :: a
  type(Matrix_Type) :: d
  character(len=80) :: prec  ! preconditioner
!-----------------------------------[Locals]-----------------------------------!
  real    :: sum1
  integer :: i, j, k
!==============================================================================!

  !---------------------------------!
  !   1) diagonal preconditioning   !
  !---------------------------------!
  if(prec .eq. 'DIAGONAL') then
    do i = 1, ni
      d % val(d % dia(i)) = a % val(a % dia(i))
    end do

  !--------------------------------------------!
  !   2) incomplete cholesky preconditioning   !
  !--------------------------------------------!
  else if(prec .eq. 'INCOMPLETE_CHOLESKY') then
    do i = 1, ni
      sum1 = a % val(a % dia(i))       ! take diaginal entry
      do j = a % row(i), a % dia(i)-1  ! only lower traingular
        k = a % col(j)
        sum1 = sum1 - d % val(d % dia(k)) * a % val(j) * a % val(j)
      end do
      d % val(d % dia(i)) = 1.0 / sum1
    end do

  !---------------------------!
  !   .) no preconditioning   !
  !---------------------------!
  else
    do i = 1, ni
      d % val(d % dia(i)) = 1.0
    end do
  end if

  end subroutine


module slf_findzer

    use iso_fortran_env, only: r64 => real64
    implicit none

    interface findzer
        module procedure findzer_single, findzer_array
    end interface

    integer, parameter :: findzer_iter = 64
    private :: ramp

contains

    subroutine findzer_single(x, xlo, xhi, delx, f)

        real(r64), intent(inout) :: x
        real(r64), intent(in) :: xlo,xhi,delx

        interface
            pure subroutine f(x,y,dy)
                import r64
                real(r64), intent(in) :: x
                real(r64), intent(out) :: y
                real(r64), intent(out), optional :: dy
            end subroutine
        end interface

        integer :: i
        real(r64) :: dx,yx,y,x1

        main_loop : do i = 1,FINDZER_ITER

            call f(x,y,yx)
            if (yx /= 0) then
                dx = - y / yx
            elseif ( dx == 0 ) then
                exit main_loop
            end if

            x1 = x + dx * ramp(i,findzer_iter)
            if ( x1 > xhi ) x1 = (x + xhi) / 2
            if ( x1 < xlo ) x1 = (x + xlo) / 2
            x = x1

            if (abs(dx) < abs(delx)) exit main_loop

        end do main_loop

    end subroutine

    subroutine findzer_array(x, nx, xlo, xhi, delx, f)

        integer, intent(in) :: nx
        real(r64), intent(inout), dimension(nx) :: x
        real(r64), intent(in), dimension(nx)  :: xlo,xhi
        real(r64), intent(in)  :: delx

        interface
            pure subroutine f(x,y,dy)
                import r64
                real(r64), intent(in), dimension(:)  :: x
                real(r64), intent(out), dimension(size(x))  :: y
                real(r64), intent(out), dimension(size(x)) , optional :: dy
            end subroutine
        end interface

        integer :: i
        real(r64), dimension(nx) :: dx,yx,y,x1
        logical, dimension(nx) :: converged

        converged = .false.
        dx = 0

        main_loop : do i = 1,FINDZER_ITER

            call f(x,y,yx)

            where ( .not. converged )

                where ( yx /= 0 )
                    dx = - y / yx
                elsewhere ( dx == 0 )
                    converged = .true.
                end where

                x1 = x + dx * ramp(i,findzer_iter)
                where ( x1 > xhi ) x1 = (x + xhi) / 2
                where ( x1 < xlo ) x1 = (x + xlo) / 2
                x = x1

                converged = abs(dx) < abs(delx)
            end where

            if (all(converged)) exit main_loop

        end do main_loop

    end subroutine

    elemental function ramp(i,n) result(y)
      integer, intent(in) :: i,n
      real(r64) :: t,y
      t = merge(real(i) / n, 1.0, i .lt. n)
      y = (3 - 2*t) * t**2
    end function

end module


! { dg-do compile }
! { dg-options "-fdump-tree-original" }
! Tests the fix for PR 30872, in which the array element references bo(1,1) etc.
! would be wrong for rank > 1.
!
! Contributed by Joost VandeVondele <jv244@cam.ac.uk>
!
 INTEGER, PARAMETER, DIMENSION(2,3) :: bo= &
                    RESHAPE((/-1,1,-2,2,-3,3/),(/2,3/))
 REAL(kind=8), DIMENSION(  &
          bo(1,1):bo(2,1), &
          bo(1,2):bo(2,2), &
          bo(1,3):bo(2,3)) :: out_val
 out_val=0.0
END
! Scan for the 105 in the declaration real8 out_val[105];
! { dg-final { scan-tree-dump-times "105" 1 "original" } }


function count_paths(matrix2,s1,s2) result(sum)
implicit none
	integer:: i,matrix2(5,5),s1,s2
	real(kind=8):: sum,floodfill
	sum=0
	do i = 1,5
		sum = sum+floodfill(1, i,matrix2,s1,s2)
	end do
end function count_paths

recursive function floodfill(r ,c,matrix1,s1,s2) result(u)
implicit none
	integer:: r,c,matrix1(5,5),r1,c1,s1,s2
	real(kind=8):: u
	u=0
	if (r.LE.5 .AND. c.LE.5 .AND. r.GE.1 .AND. c.GE.1 .AND. matrix1(r,c).EQ.1 ) then !.AND. r.GE.1 .AND. c.GE.1 excluded due to error: stack overflow
		if(r.EQ.5) then
			u=1
		else
			r1=r
			c1=c
			u= floodfill(r1 + 1, c1,matrix1,s1,s2) + floodfill(r1 + 1, c1 + 1,matrix1,s1,s2) + floodfill(r1 + 1, c1 - 1,matrix1,s1,s2)
		end if
	end if
end function floodfill

integer function getkey(inp1,inp2,inp3)
	!IMPLICIT NONE
	real :: inp1,inp2,inp3,sdr1,sdr2,sdr3
	integer :: key,m=0
	character(8)  :: date
	character(10) :: time
	character(5)  :: zone
	call date_and_time(date,time,zone)
	call date_and_time(DATE=date,ZONE=zone)
	call date_and_time(TIME=time)
	read( date, '(f10.0)' )  sdr1
	read( time, '(f10.0)' )  sdr2
	read( zone, '(f10.0)' )  sdr3
	sdr3=sdr1/sdr3+sdr2+m
	sdr3=rand(int(sdr3))
	!print *,sdr3
	m=m+31 !recently chenged from +
	if (sdr3 .GT. 0 .AND. sdr3 .LE. inp1) THEN
		key = 1 !blocked
	end if
	if (sdr3 .GE. inp1 .AND. sdr3 .LE. inp1+inp2) then
		key = 2 !empty
	end if
	if (sdr3 .GE. inp1+inp2 .AND. sdr3 .LT. 1) then
		key=3 !percolation material
	end if
	!print *, inp1,inp2,inp3
	getkey = key
	key=0
end function getkey

program perc
implicit none
!dimension is 2, but size is determined at runtime
!integer, dimension (:,:), allocatable :: darry
integer :: s1,s2,i,j,key,getkey,darry1(5,5)
real(kind=8) :: p,count_paths
real::inp1, inp2 ,inp3,g,h,t1,t2,mn
!print*, "Enter p1, p2 and p3:"
!read*, inp1, inp2 ,inp3
!print*, "Enter the dimensions of the array:"
!read*, s1, s2
inp1=0
inp2=0
inp3=0
s1=5
s2=5
mn=1000
do inp2=0.35,0.9,0.01
inp3=1-inp2
if(inp3.LE.0) then
exit
end if
! allocate memory
!allocate ( darry1(s1,s2) )
do i = 1, s1
	do j = 1, s2
		key=getkey(inp1,inp2,inp3)
		!print *, key
		if (key .EQ. 1) then
			darry1(i,j)=2
			end if
		if (key .EQ. 2) then
			darry1(i,j)=0
			end if
		if (key .EQ. 3) then
			darry1(i,j)=1  !input array elements
		end if
	END DO
END DO
p=count_paths(darry1,s1,s2)
OPEN(UNIT=1,FILE="data1.txt",position='append',FORM="FORMATTED",STATUS="OLD")  !open textfile

!write(1,*)inp2,",",inp3
!write(1,*) " "

!do i = 1, s1
	!write(1,*) inp2,inp3,p
		!write(UNIT=1,FMT="(A)",advance="yes") " "	!put linebreak in txt
	!print*," " 	!put linebreak in console
      !do j = 1, s2
		!if(darry1(i,j).EQ.1) then
		!write(UNIT=1,FMT="(A)",advance="no") "#" !write to txt
		!end if
		!if(darry1(i,j).EQ.0) then
		!write(UNIT=1,FMT="(A)",advance="no") "X" !write to txt
		!end if
		!if(darry1(i,j).EQ.2) then
		!write(UNIT=1,FMT="(A)",advance="no") "O" !write to txt
		!end if
		!write(UNIT=1,FMT="(A)",advance="no") " " !write to txt
	!write(*,"(I2)",advance="no") darry1(i,j)
	!write(*,"(A)",advance="no") " " !write to console
!END DO
!END DO
!print*,darry1
!print*," " !linebreak
print*,p
!end do
write(1,*)inp2,",",p
end do
write(1,*)inp2,",",p
close(1)
!PAUSE
end program perc


MODULE unionFindTree_module
    implicit none
    ! --
    ! This module contains the subroutines of 2D connected-component labeling (CCL)
    ! whose algorithm is introduced by Wu et. al (2009).
    !
    ! Only the subroutines related to the unionFindTree that is
    ! used in the first_scan is in this file.
    !
    ! -- Hsiao, Wei-Ting (floatlikecloud) wrote in Oct 2017

    CONTAINS
    SUBROUTINE flattenL(tree, n)
        ! flatten the tree in to height 1 in consecutive labels
        ! used in the final stage of first_scan
        implicit none
        integer, intent(in)    :: n
        integer, intent(inout) :: tree(:)
        integer :: i, k

        k = 1
        do i = 1, n-1
            if (tree(i).lt.i) then
                tree(i) = tree(tree(i))
            else
                tree(i) = k
                k = k + 1
            end if
        end do
    END SUBROUTINE flattenL

    SUBROUTINE find_root_compress(tree, nowNode, root)
        ! find the root of the tree and compress the path at the same time
        implicit none
        integer, intent(inout) :: tree(:), nowNode
        integer, intent(out)   :: root

        CALL find_root(tree, nowNode, root)
        CALL set_root(tree, nowNode, root)
    END SUBROUTINE find_root_compress

    SUBROUTINE union(tree, node_i, node_j, root)
        ! unify two trees
        implicit none
        integer, intent(inout) :: tree(:), node_i, node_j
        integer, intent(out)   :: root
        integer :: root_j

        CALL find_root_compress(tree, node_i, root)
        if (node_i.ne.node_j) then
            CALL find_root_compress(tree, node_j, root_j)
            if (root.gt.root_j) root = root_j
            CALL set_root(tree, node_j, root)
        end if
        CALL set_root(tree, node_i, root)
    END SUBROUTINE union

    SUBROUTINE find_root(tree, nowNode, root)
        ! finding root
        implicit none
        integer, intent(in)  :: tree(:), nowNode
        integer, intent(out) :: root

        root = nowNode
        do while (tree(root).lt.root)
            root = tree(root)
        end do
    END SUBROUTINE find_root

    SUBROUTINE set_root(tree, nowNode, root)
        ! setting of the nodes in the tree to connected directly onto the root
        implicit none
        integer, intent(in)    :: root
        integer, intent(inout) :: tree(:), nowNode
        integer :: nowNode2

        do while (tree(root).lt.nowNode)
            nowNode2 = tree(nowNode)
            tree(nowNode) = root
            nowNode = nowNode2
        end do
        tree(nowNode) = root
    END SUBROUTINE set_root

END MODULE unionFindTree_module


program ch0919
    ! Alternative Format Specification Using a
    ! Character Variable
    implicit none

    integer :: t
    character(30) :: fmt_100 = '(1x,i3," * 12 = ",i3)'

    print *, ' '
    print *, ' Twelve times table'
    print *, ' '
    do t = 1, 12
        write(*,fmt_100) t, t*12
    end do
end program


CALL ISORT@(b, a, n)
! n = number of elements
! a = array to be sorted
! b = array of indices of a. b(1) 'points' to the minimum value etc.


program ch0813
    ! Array Element Ordering
    implicit none

    integer :: j1 = 1
    integer :: k1 = 2
    integer :: j2 = 1
    integer :: k2 = 5
    integer :: s1, s2, d1, position

    d1 = k1-j1+1
    print *, ' Row  Column    Position'
    do s1 = j1, k1
        do s2 = j2, k2
            position = 1+(s1-j1)+(s2-j2)*d1
            print 100, s1, s2, position
        end do
    end do

100 format (3x, i2, 6x, i2, 10x, i2)
end program


module crc32_m
    use iso_fortran_env
    implicit none
    integer(int32) :: crc_table(0:255)
contains
    subroutine update_crc(a, crc)
        integer :: n, i
        character(*) :: a
        integer(int32) :: crc

        crc = not(crc)
        n = len(a)
        do i = 1, n
            crc = ieor(shiftr(crc, 8), crc_table(iand(ieor(crc, iachar(a(i:i))), 255)))
        end do
        crc = not(crc)
    end subroutine

    subroutine init_table
        integer :: i, j
        integer(int32) :: k

        do i = 0, 255
            k = i
            do j = 1, 8
                if (btest(k, 0)) then
                    k = ieor(shiftr(k, 1), -306674912)
                else
                    k = shiftr(k, 1)
                end if
            end do
            crc_table(i) = k
        end do
    end subroutine
end module

program crc32
    use crc32_m
    implicit none
    integer(int32) :: crc = 0
    character(*), parameter :: s = "The quick brown fox jumps over the lazy dog"
    call init_table
    call update_crc(s, crc)
    print "(Z8)", crc
end program