Consolidate the logic (scattered in multiple different places) into one function. Also added note messages to make it more friendly to the user (e.g. debugging problem that the profile is not dumped in a place expected ..)
Regression tests were added to ensure no behavioral change.