i give up. function is way too long, just ignore the remarks ;)