Fixed memory leaks and poor memory management. Kudos to @nacho.