Final code. Added comments.