Working non-crashing version. Made changes to memory management