Serious refractoring/cleanup.