modularised, added tests, improved example