Rearranged part of the code to make it more readable.
Added a generic function to add text.