Tidied up main function. Add support for logging.