C# port of the code from articles on tomdalling.com