Transcribed the pseudocode and added a few top-level functions.