Refactoring plus some bug fixes