Many small fixes, added JUnit tests