Refactor code and fix a reference leak