tidied up script and moved all stuff into a function