Reorganized to work correctly as a library.