Refactoring and a little optimizing