Some refactoring and optinizations