Initial work from landry@ with some fixes and further tweaking from pascal@ and brad@ ok sthen@ landry@