Fixes for potential memory issues. Some of the changes also improve the architechure.