Ugly code but seems to work