adding code from #339