This chunk of getting the layouts and determining whether the cursor fits into the first one almost seems ripe for extraction of some sort... but well there is an elsif here and we need the variables... :-(