Rewrite code to C# and do some refactoring