refactor and performance improvements