Bug fixes provided by Nuno Costa