fixed some ugly code. untested