Moved caststuff out into a function