bug fixes; some refactoring for style.