There's quite some duplication in the `then` and `else` branches. You should factor it out and put the `if` just around the part that changes.