Much more normal implementation of this problem. Makes my previous implementation look ridiculous.