Major reworking and bug-fixing.