optimise the code: threshold part