Huge code refactor. Added a lot of comments.