Ugly code but works