Lots of work moving stuff around to try and encapsulate functions