Fix various crashes found by Alexander Cherepanov