Updated to handle more complex situations