Tidied up a little and fixed loop