some refactoring made, some javadoc added, implemented cleaning flats
function