re apply changes from #597 after merge #297