Some code refactoring. Global ordering. Sanity check on cursor pos
Fixed merged conflicts