Bug fixes

Many bug fixes. If these changes break something, I'll fix it before anything is released.