Several bugfixes thanks to Bram1337