fix bug and optimization