Fix a memory issue (not exactly a leak...) and some correctness issues. Add some stronger static typing.