Bug fixes

Not fully tested yet