Some small code improvements and refractoring. Added more tests.