Had some stupid mistakes on this one, but it works pretty well.