Revised memory management.
Merge conflicts fixed.