Lots of refactoring.

Fixed a bug where new versions of files might contain old chunks if the file size was reduced.