I think you should this structure entirely and moving all these calculations into the conditionals like at line 212.  It's not used outside that.