working version, before threads refactoring