finally working version (not tested properly though)