Also needs comments, this code is really really tough to follow.