The code is ugly, but I think it works