Tidied up some code.
Started extracting the code into a seperate plugin.