Optimise code and fix style errors