updated the formatting logic and wrapped it into a function