Cleaned up a bit and added some basic error-checking and tests.