refactored algorithm, structured tests, added tests
added Java version