refactored code. The same implementation was in src/stan/prob/internal_math.hpp. This doesn't solve the infinite loop problem.