Refactor and fix memeory problems.