!***********************************************************************************
!	MODULE:	Regression
!
!	PURPOSE: Contains subroutine ChebyshevRegression
!
!	AUTHOR:	Ben Malin
!
!	DATE:	6/2004
!       REVISED: 6/2007
!
!***********************************************************************************

module Regression
  
  use Params
  implicit none
  
contains
  
  !***********************************************************************************
  !
  !	SUBROUTINE:  ChebyshevRegression
  !
  !	PURPOSE: Calculates values of the chebyshev polynomial coefficients given
  !               data (tempY) and chebyshev polynomials (tempT).
  !
  !	AUTHOR:	 Ben Malin 
  !
  !	DATE:    6/2004
  !     REVISED: 6/2007
  !
  !***********************************************************************************

  subroutine ChebyshevRegression (dim,order,tempT,tempY,tempCoeffs)
    
    ! inputs:
    !    dim -- Denotes whether regression if one-dimensional (dim=1) or tensor product (dim=2)
    !    order -- number of points in each dimension
    !    tempT -- Chebyshev polynomials
    !    tempY -- Data from functions evaluated at smolyak points
    !
    ! output:
    !    tempCoeffs -- coefficients of policy function
    ! 
    ! remarks:
    !
    
    use Params
    implicit none

    !Declaration of Variables
    integer,intent(in) :: dim	
    integer,intent(in) :: order	
    real(prec),dimension(order,order,d),intent(in) :: tempT
    real(prec),dimension(order**dim),intent(in) :: tempY
    real(prec),dimension(order**dim),intent(out) :: tempCoeffs
    integer :: h,i,j
    integer,dimension(dim) :: coeffstate,coeffstate1
    integer :: temp
    real(prec) :: Sum
    real(prec) :: ChebValueTemp

    !Using Chebyshev extrema as collocation points ... see Kubler/Krueger pg. 11
    do i = 1,(order)**dim
       call GetIndex(i,order,dim,coeffstate)
       Sum = 0
       
       do h = 1,order**dim
          call GetIndex(h,order,dim,coeffstate1)

          j = dim
          ChebValueTemp = 1
          do while (j > 1)
             ChebValueTemp = ChebValueTemp*tempT(coeffstate1(j),coeffstate(j),j)  !Assumes T same for each country
             j = j-1
          end do
          
          temp = 0
          do j = 1,dim
             if (coeffstate1(j) == 1 .or. coeffstate1(j) == order) then
                temp = temp + 1
             endif
          end do
          
          Sum = tempT(coeffstate1(1),coeffstate(1),1)*ChebValueTemp*TempY(h) / 2**(temp) + Sum  !Assumes T same
       end do
       
       temp = 0
       do j = 1,dim
          if (coeffstate(j) == 1 .or. coeffstate(j) == order) then
             temp = temp + 1
          endif
       end do
       
       tempCoeffs(i) = Sum * 2**(dim-temp) / (real(order-1,prec))**dim
       
    end do
    
  end subroutine ChebyshevRegression
  
end module Regression
