Fix and optimize memory usage + other fixes