Painful Answers…

Spending the last couple of days in pain(ranging from little-ignorable to like a million needles pricking my legs), I was wondering about the whole concept of pain. I know its associated very closely to the nervous system and defense mechanism of the body but what is the theories behind its existence. Why something like pain would have figured in the grand scheme of evolution is a little confusing to me.

So can someone out there shed some light on this? Any papers or studies regarding the topic, even personal opinions are welcome :)