Tidied up and tested. Should work for the most part now.