Mobile Site Redirection

Here is what I want to do. When a user arrives at my main site (http://www.domain.com) vis a mobile or smartphone (iPhone, Droid,etc) I want to automatically redirect them to the mobile version of my site. If the user arrives directly to my to my mobile site, no redirection is done.

Also a cookie is set to remember their user desires (mobile=1 or mobile=0)

I have done considerable research online and read many post over at Stackoverflow, for example this one.