If you can hold everything in memory, this should come close to doing what you want. It has the following assumptions/behviors: