Perfomace improvements and refactoring