Refactor a bit. Still ~ugly.