Fixing logic error and improving memory management