gigantic code cleanup, now works