Module kiki
    Integer, Parameter ::wp=kind(1.0d0), wip=kind(1)
    Integer, Parameter ::qp=selected_real_kind(R=Range(1.0_wp)+1)

contains
Function sumx128(x,n) Result(suma)
    implicit none
    Integer, Parameter :: VL = 128
    Integer(wip),Intent(in) :: n
    Real(wp),Intent(in) :: x(n)
    Real(wp) :: suma,s(1:VL)
    Integer(wip) :: i
    real(wp) :: partialsum

    s = 0
    If (n>=VL) Then
      !$OMP SIMD SIMDLEN(VL) REDUCTION(+:s)
      do i=1,n-VL+1,VL
        s(1:VL) = s(1:VL)+x(i:i+VL-1)
      End Do
    Else
      i=1
    Endif
  
    partialsum = sum(s) 
    if (partialsum /= 1024.0_wp) then
      print*, "OMP SIMD ERROR!"
      print*, "ERROR: Last value of i ", i, "  value of N ", n 
      print*, "ERROR: partial sum before remainder summation ", sum(s)
      print*, "ERROR: parital sum at this point should be 1024.0"
    end if

    !...compute sum of remaining elements < VL
    If (i<=n) Then
        s(1:n+1-i) = s(1:n+1-i) + x(i:n)
    End If  
    suma = sum(s)
End Function
end module kiki

Program test
  Use kiki
  implicit none
  Real(wp) , Allocatable:: x(:)
  Integer, Parameter :: N=2065
  Integer :: i
  real(wp) :: rez

  Allocate(x(N), SOURCE=[(Real(i,wp)*(-1)**i,i=1,N)])
  Print *, "size of array ",  N
  rez = sumx128(x,N)
  if (rez /= SUM(x) ) then
    print *, "ERROR: !! these should match !!"
    print *, "ERROR:   user summation of X ", rez 
    print *, "CORRECT: intrinsic  SUM of X ", SUM(x)
  else
    print *, "CORRECT: these should match "
    print *, "CORRECT: user summation of X ", rez
    print *, "CORRECT: intrinsic  SUM of X ", SUM(x)
  end if

End 
