Re-arranging the code a bit - trying to make it more sane