Made the code less WET to fix #2 and added the logic to fix #1