Working solution but quite unpolished code.