refactoring and pre allocation optomisation for speed