Several fixes suggested by @xabbuh