Thanks to mcpowr for help optimising this