Restructure some very ugly code