I almost died while I solved this problem :)