C# implementation by Jarosław Kroczek