enormous refactor that I haven't tested yet