Incorporating changes from @mancio's fork.