Cleaned up code some more. It now works for most cases and passes the requirements for the assignment.
I don't exactly know what is in this commit.