Various bug fixes and refactorings;
JUnit added.