Port of the C# version of this lib.