Nightly checkin

* Adding tests, more refactoring.