Fix bug and improve speed