Work commit 3

At least it works. :) But it has a few logic bugs.. Need to review.