ugly code, but it works