moved algorithm to lib, reindented, added comments