Improve text formatting function