Refactor reasoning algorithm (sorry for only one commit)