integer function grid_solve(npath,otl,params,sortpayoff,eta, &
                            sort_order,sort_orderi)

	use PATHS
	use MOD_INT
	use input_params
	implicit none

	integer,intent(IN)                                :: npath, otl
  real*8,dimension(:),intent(IN)                    :: params
  real*8,dimension(:,:),intent(IN)                  :: sortpayoff
  type (PATH),dimension(:,:),intent(INOUT)          :: eta
  integer,dimension(:,:),intent(OUT)             :: sort_order
  integer,dimension(:,:),intent(OUT)             :: sort_orderi


	integer                                           :: tnum, path0, olstart
  real*8                                            :: paymax, pay1d
	integer                                           :: olsave 
	integer                                           :: ol
	integer                                           :: ipot, jpot 


      do tnum = 1 , int(params(P_NPATH))
        if (sortpayoff(otl,tnum) == (0.0d0)) then
            path0 = tnum
            exit
        end if
      end do

    olstart = int(params(P_NPATH))
 
    eta(1:otl-1,:)%spin = 0
    eta(otl,:)%spin = 1

    paymax=-999.99d99
    olsave = params(P_NPATH)+1  !this is where the first one is

    do ol = path0,1,-1
      eta(otl,ol:npath)%spin = 0
      pay1d = 0.0d0
      do jpot=1,int(params(P_NPATH))
        do ipot=otl,int(params(P_NTIME))
          if (eta(ipot,sort_order(ipot,jpot))%spin == 1) then
            pay1d = pay1d + sortpayoff(ipot,sort_order(ipot,jpot))
              exit
          end if
        end do
      end do
      pay1d = pay1d / params(P_NPATH)
      if (pay1d > paymax) then
        ! keep this spin
        paymax = pay1d
        olsave = ol
      end if
    end do !ol

	grid_solve = olsave


end function grid_solve

