Richil's code partially merged.