more optimization
fix bugs introduced in b80ae5d