Based on the original patch by Galen Hazelwood: https://github.com/micropython/micropython/pull/1517 .