Port from detect.py [SHA: 92eeb6]

There are a few small changes, but the algorithm is identical.