ElysianTail's solution for this was much better than mine.