final, tested, commented version