Fix panic for some cases
Improve efficiency