Restructure messy code, tweak caret management