Final nitpick; all of this logic from line 17 to line 22 should be in one setcode block.