	subroutine replace_reverserank(n,x,miss)
c	replace a series with it's rank (1=hi, n=lo)

	implicit none

	real x(n),miss
	integer n,i,indx(n)
	integer malloc

	pointer (p1,indx)
	p1=malloc(n*4)

	call quickrank_miss(n,x,indx,miss)
	do i=1,n
	 if(indx(i).ne.0)x(indx(i))=n-i+1
	end do

	call free(p1)
	end

	subroutine replace_rank(n,x,miss)
c	replace a series with it's rank (1=hi, n=lo)

	implicit none

	real x(n),miss
	integer n,i,indx(n)
	integer malloc

	pointer (p1,indx)
	p1=malloc(n*4)

	call quickrank_miss(n,x,indx,miss)
	do i=1,n
	 if(indx(i).ne.0)x(indx(i))=i
	end do

	call free(p1)
	end

	subroutine quickrank_miss(n,arrin,indx,miss)
c	rank a series that has missing values

	implicit none

	real arrin(n),miss
	integer n,indx(n),i,indx1(n)
	integer pos(n),nonmiss
	real data(n)
	integer malloc

	pointer (iptr, pos)
	pointer (jptr, indx1)
	pointer (rptr, data)
	iptr = malloc(n*4)
	jptr = malloc(n*4)
	rptr = malloc(n*8)

	nonmiss=0
	do i=1,n
	 if(arrin(i).ne.miss)then
	  nonmiss=nonmiss+1
	  data(nonmiss)=arrin(i)
	  pos(nonmiss)=i
	 endif
	end do
	if(nonmiss.gt.0)call quickrank(nonmiss,data,indx1)
	  
	do i=1,n
	 if(i.le.nonmiss)then
	  indx(i)=pos(indx1(i))
	 else
	  indx(i)=0
	 end if
	end do

	call free(iptr)
	call free(jptr)
	call free(rptr)
	end


	subroutine quickrank(n,arrin,indx)
c	rank an array
c	indx(1) is greatest value

	implicit none

	real arrin(n),q
	integer n,l,indx(n),i,j,ir,indxt

	do j=1,n
	 indx(j)=j
	end do
	if(n.eq.1)return
	l=n/2+1
	ir=n
 10	continue
	if(l.gt.1)then
	 l=l-1
	 indxt=indx(l)
	 q=arrin(indxt)
	else
	 indxt=indx(ir)
	 q=arrin(indxt)
	 indx(ir)=indx(1)
	 ir=ir-1
	 if(ir.eq.1)then
	  indx(1)=indxt
c	  reverse order
	  j=0
 30	  continue
	  j=j+1
	  if(j.ge.n+1-j)return
	  i=indx(j)
	  indx(j)=indx(n+1-j)
	  indx(n+1-j)=i
	  goto 30
	 end if
	end if
	i=l
	j=l+l
 20	continue
	if(j.le.ir)then
	 if(j.lt.ir)then
	  if(arrin(indx(j)).lt.arrin(indx(j+1)))j=j+1
	 end if
	 if(q.lt.arrin(indx(j)))then
	  indx(i)=indx(j)
	  i=j
	  j=j+j
	 else
	  j=ir+1
	 end if
	 goto 20
	end if
	indx(i)=indxt
	goto 10
	end
