ugly code that almost works