old cpp code use only for inspiration
ported code from cpp to python