Refactors and bug fixes