Ugly code but it works. Refactor later