Port of the code from c++.