module OW_quanti

  use OW_parms_areal

  implicit none

  contains

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  subroutine owmedian(vel,vref,minv,maxv)

 integer 				:: ib,i,dref
 real 				:: vel(:),vref(:),minv,maxv
 real, allocatable			:: vsort(:)

 allocate(vsort(size(vel)))

 minv=minval(vel);maxv=maxval(vel)
 vsort=ssort(vel)

 dref=floor(size(vel)/real(nref))
 do ib=nref-1,1,-1
   i=(nref-ib)*dref
   vref(ib)=vsort(i)
 end do
 vref(nref)=vsort(1);vref(1)=vsort(size(vel))

 deallocate(vsort)
 end subroutine
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
FUNCTION SSORT (X) RESULT(XO)

!   Description of Parameters
!      X - array of values to be sorted   (usually abscissas)
!      IY - array to be carried with X (all swaps of X elements are
!          matched in IY .  After the sort IY(J) contains the original
!          postition of the value X(J) in the unsorted X array.
!      N - number of values in array X to be sorted
!      KFLAG - Not used in this implementation
!
      REAL 				:: X(:)
      REAL, ALLOCATABLE 			:: XO(:)
      INTEGER, ALLOCATABLE			:: IY(:)
      REAL				:: TEMP
      INTEGER 				:: I, ISWAP(1), ITEMP, ISWAP1,N

      N=SIZE(X)
      ALLOCATE(XO(N),IY(N))

      DO I=1,N
         IY(I)=I
      ENDDO

      DO I=1,N-1
         ISWAP=MAXLOC(X(I:N))
         ISWAP1=ISWAP(1)+I-1
         IF(ISWAP1.NE.I) THEN
           TEMP=X(I)
            X(I)=X(ISWAP1)
            X(ISWAP1)=TEMP
            ITEMP=IY(I)
            IY(I)=IY(ISWAP1)
            IY(ISWAP1)=ITEMP
         ENDIF
      END DO
      XO=X
END FUNCTION

end module
