Optimise and refactor code, fix naming issues