This merges lermit's work and adds a few fixes of my own