Transcribed the pseudocode. Added some top-level functions.