Reimplement code, up to Listing 2

This includes the first snippets of Sec. 3.