Fix file descriptor leak

This addresses several file descriptor leaks that affect this library when used repeatedly. Adding close calls where needed.