Tidied up main code a bit