almost got it right, still has some bugs in it.