Improved performance but code is a bit messy.