Add unit tests, compartmentalize code

Add phpunit tests for current classes where possible, and make the code amenable to instrumentation.