Major refactor

fix a fairly significant file handle leak