!*********************************************************************
!
!    Subroutine:  OutCoeff
!
!    Purpose:    Writes coefficients of policy rules to a .csv file.
!
!    Author:   Ben Malin
!
!    Date:   10/22/07
!    Revised: 11/2/07
!*********************************************************************

subroutine OutCoeff(filename)

  ! inputs:
  !   filename -- name of output file
  !
  ! output:
  ! 
  ! remarks:
  
  use Params

  implicit none
  
  ! Variable Declaration
  character(len=6), intent(IN) :: filename 
 
  real(prec), dimension(1,8) :: ParamOut
  integer :: i,j,i1,j1
  
  !Matrix that holds parameter values
  ParamOut(1,1) = rho
  ParamOut(1,2) = sigma
  ParamOut(1,3) = kappa
  ParamOut(1,4) = gamma_min
  ParamOut(1,5) = gamma_max
  ParamOut(1,6) = kss
  ParamOut(1,7) = kmin
  ParamOut(1,8) = kmax

  ! Write output to file
  print*,""
  print*,""
  print*,""
  print*,"Make sure the output file -> ", filename, ".csv <- is closed!"
  print*,""
  print*,""
  print*,""
!  pause
  
  open (1, file = filename//".csv")      ! Open file with name filename

  !Outputs the parameters of the model
!  call WriteRowM(ParamOut, 1, 8, 1)
!  write (1,"") 

  !Outputs the coefficients of the policy rules
  do i = 1, d
     do j = 1,N
        call WriteColM(CoeffsCons3(i,:,:), 5, N, j)
        write (1,"()")                              
     end do
  end do
  do i = 1, d
     do j = 1,N
        call WriteColM(CoeffsCap3(i,:,:), 5, N, j)
        write (1,"()")                              
     end do
  end do
  do i = 1, d
     do j = 1,N
        call WriteColM(CoeffsCons1(i,:,:), 3, N, j)
        write (1,"()")                              
     end do
  end do
  do i = 1, d
     do j = 1,N
        call WriteColM(CoeffsCap1(i,:,:), 3, N, j)
        write (1,"()")                              
     end do
  end do
  do i = 1, d-1
     do i1 = i+1,d
        do j = 1,N
           do j1 = 1,3
              call WriteColM(CoeffsCons2(i,i1,:,:,j), 3, 3, j1)
              write (1,"()")  
           end do
        end do
     end do
  end do
  do i = 1, d-1
     do i1 = i+1,d
        do j = 1,N
           do j1 = 1,3
              call WriteColM(CoeffsCap2(i,i1,:,:,j), 3, 3, j1)
              write (1,"()")  
           end do
        end do
     end do
  end do
  do j = 1,N
     write (1,'(F15.12," ")', advance = 'no') YCons0(j)
     write (1,"")                              
  end do
  do j = 1,N
     write (1,'(F15.12," ")', advance = 'no') YCap0(j)
     write (1,"")                              
  end do
  
  print*,""
  print*,""
  print*,""
  print*,"Results were written to file -> ", filename, ".csv", " <-"
  print*,""
  print*,""
  print*,""
  
end subroutine OutCoeff
