refactored so that different cases can be handled with different functions