For the rest, I'll have to check and need more time....Few human-readable comments. Note that proposed code adds extra integrity check by comparing scheduled extent for the file to be written with current value of last_written_extent ("out of sync" fatal condition). As 'else' clause to the this check it automatically pads previous file (or directory) to current last_written_extent.
Oops! Last sentence came out all wrong. Not "to current last_written_extent," but "to *scheduled* extent value for the *current* file." Idea is to have last_written_extent coinciding with the scheduled value... A.