Fixed minor bugs, added tests, imporoved code style