This function is still way too complex, I'll post a simpler one you can use.