!**********************************************************************************
!
!	SUBROUTINE:  ChebPoly
!
!	PURPOSE: Converts a vector of points from the [kmin,kmax] x N grid (or 
!                 [kmin,kmax]/[zmin,zmax] x d grid) to the [-1,1] x N (or d) grid 
!                and returns the Chebyshev polynomials for these points.
!                This subroutine works in conjunction with ChebValue.
!			 
!	AUTHOR:	 Ben Malin 
!
!	DATE:    6/2004
!       REVISED: 6/2007
!
!**********************************************************************************

subroutine ChebPoly(dim1,state,Ttemp)
  
  ! inputs:
  !    dim1 -- dimension of "state" vector
  !    state -- vector of capital stocks and, possibly, technology shocks
  !
  ! output:
  !    Ttemp -- Chebyshev polynomials evaluated at points in state vector
  ! 
  ! remarks:
  !

  use Params
  
  implicit none
  
  !Variable Declaration
  integer, intent(in) :: dim1
  real(prec), dimension(dim1), intent(in) :: state
  real(prec), dimension(2**(q-d)+1,dim1), intent(out) :: Ttemp
  real(prec), dimension(dim1) :: newstate
  integer :: i,j
  
  do i = 1,N
     !Convert capital stock [-1,1] grid
     newstate(i) = 2.0 * (state(i) - kmin)/(kmax-kmin) - 1.0	!kmax, kmin are global variables
     
!     if (newstate(i) < -1) then
!        print*, 'error: capital below kmin in function ChebPoly'
!        !pause
!     elseif (newstate(i) > 1) then
!        print*, 'error: capital above kmax in function ChebPoly'
!        !pause
!     end if
     
     !Construct Chebyshev Polynomials for capital stocks
     Ttemp(1,i) = 1
     Ttemp(2,i) = newstate(i)
     do j = 3,5			!Since q = d+2, 2**(q-d)+1 = 5.
        Ttemp(j,i) = 2.0 * newstate(i) * Ttemp(j-1,i) - Ttemp(j-2,i)
     end do
     
     !Convert technological shocks to [-1,1] grid
     if (dim1 == d) then
        newstate(i+N) = 2.0 * (state(i+N) - zmin)/(zmax-zmin) - 1.0	!zmax, zmin are global variables
        
!        if (newstate(i+N) < -1) then
!           print*, 'error: tech shock below zmin in function ChebPoly'
!           !pause
!        elseif (newstate(i+N) > 1) then
!           print*, 'error: tech shock above zmax in function ChebPoly'
!           !pause
!        end if
        
        !Construct Chebyshev Polynomials for tech shocks
        Ttemp(1,i+N) = 1
        Ttemp(2,i+N) = newstate(i+N)
        do j = 3,5	!Since q = d+2, 2**(q-d)+1 = 5.
           Ttemp(j,i+N) = 2.0 * newstate(i+N) * Ttemp(j-1,i+N) - Ttemp(j-2,i+N)
        end do
     endif
  end do
  
end subroutine ChebPoly
