nasty ugly code that works