Works, is accepted by KATTIS. Is also commented/tidied up a bit.