code still ugly, but it work