tidied up the code a bit, still needs a bit more work