!
!  MC simulation of hard rectangles in a periodic square box
!

implicit none

integer, parameter :: nx_part = 2000
integer, parameter :: nx_box  = 10
integer, parameter :: nb_part  = 100
real(8) :: L1, D1
real(8) :: Rad 
real(8), parameter :: drho = 0.5d0
integer :: nx_rho
logical :: overlap, overlap_wall
real(8), dimension(:), allocatable :: rho, rho2, angulo
real(8) :: L2, D2, r, x0, y0, varphi, x1, y1, d_area
real(8) :: phi, theta, dx, dang, box, rr, alfa, r2, sp, pack_ref
real(8) :: phi_aim, Rad_ret
real(8), parameter :: pi = 4d0*datan(1d0)
real(8), dimension(nx_part) :: x, y, ang
integer :: i, j, j1, num, n, k, nboxes, N_steps, p, q, ir, init, nclu
integer, dimension (nx_part) :: ix, iy
integer, dimension (nx_box, nx_box) :: nb
integer, dimension (nx_box, nx_box, nb_part) :: ind
real(8), dimension (nx_part) :: nc, nct

!
!  read parameters from input file
!
open (1, file = 'HRb.par')
read (1, *) init     ! 0 build up conf., 1 read from file
read (1, *) N        ! N (in case not read in from file)
read (1, *) L1, D1   ! L1, D1 (in case not read in from file)
read (1, *) phi_aim  ! reference phi (in case not read in from file)
read (1, *) N_steps 
read (1, *) dx, dang 
close (1)

if (init == 1) then

    write(*, '(''Read configuration from file HRb.inp'')')

    open (8, file = 'HRb.inp')
    read (8, *) N, L1, D1, Rad
    do i = 1, N
       read (8, *) x(i), y(i), ang(i)
    end do
    close (8)

else

    Rad=1.5*dsqrt(N/(pi*phi_aim/L1/D1))

!
!  Locate N rectangles inside cavity of Radius Rad
!

    write(*, '(''Locating '',i5,'' particles into cavity...'')') N

    do i = 1, N
1      r = Rad*rand()
       theta = 2*pi*rand()
       varphi= 2*pi*rand()
       x0 = r*dcos(theta); y0 = r*dsin(theta)
       do j = 1, i - 1
          if (overlap (x(j) - x0, y(j) - y0, varphi,  &
              ang(j), L1, D1, L1, D1)) go to 1
       end do
       if (overlap_wall (x0, y0, varphi, L1, D1, Rad)) go to 1
       x(i) = x0; y(i) = y0; ang(i) = varphi
    end do
    write(*, '(''Compressing configuration up to required density'')')
    call compress (L1, D1, phi_aim, Rad_ret, N, x, y, ang)
    Rad = Rad_ret 

end if

phi = N*L1*D1/(pi*Rad**2)

write(*, '(''Writing initial configuration on file HR.pl0'')')
call write_conf (0, L1, D1, N, Rad, x, y, ang)
    
nx_rho = int(Rad/drho) + 1
allocate (rho(nx_rho), rho2(nx_rho), angulo(nx_rho))

box = 2*Rad/nx_box

write(*, '(''Simulation starts...'')')
write(*, '(''phi.................'',f10.5)') phi

rho = 0; rho2 = 0; angulo = 0; nct = 0; nclu = 0

!
! MC steps - do loop
!

do k = 1, N_steps

!
!  Sort particles in boxes
!

   nb = 0

   do i = 1, N
      ix(i) = (x(i) + Rad)/box + 1
      iy(i) = (y(i) + Rad)/box + 1
      if (ix(i) > nx_box .or. iy(i) > nx_box) then
          print *,x(i), y(i)
          print *,ix(i), iy(i)
          stop 'Incorrect number of boxes'
      end if
      nb(ix(i), iy(i)) = nb(ix(i), iy(i)) + 1
      if (nb(ix(i), iy(i)) > nb_part) then
          print *,ix(i), iy(i), nb(ix(i), iy(i))
          stop 'Incorrect dimension for box particles'
      end if
      ind(ix(i), iy(i), nb(ix(i), iy(i))) = i
   end do

   do i = 1, N
      x0 = x(i); y0 = y(i)
      x1 = x0 + (2*rand() - 1)*dx
      y1 = y0 + (2*rand() - 1)*dx
      varphi = ang(i) + (2*rand() - 1)*dang
      if (overlap_wall (x1, y1, varphi, L1, D1, Rad)) go to 2
      do p = max(1, ix(i) - 1), min(ix(i) + 1, nx_box)
         do q = max(1, iy(i) - 1), min(iy(i) + 1, nx_box)
            do j1 = 1, nb(p, q)
               j = ind(p, q, j1)
               if (i /= j) then
                   if (overlap (x(j) - x1, y(j) - y1, varphi,  &
                        ang(j), L1, D1, L1, D1)) go to 2
               end if
            end do
         end do
      end do
      x(i) = x1; y(i) = y1; ang(i) = varphi
