Converted code from Matt's C++ project to C#