Copy working functionality from master b09e785