Lots of stuff. Mainly separated function out of the main.