extracting some logic and trying to make things more readable