Refactored autofit code