Fix memory overflow bug
Improved mode selection