2     continue
      r2 = dsqrt(x(i)**2 + y(i)**2)
      ir = r2/drho + 1
      rho(ir) = rho(ir) + 1
      sp = (x(i)*dcos(ang(i)) + y(i)*dsin(ang(i)))/r2
      angulo(ir) = angulo(ir) + 2d0*sp**2 - 1d0
   end do

   if (k == 50*(k/50)) then
       nclu = nclu + 1
       call cluster (N, L1, D1, Rad, x, y, ang, nc)
       do i = 1, N
          nct(i) = nct(i) + nc(i)
       end do
   end if

   if (k == 100*(k/100)) write (*, '(i6,'' MC steps completed'')') k

end do

open (2, file = 'HRb.clu')
do i = 1, N
   nct(i) = nct(i)/nclu
   write (2, *) i, nct(i)
end do
close (2)

open (2, file = 'HRb.rho'); open (3, file = 'HRb.psi')
do ir = 1, nx_rho
   rr = (ir - 0.5d0)*drho
   d_area = pi*((rr + 0.5d0*drho)**2 - (rr - 0.5d0*drho)**2)
   write (2, '(2f10.4)') rr, rho(ir)/N_steps/d_area
   if (dabs(rho(ir)) > 1d-6) then
       write (3, '(2f10.4)') rr, angulo(ir)/rho(ir)
   end if 
end do
close(2); close(3)

!
!  Write final configuration on output file
!

write(*, '(''Writing final configuration on file HR.pl1'')')
call write_conf (1, L1, D1, N, Rad, x, y, ang)

open (8, file = 'HRb.out')
write (8, *) N, L1, D1, Rad
do i = 1, N
   write (8, *) x(i), y(i), ang(i)
end do
close (8)

end 

subroutine write_conf (l, L1, D1, N, Rad, x, y, ang)

implicit none

integer, parameter :: nx_part = 2000
real(8) :: L1, D1, Rad
real(8) :: x1, y1, x2, y2, x3, y3, x4, y4
real(8) :: u1, v1, u2, v2, u3, v3, u4, v4
real(8), dimension(nx_part) :: x, y, ang
real(8), parameter :: pi = 4d0*datan(1d0)
integer :: i, N, l
character(1) :: nc

