algorithm more closely matches wikipedia psudocode