I think this code will solve all your problems: http://www.mpaste.com/p/xY