rearranging for improved readability and added some logging