Reorganized and added memory allocation code.