Fix memory / fd leaks reported by valgrind. Fixes #6.