It's hard to follow the logic. Please add comments, and maybe split it into two IFs