!**********************************************************************************
!
!	SUBROUTINE: Permutation
!
!	PURPOSE: The "reverse" of GetIndex subroutine ... see remark below.
!
!	AUTHOR:	Ben Malin 
!
!	DATE: 6/2003
!
!**********************************************************************************

subroutine Permutation(dim1,dim2,states,ind)
  
  ! inputs:
  !    dim1,dim2 -- dimensions of matrix 
  !    states -- vector of size dim2 which holds state of each country
  !
  ! output:
  !    ind -- holds converted index number  
  ! 
  ! remarks:
  !    If there are dim1 states and dim2 countries and the state of each of the dim2 countries
  !    is given in the vector, 'states', Ind(i) will hold the element of the dim1**dim2 x 1
  !    vector for country i that corresponds to the given 'states'.  
  !

  implicit none
    
  !Variable Declaration
  integer,intent(in) :: dim1,dim2
  integer,dimension(dim2),intent(in) :: states
  integer,dimension(dim2),intent(out) :: ind
  
  integer :: h,i
  
  !Calculations
  do h = 1,dim2
     ind(h) = 0
     
     do i = 1,(dim2-1)
        if ( (h+i-1) <= dim2) then
           ind(h) = dim1**(dim2-i)*(states(h+i-1) - 1) + ind(h)
        else
           ind(h) = dim1**(dim2-i)*(states(h+i-1-dim2) - 1) + ind(h)
        endif
     end do
     
     if (h == 1) then
        ind(h) = states(dim2)  + ind(h)
     else
        ind(h) = states(h-1) + ind(h)
     endif
     
  end do
  
end subroutine Permutation
