Revert "Revert "fixes memory issue as well as re-orders somethings.""

This reverts commit 9a119e826f7a99286ce29eb24cee94b96018a985.