!===============================================================================
!
! Initialize the overindexed scalar field storage 'sco' for use in PFHMC
!
!-------------------------------------------------------------------------------
! Author: Taylor Haar
! Last modified: 28/09/2016
!-------------------------------------------------------------------------------

subroutine init_sco
  ! Initialize storage for 'sco' in the PF case without RHMC
  ! The PF-RHMC case is handled in init_rhmc()

  use module_p_interface
  use module_field
  use module_switches
  use module_rhmc
  use module_poly
  implicit none

  integer :: max_shift
  integer :: i, j

  if (associated(sco)) then
     ! sco already allocated: don't need to do this again
     return
  endif

  ! Need storage for each polynomial root
  max_shift = maxval(poly(:)%n)

  if (max_shift == 0) then
     ! No storage required
     return
  else
     call expand_sco(max_shift)
  endif

end subroutine init_sco

!-------------------------------------------------------------------------------
subroutine expand_sco(new_size)
  ! Expands the sco storage such that there are at least new_size vectors

  use module_p_interface
  use module_field
  use module_switches
  use module_rhmc
  use module_input
  implicit none

  integer, intent(in) :: new_size
  integer :: current_size
  integer :: i, j

  if (associated(sco)) then
     current_size = size(sco, dim=2)
  else
     current_size = 0
  endif

  if (new_size > current_size) then
     ! Deallocate the storage completely
     if (associated(sco)) then
        do i = 1, 2
           do j = 1, current_size
              deallocate(sco(i, j)%sco)
           enddo
        enddo
        deallocate(sco)
     endif

     ! Reallocate up to the larger size 'new_size'
     allocate(sco(2, new_size))
     do i = 1, 2
        do j = 1, new_size
           nullify(sco(i, j)%sco)
           call allocate_sc_overindexed(sco(i, j)%sco)
        enddo
     enddo
  endif

end subroutine expand_sco
