Besides from usual solutions like phoon, there is a winning IOCCC entry that exactly does this: https://github.com/ioccc-src/winner/blob/master/2000/natori/...