added logic to avoid a middle space first loss; slight refactoring