Memory leak + small fixes

See commits for details. :)