+ } while (bytes_remaining);
+
+ /* If writing a compressed resource and not doing a raw copy, write the
+ * chunk table, and finish_wim_resource_chunk_tab() will provide the
+ * compressed size of the resource we wrote. Otherwise, the compressed
+ * size of the written resource is the same as the compressed size of
+ * the existing resource. */
+ if (out_ctype != WIM_COMPRESSION_TYPE_NONE && !raw) {
+ ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
+ &new_compressed_size);
+ if (ret != 0)
+ goto out_fclose;
+ } else {
+ new_compressed_size = old_compressed_size;
+ }
+
+ /* Verify SHA1 message digest of the resource, unless we are doing a raw
+ * write (in which case we never even saw the uncompressed data). Or,
+ * if the hash we had before is all 0's, just re-set it to be the new
+ * hash. */
+ if (!raw) {
+ u8 md[SHA1_HASH_SIZE];
+ sha1_final(md, &ctx);
+ if (is_zero_hash(lte->hash)) {
+ copy_hash(lte->hash, md);
+ } else if (!hashes_equal(md, lte->hash)) {
+ ERROR("WIM resource has incorrect hash!");
+ if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
+ ERROR("We were reading it from `%s'; maybe it changed "
+ "while we were reading it.",
+ lte->file_on_disk);
+ }
+ ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
+ goto out_fclose;
+ }
+ }
+
+ if (new_compressed_size >= original_size &&
+ out_ctype != WIM_COMPRESSION_TYPE_NONE && !raw)
+ {
+ /* Oops! We compressed the resource to larger than the original
+ * size. Write the resource uncompressed instead. */
+ if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
+ ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" "
+ "of output WIM file", file_offset);
+ ret = WIMLIB_ERR_WRITE;
+ goto out_fclose;
+ }
+ ret = write_wim_resource(lte, out_fp, WIM_COMPRESSION_TYPE_NONE,
+ out_res_entry);
+ if (ret != 0)
+ goto out_fclose;
+ if (fflush(out_fp) != 0) {
+ ERROR_WITH_ERRNO("Failed to flush output WIM file");
+ ret = WIMLIB_ERR_WRITE;
+ goto out_fclose;
+ }
+ if (ftruncate(fileno(out_fp), file_offset + out_res_entry->size) != 0) {
+ ERROR_WITH_ERRNO("Failed to truncate output WIM file");
+ ret = WIMLIB_ERR_WRITE;
+ }
+ goto out_fclose;
+ }
+ wimlib_assert(new_compressed_size <= original_size);
+ if (out_res_entry) {
+ out_res_entry->size = new_compressed_size;
+ out_res_entry->original_size = original_size;
+ out_res_entry->offset = file_offset;
+ out_res_entry->flags = lte->resource_entry.flags
+ & ~WIM_RESHDR_FLAG_COMPRESSED;
+ if (out_ctype != WIM_COMPRESSION_TYPE_NONE)
+ out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;