Refactoring and small bug fixes