Refactor base directory detection