complicated but seems to work so far...