Working implementation of Catalin's code