Read
this for an explanation.
This thread includes a tool (I believe it's Windows only) by goaspy that might be some help. It also contains a discusion that lead to the explanation I wrote in the first link.
If you need programming examples look at
apnx.py in the calibre source tree.