bug fix and optimise