module VotCor_m

! Calculate correlation of actual with predicted vote

  implicit NONE
  public

contains

  subroutine VOTCOR ( K1, K2, F, V1, V2 )

    integer, intent(in) :: K1 ! < 2 -> All 48 states including south
                              ! = 2 -> 32 Non-southern or border states
                              ! > 2 -> Both
    integer, intent(in) :: K2 ! < 1 -> Each weighted equally
                              ! = 1 -> Each state weighted by size
                              ! > 1 -> Both
    real, intent(in) :: F(48) ! Size per state
    real, intent(inout) :: V1(48), V2(48) ! Vote counts

    real :: AVE
    real :: COV
    real:: EF(48) ! index2 == 1 -> F
                  ! index2 /= 1 -> all ones
    real:: EN     ! Total weight, sum of EF
    integer :: IRIGHT, INDEX1, INDEX2, IT
    logical :: MASK(48)       ! Which states to use
    real :: R
    real :: SIG1, SIG2, SV1, SV1SQ, SV2, SV2SQ, SV1V2

    v1 = v1 - 0.5
    v2 = v2 - 0.5
    ave = sum ( abs ( v1 - v2 ) ) / 48
    iright = count ( v1 * v2 > 0 )

    print '( i3, " States predicted correctly.  Average absolute error= ", &
           & F10.5 )', iright, ave
    print '(" Correlation of actual with predicted Kennedy Vote" )'

!     Weighted or unweighted option

    index2 = k2
    do
      if ( index2 == 1 ) then
        ef = f
        en = sum(f)
        print '( "With each state weighted by size" )'
      else
        ef = 1
        en = 48
        print '( "With each state weighted equally" )'
      end if

!     Initialize index and sums

      index1 = k1
      do

!       Option to include or exclude south
        mask = index1 /= 2 .or. &
             & [ ( ( it > 5 .and. it < 15 ) .or. it > 25, it = 1, 48 ) ]

        sv1 = sum ( ef * v1, mask=mask )
        sv2 = sum ( ef * v2, mask=mask )
        sv1sq = sum ( ef * v1**2, mask=mask )
        sv2sq = sum ( ef * v2**2, mask=mask )
        sv1v2 = sum ( ef * v1 * v2, mask=mask )

        cov = ( sv1v2 - sv1 * sv2 / en )**2
        sig1 = sv1sq - sv1**2 / en
        sig2 = sv2sq - sv2**2 / en
        r = sqrt ( cov / ( sig1 * sig2 ) )

!       Print R and repeat if necessary

        select case ( index1 )
        case ( :1 )
          print 1, r
        1 format (" For all 48 states including south is ", f7.4 )
          exit
        case ( 2 )
          print '( " For the 32 non-southern or border states is...", f7.4 )' , r
          exit
        case ( 3: )
          print 1, r
          index1 = 2
        end select
      end do

      if ( index2 <= 1 ) exit
      index2 = 1
    end do

    v1 = v1 + 0.5
    v2 = v2 + 0.5

  end subroutine VOTCOR

end module VotCor_m

! File Name: box5batch12.bin, Fingerprint: 8f207c-31c979
