Can you please help me in optimizing the code given below.

Sure, but clean up your code first then re-post it. As is, it is almost unreadable.