Rewritten, slight performance increase.