Better memory management to avoid OOM error - probably not ideal yet