refactor and memory improvements