What did you tried so far?
What are the results you got? Error? How the results differs from your desired output?
Knowing what you tried and why and how it does not work will allow us to not focus and propose a solution that you have already rejected. And may be having the appropriate result is a simple fine-tuning of what you already have.
Please post your sample input and output documents after reading Formatting code and log snippets in posts. Using you document as-is is a lot of effort since they are not formatted correctly.