write (nc, '(i1)') l
open(1, file = 'HRb.pl'//trim(nc)) 

do i = 1, N
   x1 = L1/2d0; y1 = D1/2d0
   x2 =-L1/2d0; y2 = D1/2d0
   x3 =-L1/2d0; y3 =-D1/2d0
   x4 = L1/2d0; y4 =-D1/2d0
   u1 = x1*dcos(ang(i)) - y1*dsin(ang(i))
   v1 = x1*dsin(ang(i)) + y1*dcos(ang(i))
   u2 = x2*dcos(ang(i)) - y2*dsin(ang(i))
   v2 = x2*dsin(ang(i)) + y2*dcos(ang(i))
   u3 = x3*dcos(ang(i)) - y3*dsin(ang(i))
   v3 = x3*dsin(ang(i)) + y3*dcos(ang(i))
   u4 = x4*dcos(ang(i)) - y4*dsin(ang(i))
   v4 = x4*dsin(ang(i)) + y4*dcos(ang(i))
   write(1, *) x(i) + u1, y(i) + v1
   write(1, *) x(i) + u2, y(i) + v2
   write(1, *) x(i) + u3, y(i) + v3
   write(1, *) x(i) + u4, y(i) + v4
   write(1, *) x(i) + u1, y(i) + v1
   write(1, *) 
end do
do i = 1, 360
   write(1, *) Rad*dcos(i*pi/180d0), Rad*dsin(i*pi/180d0)
end do
close(1)

end subroutine write_conf

!
!  Overlap function for one HR and a circular interior wall
!

function overlap_wall (x, y, f, L, D, Rad)

implicit none

logical :: overlap_wall
real(8) :: x, y, f, L, D, Rad, Rad2, r
real(8) :: x1, y1, x2, y2, x3, y3, x4, y4
real(8) :: u1, v1, u2, v2, u3, v3, u4, v4

overlap_wall = .true.
Rad2 = Rad**2
x1 = L/2d0; y1 = D/2d0
x2 =-L/2d0; y2 = D/2d0
x3 =-L/2d0; y3 =-D/2d0
x4 = L/2d0; y4 =-D/2d0
u1 = x + x1*dcos(f) - y1*dsin(f)
v1 = y + x1*dsin(f) + y1*dcos(f)
r = u1**2 + v1**2
if (r > Rad2) return
u2 = x + x2*dcos(f) - y2*dsin(f)
v2 = y + x2*dsin(f) + y2*dcos(f)
r = u2**2 + v2**2
if (r > Rad2) return
u3 = x + x3*dcos(f) - y3*dsin(f)
v3 = y + x3*dsin(f) + y3*dcos(f)
r = u3**2 + v3**2
if (r > Rad2) return
u4 = x + x4*dcos(f) - y4*dsin(f)
v4 = y + x4*dsin(f) + y4*dcos(f)
r = u4**2 + v4**2
if (r > Rad2) return
overlap_wall = .false.

end function overlap_wall

!
!  Overlap function for two HR's 
!

function overlap (x, y, f1, f2, L1, D1, L2, D2)

implicit none

logical :: overlap

real(8) :: x, y, f1, f2, f, x1, y1, L1, D1, L2, D2, x2, y2
real(8) :: lambda1, lambda2, det
real(8) :: x11, x12, y11, y12, x21, y21, x22, y22
real(8), dimension(4, 2) :: c1, c2
integer :: i, j, n, k, j1, k1

overlap = .true.

x1 = x*dcos(f1) + y*dsin(f1)
y1 =-x*dsin(f1) + y*dcos(f1)
f = f2 - f1

n = 0
do i = 1, -1, -2
   do j = 1, -1, -2
      n = n + 1
      c1(n, 1) = 0.5d0*i*j*L1; c1(n, 2) = 0.5d0*i*D1
      x2 = 0.5d0*i*j*L2; y2 = 0.5d0*i*D2
      c2(n, 1) = x1 + x2*dcos(f) - y2*dsin(f)
      c2(n, 2) = y1 + x2*dsin(f) + y2*dcos(f)
   end do
end do

do j = 1, 4
   j1 = j + 1
   if (j1 > 4) j1 = 1 
   do k = 1, 4
      k1 = k + 1
      if (k1 > 4) k1 = 1 
      x11 = c1(j, 1); y11 = c1(j, 2);
      x12 = c1(j1, 1); y12 = c1(j1, 2);
      x21 = c2(k, 1); y21 = c2(k, 2);
      x22 = c2(k1, 1); y22 = c2(k1, 2);
      det = (x12 - x11)*(y21 - y22) - (y12 - y11)*(x21 - x22)
      lambda1 = ((x21 - x11)*(y21 - y22) - (y21 - y11)*(x21 - x22))/det
      lambda2 = ((y21 - y11)*(x12 - x11) - (x21 - x11)*(y12 - y11))/det
      if (lambda1 > 0d0 .and. lambda1 < 1d0 .and. lambda2 > 0d0 .and. lambda2 < 1d0) return
   end do
end do

overlap = .false.

end

subroutine compress (L1, D1, phi, Rad_ret, N, x, y, ang)
implicit none
integer, parameter :: nx_box  = 10
integer, parameter :: nb_part  = 100
logical :: overlap, overlap_wall
integer, parameter :: nx_part = 2000
real(8), parameter :: pi = 4d0*datan(1d0)
real(8) :: L1, D1
real(8), dimension(nx_part) :: x, y, ang
integer, dimension (nx_part) :: ix, iy
integer, dimension (nx_box, nx_box) :: nb
integer, dimension (nx_box, nx_box, nb_part) :: ind
real(8) :: phi, Rad, Rad0, theta, varphi, x0, y0, x1, y1, r
real(8) :: dx, dang, box, pack, scale, du, rmax, Rad_ret, pack0
integer :: i, j, k, N, p, q, j1, eps

dx = 0.2d0; dang = 0.05d0

100 continue

!
! Calculates radius of confining region
!

rmax = 0d0
do i = 1, N
   r = dsqrt(x(i)**2 + y(i)**2)
   if (r > rmax) rmax = r
end do
Rad0 = rmax + dsqrt(L1**2 + D1**2)/2d0

pack0 = N*L1*D1/(pi*Rad0**2)

write (*, '('' current packing fraction...'',f6.3,'' target...'',f6.3)') &
     pack0, phi
if (pack0 > phi) then
    Rad_ret = Rad0
    return
end if

do i = 1, N
   if (overlap_wall (x(i), y(i), ang(i), L1, D1, Rad0)) then
       print *,'r, Rad0=',dsqrt(x(i)**2+y(i)**2), Rad0
       stop 'solape'
   end if
end do

box = 2*Rad0/nx_box

do k = 1, 100

   if (k == 20*(k/20)) then
       if (eps == 10) eps = 0
   else
       eps = 10
   end if

   nb = 0

   do i = 1, N
      ix(i) = (x(i) + Rad0)/box + 1
      iy(i) = (y(i) + Rad0)/box + 1
      if (ix(i) > nx_box .or. iy(i) > nx_box) then
          print *,x(i), y(i)
          print *,ix(i), iy(i)
          stop 'Incorrect number of boxes'
      end if
      nb(ix(i), iy(i)) = nb(ix(i), iy(i)) + 1
      if (nb(ix(i), iy(i)) > nb_part) then
          print *,ix(i), iy(i), nb(ix(i), iy(i))
          stop 'Incorrect dimension for box particles'
      end if
      ind(ix(i), iy(i), nb(ix(i), iy(i))) = i
   end do
   do i = 1, N
      x0 = x(i); y0 = y(i)
      x1 = x0 + (2*rand() - 1)*dx
      y1 = y0 + (2*rand() - 1)*dx
      varphi = ang(i) + (2*rand() - 1)*dang
      if (overlap_wall (x1, y1, varphi, L1, D1, Rad0)) go to 9
      do p = max(1, ix(i) - 1), min(ix(i) + 1, nx_box)
         do q = max(1, iy(i) - 1), min(iy(i) + 1, nx_box)
            do j1 = 1, nb(p, q)
               j = ind(p, q, j1)
               if (i /= j) then
               if (overlap (x(j) - x1, y(j) - y1, varphi,  &
                    ang(j), L1, D1, L1, D1)) go to 9
               end if
            end do
         end do
      end do
      du = eps*(dsqrt(x1**2 + y1**2) - dsqrt(x0**2 + y0**2))
      if (dexp(du) < rand()) then
         x(i) = x1; y(i) = y1; ang(i) = varphi
      end if
9     continue
   end do
end do

go to 100

end subroutine compress 


subroutine cluster (N, L1, D1, Rad, x, y, ang, nc)

implicit none

integer, parameter :: nx_part = 2000
real(8) :: rcl, rclsq, rxj, ryj, rxjk, ryjk, rjksq, tol_ang, da
real(8) :: L1, D1, Rad
real(8), dimension (nx_part) :: x, y, ang, nc
integer, dimension (nx_part) :: l
integer :: i, N, lk, j, k, nit, lit, it
real(8), parameter :: pi = 4d0*datan(1d0)

rcl = 1.8d0*D1
tol_ang = dcos(10*pi/180d0)
nc = 0d0

rclsq = rcl**2

do i = 1, N
   l(i) = i
end do

do i = 1, N - 1

   if (i == l(i)) then
       j = i
       rxj = x(j)
       ryj = y(j)

       do k = i + 1, N
          lk = l(k)
          if (lk == k) then
              rxjk = rxj - x(k)
              ryjk = ryj - y(k)
              rjksq = rxjk**2 + ryjk**2
              da = 1d0 - dabs(dcos(ang(j) - ang(k)))
              if (rjksq <= rclsq .and. da <= tol_ang .and. &
                  dsqrt(rxj**2 + ryj**2) < Rad - 3*L1 .and. &
                  dsqrt(x(k)**2 + x(k)**2) < Rad - 3*L1) then
                  l(k) = l(j)
                  l(j) = lk
              end if
          end if
       end do

       j = l(j)
       rxj = x(j)
       ryj = y(j)
30     if (j /= i) then
           do k = i + 1, N
              lk = l(k)
              if (lk == k) then
                  rxjk = rxj - x(k)
                  ryjk = ryj - y(k)
                  rjksq = rxjk**2 + ryjk**2
                  da = 1d0 - dabs(dcos(ang(j) - ang(k)))
                  if (rjksq <= rclsq .and. da <= tol_ang .and. &
                  dsqrt(rxj**2 + ryj**2) < Rad - 3*L1 .and. &
                  dsqrt(x(k)**2 + x(k)**2) < Rad - 3*L1) then
                      l(k) = l(j)
                      l(j) = lk
                  end if
              end if
           end do
           j = l(j)
           rxj = x(j)
           ryj = y(j)
           go to 30
       end if
   end if
end do

do i = 1, N
   nit = 1
   lit = l(i)
60 if (lit /= i) then
       nit = nit + 1
       lit = l(lit)
       go to 60
   end if
   nc(nit) = nc(nit) + 1
end do

do i = 1, N
   nc(i) = nc(i)/i
end do

end
