Wow, this function looks like a real beast :-)