somehow works implementation (but very slow, probably due to bug)