Implements IDisposable. Miscellaneous refactorings.