      subroutine perm(ii,n,ip)
c
c purpose: generates permutations of numbers 1,...,n.
c ii=1,...,n! picks out a specific permutation.
c ip(n):      contains the result (permutation of 1,...,n).         
c
      parameter(nmax=12)
      dimension iwork(nmax),ip(n)
      if(n.gt.nmax) stop 'perm: 12! is largest value representable.'
c
      nm1=n-1
      ip(1)=1
      do i=2,n
      ip(i)=0
      end do
c
      nf=1
      do i=2,n
      nf=nf*i
      end do
      if(ii.gt.nf) stop 'perm: ii must be .le. n!.'
c
      jj=nf-ii+1
      do i=n,2,-1
      kk=jj/i
      iwork(i)=jj-i*kk
      jj=kk
      end do
c
      do i=2,n
      j=i-iwork(i)
      ip(i)=ip(j)
      ip(j)=i
      end do
c
      return
      end
