Cherry picking from #25 + minor changes.