Tidied up code and re-structured it.