Fix errors when certain pages does not exist.

Also added some comments to clear up the logic.

Cherry-picked from f65eda5 (master)