Took some sanity checks from Fabrice Bellard's code