aboutsummaryrefslogtreecommitdiff
path: root/src/conversion/czi
diff options
context:
space:
mode:
authorTom Harley2018-03-07 16:00:54 +0000
committerTom Harley2018-03-07 16:00:54 +0000
commite338c8ce35f22812ae1de5303a06edde166ba8cf (patch)
treee80a4f060816b57a60357fb832bb7bcbeac78b0a /src/conversion/czi
parentMerge remote-tracking branch 'origin/testing-middleware' into development (diff)
parentAdding support for the protocol's supported_views thing and laid base work fo... (diff)
downloadmedicine-e338c8ce35f22812ae1de5303a06edde166ba8cf.tar.gz
medicine-e338c8ce35f22812ae1de5303a06edde166ba8cf.zip

Merge branch ‘cjd24/conversion’ into development

Diffstat (limited to 'src/conversion/czi')
-rw-r--r--src/conversion/czi/convertJxrs.py38
-rw-r--r--src/conversion/czi/czi.ts431
-rwxr-xr-xsrc/conversion/czi/cziConvert.sh10
-rw-r--r--src/conversion/czi/cziSegmentHeaders.h458
-rw-r--r--src/conversion/czi/cziconvert.c354
5 files changed, 1291 insertions, 0 deletions
diff --git a/src/conversion/czi/convertJxrs.py b/src/conversion/czi/convertJxrs.py
new file mode 100644
index 0000000..d19a59a
--- /dev/null
+++ b/src/conversion/czi/convertJxrs.py
@@ -0,0 +1,38 @@
+from concurrent.futures import ThreadPoolExecutor
+from subprocess import check_call
+from glob import glob
+from sys import argv
+
+totalFiles = 0
+coutner = 0
+
+
+def convertjxrs(filename):
+ global counter
+ global totalFiles
+ asTif = filename.rsplit('.',1)[0] + ".tif"
+ check_call(['./JxrDecApp', "-i", filename, "-o", asTif])
+ check_call(['convert', asTif, filename.rsplit('.',1)[0] + ".png"])
+ check_call(['rm', filename, asTif])
+ counter += 1
+ print (f"> Processed File: {counter}/{totalFiles} : {filename} --> {filename.rsplit('.',1)[0]}.png")
+
+
+if __name__ == "__main__":
+
+ if (len(argv) != 2):
+ print("\nMissing Argument!\n\nUsage:\npython3 convertJxrs.py <DirectoryContainingJxrs>")
+ exit(0)
+ else:
+ print("=========== BEGIN JXR CONVERSION ===========")
+ print ('Files Dir: ' + argv[1] + '\n')
+
+ filenames = glob(argv[1] + 'data-*.jxr')
+ counter = 0
+ totalFiles = len(filenames)
+
+ pool = ThreadPoolExecutor(5)
+ for f in pool.map(convertjxrs, filenames):
+ pass
+ pool.shutdown(True)
+ print("=========== FINISH JXR CONVERSION ===========")
diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts
new file mode 100644
index 0000000..addf43e
--- /dev/null
+++ b/src/conversion/czi/czi.ts
@@ -0,0 +1,431 @@
+
+import * as fs from 'fs';
+import { logger } from '../../logger';
+import * as sharp from 'sharp';
+import * as parsexml from 'xml-parser';
+import { SharpInstance } from 'sharp';
+
+const extractionDirectory: string = '/cs/scratch/cjd24/0701-extraction/';
+const outputImageDirectory: string = '/cs/scratch/cjd24/0701-extraction-processed2/'
+const tileOverlap: number = 0;
+const tileSize: number = 1024;
+const maxZoom: number = 64;
+
+interface Dimension {
+ Dimension: string;
+ Start: number;
+ Size: number;
+}
+interface DirectoryEntry {
+ DimensionCount: number;
+ DimensionEntries: Dimension[];
+}
+interface SubBlock {
+ DirectoryEntry: DirectoryEntry;
+ Data: string;
+}
+interface Segment {
+ Id: string;
+ UsedSize: number;
+ Data: SubBlock;
+}
+class TileBounds {
+ public left!: number;
+ public right!: number;
+ public top!: number;
+ public bottom!: number;
+ public constructor(leftBound: number, rightBound: number, topBound: number, bottomBound: number) {
+ this.left = leftBound;
+ this.right = rightBound;
+ this.top = topBound;
+ this.bottom = bottomBound;
+ }
+}
+interface SupportedViews {
+ scalable_image: {
+ width: number;
+ height: number;
+ channels: [
+ {
+ channel_id: string;
+ channel_name: string;
+ metadata?: {};
+ }
+ ];
+ real_width?: {
+ value: number;
+ units: string;
+ };
+ real_height?: {
+ value: number;
+ units: string;
+ };
+ metadata?: {};
+ }
+}
+interface CZITile {
+ x_offset: number;
+ y_offset: number;
+ width: number;
+ height: number;
+ file: string;
+}
+interface CZIHeightMap {
+ zoom_level: number,
+ plane: CZITile[][];
+}
+interface WholeCZIHierarchy {
+ c_values: [{
+ channel_id: string,
+ height_map: CZIHeightMap[];
+ }];
+}
+
+const getOriginalTileBounds: Function = function(originalTile: Segment): (TileBounds | null) {
+ const bounds: TileBounds = new TileBounds(-1, -1, -1, -1);
+
+ for (const dimension of originalTile.Data.DirectoryEntry.DimensionEntries) {
+ switch (dimension.Dimension) {
+ case 'X':
+ bounds.left = dimension.Start;
+ bounds.right = bounds.left + dimension.Size;
+ continue;
+ case 'Y':
+ bounds.top = dimension.Start;
+ bounds.bottom = bounds.top + dimension.Size;
+ continue;
+ default:
+ continue;
+ }
+ }
+
+ if (bounds.left < 0 || bounds.right < 0 || bounds.top < 0 || bounds.bottom < 0) {
+ return null;
+ }
+
+ return bounds;
+};
+
+const findRelatedTiles: Function = function(activeSegments: Segment[], desired: TileBounds): Segment[] {
+ const relatedTiles: Segment[] = [];
+
+ for (const baseTile of activeSegments) {
+
+ let origCoords: TileBounds | null;
+
+ if ((origCoords = getOriginalTileBounds(baseTile)) === null) {
+ throw new Error('There was a Sad Boi error');
+ }
+
+ // Desired X on left is within current tile
+ if (((desired.left >= origCoords.left) &&
+ (desired.left < origCoords.right)) ||
+
+ // Desired X on right is within the current tile
+ ((desired.right > origCoords.left) &&
+ (desired.right <= origCoords.right)) ||
+
+ // Desired tile X overlaps base tile
+ ((desired.left < origCoords.left) &&
+ (desired.right > origCoords.right))) {
+
+ // Desired Y on top is within current tile
+ if (((desired.top >= origCoords.top) &&
+ (desired.top < origCoords.bottom)) ||
+
+ // Desired Y on right is within the current tile
+ ((desired.bottom > origCoords.top) &&
+ (desired.bottom <= origCoords.bottom)) ||
+
+ // Desired tile Y overlaps whole base tile
+ ((desired.top < origCoords.top) &&
+ (desired.bottom > origCoords.bottom))) {
+
+ relatedTiles.push(baseTile);
+ }
+ }
+ }
+
+ return relatedTiles;
+};
+
+const getDimension: Function = function(segment: Segment, name: string): Dimension {
+ for (const dimension of segment.Data.DirectoryEntry.DimensionEntries) {
+ if (dimension.Dimension === name) {
+ return dimension;
+ }
+ }
+ throw new Error('Dimension: ' + name + " doesn't exist for segment: " + segment);
+};
+
+const orderSegments: Function = function(segments: Segment[]): Segment[][] {
+
+ const output: Segment[][] = [];
+
+ if (segments.length > 1) {
+ let xCoords: number[] = [];
+ let yCoords: number[] = [];
+
+ // Get all x/y's;
+ const initC: number = getDimension(segments[0], 'C').Start;
+ for (const seg of segments) {
+ if (getDimension(seg, 'C').Start !== initC) {
+ throw new Error('Segment array contains multiple values of C - this overlay is currently unsupported within this method');
+ }
+ xCoords.push(getDimension(seg, 'X').Start);
+ yCoords.push(getDimension(seg, 'Y').Start);
+ }
+ // Filter to get Uniaue Values
+ xCoords = xCoords.filter(
+ (item: number, index: number, array: number[]) => array.indexOf(item) === index);
+ yCoords = yCoords.filter(
+ (item: number, index: number, array: number[]) => array.indexOf(item) === index);
+
+ // Use the filtered list to order the segments into rows
+ for (const yVal of yCoords) {
+
+ // Get all segments with the same y value
+ const row: Segment[] = [];
+ for (const seg of segments) {
+ if (getDimension(seg, 'Y').Start === yVal) {
+ row.push(seg);
+ }
+ }
+
+ // Sort the row of y values by x value
+ const sortedRow: Segment[] = [];
+ for (const xVal of xCoords) {
+ for (const seg of row) {
+ if (getDimension(seg, 'X').Start === xVal) {
+ sortedRow.push(seg);
+ break;
+ }
+ }
+ }
+
+ // Push this to the finalised grid
+ output.push(sortedRow);
+ }
+
+ // Return the result
+ return output;
+ } else {
+ output.push(segments);
+ return output;
+ }
+};
+
+const findRegionToExtract: Function = function(segment: Segment, desired: TileBounds): TileBounds {
+ const baseBounds: TileBounds = getOriginalTileBounds(segment);
+ let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1);
+
+ if (desired.left <= baseBounds.left) {
+ chunkToExtract.left = 0;
+ } else {
+ chunkToExtract.left = desired.left - baseBounds.left;
+ }
+
+ if (desired.right >= baseBounds.right) {
+ chunkToExtract.right = baseBounds.right - baseBounds.left;
+ } else {
+ chunkToExtract.right = desired.right - baseBounds.left;
+ }
+
+ if (desired.top <= baseBounds.top) {
+ chunkToExtract.top = 0;
+ } else {
+ chunkToExtract.top = desired.top - baseBounds.top;
+ }
+
+ if (desired.bottom >= baseBounds.bottom) {
+ chunkToExtract.bottom = baseBounds.bottom - baseBounds.top;
+ } else {
+ chunkToExtract.bottom = desired.bottom - baseBounds.top;
+ }
+
+ return chunkToExtract;
+};
+
+const extractAndStitchChunks: Function = async function(segments: Segment[][], desiredRegion: TileBounds): Promise<SharpInstance> {
+
+ let tileVerticalBuffer: Buffer[] = [];
+
+ for (const segRow of segments) {
+ let tileRow: Buffer[] = [];
+ let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1);
+ for (const segCol of segRow) {
+ chunkToExtract = findRegionToExtract(segCol, desiredRegion);
+ let data: Promise<Buffer> =
+ sharp(`${extractionDirectory}${segCol.Data.Data}`)
+ .extract({
+ left: chunkToExtract.left,
+ top: chunkToExtract.top,
+ width: chunkToExtract.right - chunkToExtract.left,
+ height: chunkToExtract.bottom - chunkToExtract.top
+ })
+ .toBuffer();
+
+ tileRow.push(await data);
+ }
+
+ let imageVerticalSlice: SharpInstance = sharp(tileRow[0]);
+ let bufferBound = findRegionToExtract(segRow[0], desiredRegion);
+ if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) {
+ imageVerticalSlice = await imageVerticalSlice.extend(
+ {top:0, left:0, bottom:0, right: (tileSize - (bufferBound.right - bufferBound.left))});
+ }
+ for (let index = 1; index < segRow.length; index++) {
+ imageVerticalSlice = await imageVerticalSlice
+ .overlayWith(tileRow[index],
+ {top: 0, left: (bufferBound.right - bufferBound.left) + ((index -1) * tileSize)});
+ }
+
+ tileVerticalBuffer.push(await imageVerticalSlice.toBuffer());
+ }
+
+ let finalImage: SharpInstance = sharp(tileVerticalBuffer[0]);
+ let bufferBound = findRegionToExtract(segments[0][0], desiredRegion);
+ if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) {
+ finalImage = await finalImage.extend(
+ {top:0, left:0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0});
+ }
+ for (let index = 1; index < segments.length; index++) {
+ finalImage = finalImage.overlayWith(
+ tileVerticalBuffer[index],
+ {top: getDimension(segments[index -1][0], 'Y').Size, left: 0});
+ }
+
+ return finalImage;
+};
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+const dataBlocks: Segment[] = require(`${extractionDirectory}outputjson.json`).czi.filter(
+ (s: Segment) => s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty');
+const inspect = require('util').inspect;
+const metaXML: parsexml.Document = parsexml(fs.readFileSync(`${extractionDirectory}FILE-META-1.xml`, 'utf8'));
+
+let supportedViews: SupportedViews = {scalable_image: {width: -1, height: -1, channels: [{channel_id: '-1', channel_name: ''}], metadata: metaXML}};
+supportedViews.scalable_image.channels.pop();
+
+let totalSizeX: number = -1;
+let totalSizeY: number = -1;
+
+// THE FOLLOWING FOR LOOP IS DISGUSTING AND I HATE IT, AND I WISH I DIDNT WRITE IT BUT DON'T SEE ANY OTHER WAY TO DO IT LOL :'(
+for (const child of metaXML.root.children) {
+ if (child.name === 'Metadata') {
+ for (const entry of child.children) {
+ if (entry.name === 'Information') {
+ for (const properties of entry.children) {
+ if (properties.name === 'Image') {
+ for (const property of properties.children) {
+ if (property.name === 'SizeX' && property.content) {
+ totalSizeX = Number.parseInt(property.content, 10);
+ supportedViews.scalable_image.width = totalSizeX;
+ continue;
+ } else if (property.name === 'SizeY' && property.content) {
+ totalSizeY = Number.parseInt(property.content, 10);
+ supportedViews.scalable_image.height = totalSizeY;
+ continue;
+ } else if(property.name === 'Dimensions') {
+ for (const chan of property.children) {
+ if (chan.name === 'Channels') {
+ for (const channel of chan.children) {
+ supportedViews.scalable_image.channels.push(
+ {
+ channel_id: channel.attributes.Id.split(":")[1],
+ channel_name: channel.attributes.Name,
+ metadata: channel.children
+ }
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+// Get all values of X and Y respectively.
+const uniqueX: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'X').Start).filter(
+ (item: number, index: number, array: number[]) => array.indexOf(item) === index);
+const uniqueY: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'Y').Start).filter(
+ (item: number, index: number, array: number[]) => array.indexOf(item) === index);
+
+const uniqueTileSizes: number[][] = [];
+for (const seg of dataBlocks) {
+
+ const x: number = getDimension(seg, 'X').Size;
+ const y: number = getDimension(seg, 'Y').Size;
+ let found: boolean = false;
+ for (const dimPair of uniqueTileSizes) {
+ if (x === dimPair[0] && y === dimPair[1]) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ uniqueTileSizes.push([x, y]);
+ }
+}
+
+let filteredDataBlocks: Segment[] = [];
+const filterC: Function = function(to: number): void {
+ filteredDataBlocks = dataBlocks.filter(
+ (item: Segment, index: number, array: Segment[]) => getDimension(item, 'C').Start === to
+ );
+};
+
+
+////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+// Begin work on getting the new tiles all nice
+// Print out all of the related tiles to every new tile to be created.
+let filecoutner: number = 0;
+async function extrapolateDimension(cVal: number, totalCs: number, maxZoomLevel: number): Promise<CZIHeightMap[]> {
+ console.log(`Stage (${cVal + 1}/${totalCs}): Task(0/${Math.ceil(totalSizeY/tileSize)}): 0% complete.`)
+ for (let ys: number = 0; ys < totalSizeY;) {
+ var timing = process.hrtime();
+ for (let xs: number = 0; xs < totalSizeX; xs += tileSize) {
+ const desired = new TileBounds (
+ xs - tileOverlap,
+ xs + tileSize + tileOverlap,
+ ys - tileOverlap,
+ ys + tileSize + tileOverlap
+ );
+ filterC(cVal);
+
+ // console.log(filteredDataBlocks.map((x: any) => x.Data.DirectoryEntry.DimensionEntries[2]));
+ const sortedSegments: Segment[][] = orderSegments(findRelatedTiles(filteredDataBlocks, desired));
+ (await extractAndStitchChunks(sortedSegments, desired)).toFile(`${outputImageDirectory}img-${filecoutner++}`);
+ }
+ ys += tileSize;
+ timing = process.hrtime(timing);
+ console.log(`Stage (${cVal + 1}/${totalCs}): Task(${ys/tileSize}/${Math.ceil(totalSizeY/tileSize)}): ${Math.ceil(((ys/totalSizeY)*100) *100)/100}% complete. (${timing[0]} sec/iter)`);
+ }
+ return [];
+}
+
+let finalCZIJson: WholeCZIHierarchy = {} as any;
+async function main(): Promise<void> {
+ for (const cval of supportedViews.scalable_image.channels) {
+ await extrapolateDimension(Number.parseInt(cval.channel_id, 10), supportedViews.scalable_image.channels.length, maxZoom).then(v =>
+ {
+ finalCZIJson.c_values.push({channel_id: cval.channel_id, height_map: v});
+ console.log(`Completed Tier: ${cval.channel_id}`);
+ return;
+ }, err => {
+ console.error(err);
+ }
+ );
+ }
+ fs.writeFile(`${outputImageDirectory}layout.json`, JSON.stringify(finalCZIJson), (err) => console.error(err));
+}
+main();
diff --git a/src/conversion/czi/cziConvert.sh b/src/conversion/czi/cziConvert.sh
new file mode 100755
index 0000000..639251c
--- /dev/null
+++ b/src/conversion/czi/cziConvert.sh
@@ -0,0 +1,10 @@
+#!/bin/sh
+
+CZI_WORKING_DIR=${1:-"/cs/scratch"}
+CZI_EXTRACTION_DIR=${2:-"0701-extraction"}
+CZI_FILE=${3:-"2016_12_17__0701.czi"}
+
+gcc -Wall -Wextra --pedantic -std=c99 cziconvert.c
+mkdir -p ${CZI_WORKING_DIR}/${USER}/${CZI_EXTRACTION_DIR}
+./a.out ${CZI_WORKING_DIR}/${USER}/${CZI_FILE} ${CZI_WORKING_DIR}/${USER}/${CZI_EXTRACTION_DIR}/ ${PWD}/convertJxrs.py
+rm ./a.out
diff --git a/src/conversion/czi/cziSegmentHeaders.h b/src/conversion/czi/cziSegmentHeaders.h
new file mode 100644
index 0000000..3ed0c60
--- /dev/null
+++ b/src/conversion/czi/cziSegmentHeaders.h
@@ -0,0 +1,458 @@
+#include <inttypes.h>
+#include <uuid/uuid.h>
+
+typedef uuid_t GUID;
+extern char extractDirName[100];
+
+
+//START FILE WRITER ////////////////////////////////////////////////////////////
+void writeDataToFile(const char* filename, int fileCount, const char* optionalFileExtension, void* content, long contentSize) {
+ FILE* outputFile;
+ char outputFileName[150];
+ sprintf(outputFileName, "%s%s%d%s", extractDirName, filename, fileCount, optionalFileExtension);
+ if ((outputFile = fopen(outputFileName, "w"))==NULL){
+ printf("Write error occurred, check file path.");
+ exit(1);
+ }
+ fwrite(content, 1, contentSize, outputFile);
+ fclose(outputFile);
+}
+//END FILE WRITER //////////////////////////////////////////////////////////////
+
+
+
+//START SEGMENT HEADERS/////////////////////////////////////////////////////////
+typedef struct {
+ char name[16];
+ uint64_t allocated_size;
+ uint64_t used_size;
+} __attribute__ ((__packed__)) SegmentHeader;
+
+void printSegmentHeader(SegmentHeader* header) {
+ printf("name: %s\n", header->name);
+ printf("allocated_size: %" PRIu64 "\n", header->allocated_size);
+ printf("used_size: %" PRIu64 "\n", header->used_size);
+ printf("\n");
+}
+void writeSegmentHeader(SegmentHeader* header, FILE* outputFile) {
+ fprintf(outputFile, "\"Id\": \"%s\",\n", header->name);
+ fprintf(outputFile, "\"AllocatedSize\": %" PRIu64 ",\n", header->allocated_size);
+ fprintf(outputFile, "\"UsedSize\": %" PRIu64 ",\n", header->used_size);
+ fprintf(outputFile, "\"Data\": \n");
+}
+//END SEGMENT HEADERS///////////////////////////////////////////////////////////
+
+
+
+//START ZISRAWFILE /////////////////////////////////////////////////////////////
+typedef struct {
+ uint32_t major;
+ uint32_t minor;
+ uint32_t reserved1;
+ uint32_t reserved2;
+ GUID primary_file_guid;
+ GUID file_guid;
+ uint32_t file_part;
+ uint64_t directory_position;
+ uint64_t metadata_position;
+ uint32_t update_pending;
+ uint64_t attachment_directory_potition;
+} __attribute__ ((__packed__)) ZisrawFile;
+
+void printZisrawFile(ZisrawFile* header) {
+ printf("major: %" PRIu32 "\n", header->major);
+ printf("minor: %" PRIu32 "\n", header->minor);
+ printf("reserved1: %" PRIu32 "\n", header->reserved1);
+ printf("reserved2: %" PRIu32 "\n", header->reserved2);
+ printf("primary_file_guid: ");
+ for (int i = 0; i < 16; i++) {
+ printf("%u ",header->primary_file_guid[i]);
+ }
+ printf("\nfile_guid: ");
+ for (int i = 0; i < 16; i++) {
+ printf("%u ",header->file_guid[i]);
+ }
+ printf("\nfile_part: %" PRIu32 "\n", header->file_part);
+ printf("directory_position: %" PRIu64 "\n", header->directory_position);
+ printf("metadata_position: %" PRIu64 "\n", header->metadata_position);
+ printf("update_pending: %" PRIu32 "\n", header->update_pending);
+ printf("attachment_directory_potition: %" PRIu64 "\n", header->attachment_directory_potition);
+ printf("\n");
+}
+void writeZisrawFile(ZisrawFile* header, FILE* outputFile) {
+ fprintf(outputFile, "{\n");
+ fprintf(outputFile, "\"Major\": %" PRIu32 ",\n", header->major);
+ fprintf(outputFile, "\"Minor\": %" PRIu32 ",\n", header->minor);
+ fprintf(outputFile, "\"Reserved1\": %" PRIu32 ",\n", header->reserved1);
+ fprintf(outputFile, "\"Reserved2\": %" PRIu32 ",\n", header->reserved2);
+ fprintf(outputFile, "\"PrimaryFileGuid\": \n[");
+ int i = 0;
+ for (; i < 15; i++) {
+ fprintf(outputFile, "%u, ",header->primary_file_guid[i]);
+ }
+ fprintf(outputFile, "%u],\n",header->primary_file_guid[i]);
+ fprintf(outputFile, "\"FileGuid\": \n[");
+ for (i = 0; i < 15; i++) {
+ fprintf(outputFile, "%u, ",header->file_guid[i]);
+ }
+ fprintf(outputFile, "%u],\n",header->file_guid[i]);
+ fprintf(outputFile, "\"FilePart\": %" PRIu32 ",\n", header->file_part);
+ fprintf(outputFile, "\"DirectoryPosition\": %" PRIu64 ",\n", header->directory_position);
+ fprintf(outputFile, "\"MetadataPosition\": %" PRIu64 ",\n", header->metadata_position);
+ fprintf(outputFile, "\"UpdatePending\": %" PRIu32 ",\n", header->update_pending);
+ fprintf(outputFile, "\"AttachmentDirectoryPosition\": %" PRIu64 "\n", header->attachment_directory_potition);
+ fprintf(outputFile, "}\n");
+}
+//END ZISRAWFILE ///////////////////////////////////////////////////////////////
+
+
+
+//START SubBlockDirectory/////////////////////////////////////////////////////////
+typedef struct {
+ char dimension[4];
+ int32_t start;
+ uint32_t size;
+ float start_coordinate;
+ uint32_t stored_size;
+} __attribute__ ((__packed__)) SubBlockDimentionEntry;
+
+typedef struct {
+ char schema[2];
+ uint32_t pixel_type;
+ uint64_t file_position;
+ uint32_t file_part;
+ uint32_t compression;
+ char pyramidType;
+ char spare1;
+ char spare2[4];
+ uint32_t dimension_count;
+ SubBlockDimentionEntry* dimension_entries;
+} __attribute__ ((__packed__)) SubBlockDirectoryEntry;
+
+typedef struct {
+ uint32_t entry_count;
+ char reserved[124];
+ SubBlockDirectoryEntry* directory_entries;
+} __attribute__ ((__packed__)) SubBlockDirectory;
+
+void printSubBlockDimentionEntry(SubBlockDimentionEntry* dimensionEntry) {
+ // printf(" dimension: ");
+ // for (int i = 0; i < 4; i++) {
+ // printf("%c", dimensionEntry->dimension[i]);
+ // }
+
+ printf(" dimension: %s\n", dimensionEntry->dimension);
+
+ printf(" start: %" PRIi32 "\n", dimensionEntry->start);
+ printf(" size: %" PRIu32 "\n", dimensionEntry->size);
+ printf(" start_coordinate: %f\n", dimensionEntry->start_coordinate);
+ printf(" stored_size: %" PRIu32 "\n", dimensionEntry->stored_size);
+}
+void writeSubBlockDimentionEntry(SubBlockDimentionEntry* dimensionEntry, FILE* outputFile) {
+ fprintf(outputFile, "{\n");
+
+ // fprintf(outputFile, "\"Dimension\": \"");
+ // for(int i = 0; i < 4; i++) {
+ // fprintf(outputFile, "%c", dimensionEntry->dimension[i]);
+ // }
+ // fprintf(outputFile, "\",\n\"Start\": %" PRIi32 ",\n", dimensionEntry->start);
+
+ fprintf(outputFile, "\"Dimension\": \"%s\",\n", dimensionEntry->dimension);
+ fprintf(outputFile, "\"Start\": %" PRIi32 ",\n", dimensionEntry->start);
+
+ fprintf(outputFile, "\"Size\": %" PRIu32 ",\n", dimensionEntry->size);
+ fprintf(outputFile, "\"StartCoordinate\": %f,\n", dimensionEntry->start_coordinate);
+ fprintf(outputFile, "\"StoredSize\": %" PRIu32 "\n", dimensionEntry->stored_size);
+ fprintf(outputFile, "}\n");
+}
+
+void printSubBlockDirectoryEntry(SubBlockDirectoryEntry* directoryEntry) {
+ printf(" schema: %c%c\n", directoryEntry->schema[0], directoryEntry->schema[1]);
+ printf(" pixel_type: %" PRIu32 "\n", directoryEntry->pixel_type);
+ printf(" file_position: %" PRIu64 "\n", directoryEntry->file_position);
+ printf(" file_part: %" PRIu32 "\n", directoryEntry->file_part);
+ printf(" compression: %" PRIu32 "\n", directoryEntry->compression);
+ printf(" pyramidType: %u\n", directoryEntry->pyramidType);
+ printf(" spare1: %d\n", directoryEntry->spare1);
+ printf(" spare2: %d %d %d %d\n", directoryEntry->spare2[0], directoryEntry->spare2[1], directoryEntry->spare2[2], directoryEntry->spare2[3]);
+ printf(" dimension_count: %" PRIu32 "\n", directoryEntry->dimension_count);
+ printf(" dimension_entries: \n");
+ for (uint32_t i = 0; i < directoryEntry->dimension_count; i++) {
+ printSubBlockDimentionEntry(&directoryEntry->dimension_entries[i]);
+ }
+ printf("\n");
+}
+void writeSubBlockDirectoryEntry(SubBlockDirectoryEntry* directoryEntry, FILE* outputFile) {
+ fprintf(outputFile, "{\n");
+ fprintf(outputFile, "\"SchemaType\": \"%c%c\",\n", directoryEntry->schema[0],directoryEntry->schema[1]);
+ fprintf(outputFile, "\"PixelType\": %" PRIu32 ",\n", directoryEntry->pixel_type);
+ fprintf(outputFile, "\"FilePosition\": %" PRIu64 ",\n", directoryEntry->file_position);
+ fprintf(outputFile, "\"FilePart\": %" PRIu32 ",\n", directoryEntry->file_part);
+ fprintf(outputFile, "\"Compression\": %" PRIu32 ",\n", directoryEntry->compression);
+ fprintf(outputFile, "\"PyramidType\": \"%u\",\n", directoryEntry->pyramidType);
+ fprintf(outputFile, "\"spare1\": %d,\n", directoryEntry->spare1);
+ fprintf(outputFile, "\"spare2\": \"%d %d %d %d\",\n", directoryEntry->spare2[0], directoryEntry->spare2[1], directoryEntry->spare2[2], directoryEntry->spare2[3]);
+ fprintf(outputFile, "\"DimensionCount\": %" PRIu32 ",\n", directoryEntry->dimension_count);
+ fprintf(outputFile, "\"DimensionEntries\": \n[\n");
+ uint32_t i = 0;
+ for (; i < directoryEntry->dimension_count - 1; i++) {
+ writeSubBlockDimentionEntry(&directoryEntry->dimension_entries[i], outputFile);
+ fprintf(outputFile, ", ");
+ }
+ writeSubBlockDimentionEntry(&directoryEntry->dimension_entries[i], outputFile);
+ fprintf(outputFile, "]}\n");
+}
+
+void printSubBlockDirectory(SubBlockDirectory* zisDirectory) {
+ printf("entry_count: %" PRIu32 "\n", zisDirectory->entry_count);
+ printf("reserved: %s\n", zisDirectory->reserved);
+ printf("directory_entries: \n");
+ for (uint32_t i = 0; i < zisDirectory->entry_count; i++) {
+ printSubBlockDirectoryEntry(&zisDirectory->directory_entries[i]);
+ }
+}
+void writeSubBlockDirectory(SubBlockDirectory* zisDirectory, FILE* outputFile) {
+ fprintf(outputFile, "{\n");
+ fprintf(outputFile, "\"EntryCount\": %" PRIu32 ",\n", zisDirectory->entry_count);
+ fprintf(outputFile, "\"Reserved\": \"%s\",\n", zisDirectory->reserved);
+ fprintf(outputFile, "\"Entry\": \n[\n");
+ uint32_t i = 0;
+ for (; i < zisDirectory->entry_count - 1; i++) {
+ writeSubBlockDirectoryEntry(&zisDirectory->directory_entries[i], outputFile);
+ fprintf(outputFile, ", ");
+ }
+ writeSubBlockDirectoryEntry(&zisDirectory->directory_entries[i], outputFile);
+ fprintf(outputFile, "]}\n");
+}
+//END SubBlockDirectory///////////////////////////////////////////////////////////
+
+
+
+//START METADATASEGMENT/////////////////////////////////////////////////////////
+typedef struct {
+ uint32_t xml_size;
+ uint32_t attachment_size;
+ char spare[248];
+} __attribute__ ((__packed__)) MetadataSegment;
+
+void printMetadataSegment(MetadataSegment* metaSegement) {
+ printf("xml_size: %" PRIu32 "\n", metaSegement->xml_size);
+ printf("attachment_size: %" PRIu32 "\n", metaSegement->attachment_size);
+ printf("spare: \n");
+ printf("Document Name: %s", "FILE-META-1.xml");
+}
+void writeMetadataSegment(MetadataSegment* metaSegement, FILE* outputFile) {
+ fprintf(outputFile, "{\n");
+ fprintf(outputFile, "\"XmlSize\": %" PRIu32 ",\n", metaSegement->xml_size);
+ fprintf(outputFile, "\"AttachmentSize\": %" PRIu32 ",\n", metaSegement->attachment_size);
+ fprintf(outputFile, "\"<spare>\": \"<256-8>\",\n");
+ fprintf(outputFile, "\"XmlName\": \"FILE-META-1.xml\"\n");
+ fprintf(outputFile, "}\n");
+}
+//END METADATASEGMENT///////////////////////////////////////////////////////////
+
+
+
+//START SUBBLOCKSEGMENT/////////////////////////////////////////////////////////
+typedef struct {
+ uint32_t metadata_size;
+ uint32_t attachment_size;
+ uint64_t data_size;
+ SubBlockDirectoryEntry directory_entry;
+ char* metadata;
+ void* data;
+ void* attachments;
+} __attribute__ ((__packed__)) SubBlockSegment;
+
+void printSubBlockSegment(SubBlockSegment* subBlockSegment) {
+ static int META_COUNT = 0;
+ static int DATA_COUNT = 0;
+ static int ATTACH_COUNT = 0;
+ printf("metadata_size: %" PRIu32 "\n", subBlockSegment->metadata_size);
+ printf("attachment_size: %" PRIu32 "\n", subBlockSegment->attachment_size);
+ printf("data_size: %" PRIu64 "\n", subBlockSegment->data_size);
+ printf("spare: \n");
+ printSubBlockDirectoryEntry(&subBlockSegment->directory_entry);
+ if (strncmp(subBlockSegment->metadata, "<METADATA />", subBlockSegment->metadata_size) != 0) {
+ printf("metadata: \"metadata-%d\"\n", META_COUNT++);
+ } else {
+ printf("metadata: \"empty\"\n");
+ }
+ printf("data: \"data-%d\"\n", DATA_COUNT++);
+ if (subBlockSegment->attachment_size != 0) {
+ printf("attatchments: \"attach-%d\"\n", ATTACH_COUNT++);
+ } else {
+ printf("attatchments: \"empty\"\n");
+ }
+}
+
+int findEqualDimension(SubBlockDirectoryEntry* directoryEntry, const char* dimensionName) {
+
+ for (uint32_t i = 0; i < directoryEntry->dimension_count; i++) {
+ if (strcmp(directoryEntry->dimension_entries[i].dimension, dimensionName) == 0) {
+ if (directoryEntry->dimension_entries[i].size == directoryEntry->dimension_entries[i].stored_size) {
+ return 1;
+ } else {
+ return 0;
+ }
+ }
+ }
+ return 0;
+}
+
+void writeSubBlockSegment(SubBlockSegment* subBlockSegment, FILE* outputFile) {
+
+ static int META_COUNT = 0;
+ static int DATA_COUNT = 0;
+ static int ATTACH_COUNT = 0;
+
+ fprintf(outputFile, "{\n");
+ fprintf(outputFile, "\"MetadataSize\": %" PRIu32 ",\n", subBlockSegment->metadata_size);
+ fprintf(outputFile, "\"AttachmentSize\": %" PRIu32 ",\n", subBlockSegment->attachment_size);
+ fprintf(outputFile, "\"DataSize\": %" PRIu64 ",\n", subBlockSegment->data_size);
+ fprintf(outputFile, "\"DirectoryEntry\": ");
+ writeSubBlockDirectoryEntry(&subBlockSegment->directory_entry, outputFile);
+ fprintf(outputFile, ",\n\"Fill\": \"\",\n");
+
+ /* open file for Output */
+ if (strncmp(subBlockSegment->metadata, "<METADATA />", subBlockSegment->metadata_size) != 0) {
+ writeDataToFile("metadata-", META_COUNT, ".xml", subBlockSegment->metadata, subBlockSegment->metadata_size);
+ fprintf(outputFile, "\"Metadata\": \"metadata-%d.xml\",\n", META_COUNT++);
+ } else {
+ fprintf(outputFile, "\"Metadata\": \"empty\",\n");
+ }
+
+ if (findEqualDimension(&subBlockSegment->directory_entry, "X") && findEqualDimension(&subBlockSegment->directory_entry, "Y")) {
+ writeDataToFile("data-", DATA_COUNT, ".jxr", subBlockSegment->data, subBlockSegment->data_size);
+ fprintf(outputFile, "\"Data\": \"data-%d.png\",\n", DATA_COUNT++);
+ } else {
+ fprintf(outputFile, "\"Data\": \"empty\",\n");
+ }
+
+ if (subBlockSegment->attachment_size != 0) {
+ writeDataToFile("attach-", ATTACH_COUNT, "", subBlockSegment->attachments, subBlockSegment->attachment_size);
+ fprintf(outputFile, "\"Attachments\": \"attach-%d\"\n", ATTACH_COUNT++);
+ } else {
+ fprintf(outputFile, "\"Attachments\": \"empty\"\n");
+ }
+ fprintf(outputFile, "}\n");
+}
+//END SUBBLOCKSEGMENT///////////////////////////////////////////////////////////
+
+
+
+
+
+
+
+//START ATTACHMENTENTRY/////////////////////////////////////////////////////////
+typedef struct {
+ char schema_type[2];
+ char reserved[10];
+ uint64_t file_position;
+ int file_part;
+ GUID content_guid;
+ char content_file_type[8];
+ char name[80];
+} __attribute__ ((__packed__)) AttachmentEntry;
+
+void printAttachmentEntry(AttachmentEntry* attachmentSegment){
+ printf(" schema_type: \"%c%c\"\n", attachmentSegment->schema_type[0],attachmentSegment->schema_type[1]);
+ printf(" reserved: %s\n", attachmentSegment->reserved);
+ printf(" file_position: %" PRIu64 "\n", attachmentSegment->file_position);
+ printf(" file_part: %d\n", attachmentSegment->file_part);
+ printf(" ContentGuid: [");
+ int i = 0;
+ for (; i < 15; i++) {
+ printf("%u, ", attachmentSegment->content_guid[i]);
+ }
+ printf("%u]\n", attachmentSegment->content_guid[i]);
+ printf(" content_file_type: \"%s\"\n", attachmentSegment->content_file_type);
+ printf(" name: \"%s\"\n", attachmentSegment->name);
+}
+void writeAttachmentEntry(AttachmentEntry* attachmentSegment, FILE* outputFile){
+ fprintf(outputFile, "{\n");
+ fprintf(outputFile, "\"SchemaType\": \"%c%c\",\n", attachmentSegment->schema_type[0],attachmentSegment->schema_type[1]);
+ fprintf(outputFile, "\"Reserved\": \"%s\",\n", attachmentSegment->reserved);
+ fprintf(outputFile, "\"FilePosition\": %" PRIu64 ",\n", attachmentSegment->file_position);
+ fprintf(outputFile, "\"FilePart\": %d,\n", attachmentSegment->file_part);
+ fprintf(outputFile, "\"ContentGuid\": \n[");
+ int i = 0;
+ for (; i < 15; i++) {
+ fprintf(outputFile, "%u, ", attachmentSegment->content_guid[i]);
+ }
+ fprintf(outputFile, "%u],\n", attachmentSegment->content_guid[i]);
+ fprintf(outputFile, "\"ContentFileType\": \"%s\",\n", attachmentSegment->content_file_type);
+ fprintf(outputFile, "\"Name\": \"%s\"\n", attachmentSegment->name);
+ fprintf(outputFile, "}\n");
+}
+
+//END ATTACHMENTENTRY///////////////////////////////////////////////////////////
+
+
+
+
+
+
+//START ATTACHMENTSEGMENT///////////////////////////////////////////////////////
+typedef struct {
+ uint32_t data_size;
+ char spare1[12];
+ AttachmentEntry attachment_entry;
+ char spare2[112];
+ void* data;
+} __attribute__ ((__packed__)) AttachmentSegment;
+
+void printAttachmentSegment(AttachmentSegment* attachmentSegment){
+
+ static int ATTACH_DATA_COUNT = 0;
+
+ printf("data_size: %" PRIu32 "\n", attachmentSegment->data_size);
+ printAttachmentEntry(&attachmentSegment->attachment_entry);
+ printf("data: \"attach-data-%d\"\n", ATTACH_DATA_COUNT++);
+}
+void writeAttachmentSegment(AttachmentSegment* attachmentSegment, FILE* outputFile){
+
+ static int ATTACH_DATA_COUNT = 0;
+
+ fprintf(outputFile, "{\n");
+ fprintf(outputFile, "\"DataSize\": %" PRIu32 ",\n", attachmentSegment->data_size);
+ fprintf(outputFile, "\"AttachmentEntry\": ");
+ writeAttachmentEntry(&attachmentSegment->attachment_entry, outputFile);
+
+ /* open file for Output */
+ writeDataToFile("attach-data-", ATTACH_DATA_COUNT, "", attachmentSegment->data, attachmentSegment->data_size);
+
+ fprintf(outputFile, ",\n\"Data\": \"attach-data-%d\"\n", ATTACH_DATA_COUNT++);
+ fprintf(outputFile, "}\n");
+}
+//END ATTACHMENTSEGMENT/////////////////////////////////////////////////////////
+
+
+
+//END ATTACHMENTDIRECTORY///////////////////////////////////////////////////////
+typedef struct {
+ int entry_count;
+ char reserved[252];
+ AttachmentEntry* attachment_entries;
+} __attribute__ ((__packed__)) AttachmentDirectory;
+
+void printAttachmentDirectory(AttachmentDirectory* attachmentDirectory){
+ printf("entry_count: %d\n", attachmentDirectory->entry_count);
+ for (int i = 0; i < attachmentDirectory->entry_count; i++) {
+ printAttachmentEntry(&attachmentDirectory->attachment_entries[i]);
+ }
+}
+void writeAttachmentDirectory(AttachmentDirectory* attachmentDirectory, FILE* outputFile){
+ fprintf(outputFile, "{\n");
+ fprintf(outputFile, "\"EntryCount\": %d,\n", attachmentDirectory->entry_count);
+ fprintf(outputFile, "\"Entry\": [\n");
+ int i = 0;
+ for (; i < attachmentDirectory->entry_count - 1; i++) {
+ writeAttachmentEntry(&attachmentDirectory->attachment_entries[i], outputFile);
+ fprintf(outputFile, ", ");
+ }
+ writeAttachmentEntry(&attachmentDirectory->attachment_entries[i], outputFile);
+ fprintf(outputFile, "]}\n");
+}
+//END ATTACHMENTDIRECTORY///////////////////////////////////////////////////////
diff --git a/src/conversion/czi/cziconvert.c b/src/conversion/czi/cziconvert.c
new file mode 100644
index 0000000..85b925c
--- /dev/null
+++ b/src/conversion/czi/cziconvert.c
@@ -0,0 +1,354 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "cziSegmentHeaders.h"
+
+void writeDataToFile(const char* filename, int fileCount, const char* optionalFileExtension, void* content, long contentSize);
+char extractDirName[100];
+long totalFileSize;
+long lastPercentFileProgress = -1;
+SegmentHeader* segHead;
+SubBlockDirectory* zisDirectory;
+SubBlockSegment* zisSubBlock;
+AttachmentSegment* attachmentSegment;
+AttachmentDirectory* attachmentDirectory;
+MetadataSegment* metadataSegment;
+
+
+
+void setFileOffset(FILE* streamPointer, long currentPosition, SegmentHeader* segment) {
+ // if (segment->used_size == 0) {
+ fseek(streamPointer, currentPosition + segment->allocated_size, SEEK_SET);
+ // } else {
+ // fseek(streamPointer, currentPosition + segment->used_size, SEEK_SET);
+ // }
+}
+
+int findSegmentID() {
+
+ if (strcmp(segHead->name, "ZISRAWSUBBLOCK") == 0) {
+ return 3;
+ }
+ else if (strcmp(segHead->name, "ZISRAWATTACH") == 0) {
+ return 5;
+ }
+ else if (strcmp(segHead->name, "ZISRAWATTDIR") == 0) {
+ return 6;
+ }
+ else if (strcmp(segHead->name, "ZISRAWDIRECTORY") == 0) {
+ return 2;
+ }
+ else if (strcmp(segHead->name, "DELETED") == 0) {
+ return 7;
+ }
+ else if (strcmp(segHead->name, "ZISRAWMETADATA") == 0) {
+ return 4;
+ }
+ else if (strcmp(segHead->name, "ZISRAWFILE") == 0) {
+ return 1;
+ }
+ else {
+ return -1;
+ }
+}
+
+
+void loadMainHeader(FILE* imageFile, FILE* outputFile, long* fileOffset) {
+
+ //initial thing.
+ fprintf(outputFile,"{\n");
+ writeSegmentHeader(segHead, outputFile);
+
+ //main file descriptor
+ ZisrawFile* zisFileHeader = malloc(sizeof(ZisrawFile));
+ fread(zisFileHeader, sizeof(ZisrawFile), 1, imageFile);
+
+ //print and write to file
+// printZisrawFile(zisFileHeader);
+ writeZisrawFile(zisFileHeader, outputFile);
+ free(zisFileHeader);
+ fprintf(outputFile,"}\n");
+
+ //correct for Zero Paddings
+ setFileOffset(imageFile, *fileOffset, segHead);
+}
+
+
+void loadZisDirectories(SubBlockDirectory* zisrawDirectory, FILE* imageFile) {
+
+ //Get the main directory;
+ fread(zisrawDirectory, sizeof(SubBlockDirectory), 1, imageFile);
+ //Take care for the fact that what we are using as a pointer value in struct size is actually just the first address.
+ fseek(imageFile, -8, SEEK_CUR);
+ //allocate space for each of the directory entries
+ zisrawDirectory->directory_entries = malloc(sizeof(SubBlockDirectoryEntry) * zisrawDirectory->entry_count);
+
+ //now get each Directory entry
+ for (uint32_t i = 0; i < zisrawDirectory->entry_count; i++) {
+
+ //read in the directory entry
+ fread(&zisrawDirectory->directory_entries[i], sizeof(SubBlockDirectoryEntry), 1, imageFile);
+ //Again cater for the struct pointer size difference
+ fseek(imageFile, -8, SEEK_CUR);
+
+ //malloc the dimension entry requirements into the above directory entries pointer
+ zisrawDirectory->directory_entries[i].dimension_entries = malloc(sizeof(SubBlockDimentionEntry) * zisrawDirectory->directory_entries[i].dimension_count);
+
+ //read in the dimension entries into the new malloc location
+ fread(zisrawDirectory->directory_entries[i].dimension_entries, sizeof(SubBlockDimentionEntry), zisrawDirectory->directory_entries[i].dimension_count, imageFile);
+ }
+}
+void freeZisDirectories(SubBlockDirectory* zisrawDirectory) {
+ //now get each Directory entry
+ for (uint32_t i = 0; i < zisrawDirectory->entry_count; i++) {
+ //free the dimension entry requirements into the above directory entries pointer
+ free(zisrawDirectory->directory_entries[i].dimension_entries);
+ }
+ //free space for each of the directory entries
+ free(zisrawDirectory->directory_entries);
+}
+
+
+void loadSubBlockSegment(SubBlockSegment* subBlockSegment, FILE* imageFile) {
+
+ long offsetCorrection = ftell(imageFile);
+ //Get the fixed size content;
+ fread(subBlockSegment, sizeof(SubBlockDirectoryEntry) + 8, 1, imageFile);
+ //read in the directoryEntry
+ subBlockSegment->directory_entry.dimension_entries = malloc(subBlockSegment->directory_entry.dimension_count * sizeof(SubBlockDimentionEntry));
+ //read in the dimensions
+ fread(subBlockSegment->directory_entry.dimension_entries, sizeof(SubBlockDimentionEntry), subBlockSegment->directory_entry.dimension_count, imageFile);
+
+ //Deal with the "fill" block
+ offsetCorrection = ftell(imageFile) - offsetCorrection;
+ offsetCorrection = 256 - offsetCorrection;
+ if (offsetCorrection > 0) {
+ fseek(imageFile, offsetCorrection, SEEK_CUR);
+ }
+
+ // metadata block
+ subBlockSegment->metadata = malloc(subBlockSegment->metadata_size);
+ fread(subBlockSegment->metadata, 1, subBlockSegment->metadata_size, imageFile);
+
+ // data block
+ subBlockSegment->data = malloc(subBlockSegment->data_size);
+ fread(subBlockSegment->data, 1, subBlockSegment->data_size, imageFile);
+
+ // attach block
+ subBlockSegment->attachments = malloc(subBlockSegment->attachment_size);
+ fread(subBlockSegment->attachments, 1, subBlockSegment->attachment_size, imageFile);
+}
+void freeSubBlockSegment(SubBlockSegment* subBlockSegment) {
+ //free the directoryEntry
+ free(subBlockSegment->directory_entry.dimension_entries);
+
+ // metadata block
+ free(subBlockSegment->metadata);
+
+ // data block
+ free(subBlockSegment->data);
+
+ // attach block
+ free(subBlockSegment->attachments);
+}
+
+
+void loadAttachmentSegment(AttachmentSegment* attachmentSegment, FILE* imageFile) {
+
+ //Get the fixed size content;
+ fread(attachmentSegment, sizeof(AttachmentSegment), 1, imageFile);
+ //account for the pointer space
+ fseek(imageFile, -8, SEEK_CUR);
+
+ //make space for the data element;
+ attachmentSegment->data = malloc(attachmentSegment->data_size);
+
+ //read in the data
+ fread(attachmentSegment->data, attachmentSegment->data_size, 1, imageFile);
+}
+void freeAttachmentSegment(AttachmentSegment* attachmentSegment) {
+ //free the data area
+ free(attachmentSegment->data);
+}
+
+
+void loadAttachmentDirectory(AttachmentDirectory* attachmentDirectory, FILE* imageFile) {
+
+ //Get the fixed size content;
+ fread(attachmentDirectory, sizeof(AttachmentDirectory), 1, imageFile);
+ //account for the pointer space
+ fseek(imageFile, -8, SEEK_CUR);
+ //malloc the space for the attachments;
+ attachmentDirectory->attachment_entries = malloc(sizeof(AttachmentEntry) * attachmentDirectory->entry_count);
+ //read in the content;
+ fread(attachmentDirectory->attachment_entries, sizeof(AttachmentEntry), attachmentDirectory->entry_count, imageFile);
+}
+void freeAttachmentDirectory(AttachmentDirectory* attachmentDirectory) {
+ //free the entries area
+ free(attachmentDirectory->attachment_entries);
+}
+
+void loadMetadataSegment(MetadataSegment* metadataSegment, FILE* imageFile) {
+ fread(metadataSegment, sizeof(MetadataSegment), 1, imageFile);
+}
+void loadAndWriteMetadataData(MetadataSegment* metadataSegment, FILE* imageFile) {
+ void* rawMetadata = malloc(metadataSegment->xml_size);
+ fread(rawMetadata, 1, metadataSegment->xml_size, imageFile);
+ writeDataToFile("FILE-META-", 1, ".xml", rawMetadata, metadataSegment->xml_size);
+ free(rawMetadata);
+}
+
+
+int functionRouter(FILE* imageFile, FILE* jsonOutput, long* fileOffset) {
+
+ //next segment header
+ long newPercent = (100 * ftell(imageFile) / totalFileSize);
+ if (newPercent > lastPercentFileProgress) {
+ lastPercentFileProgress = newPercent;
+ printf("> Amount of CZI file extracted: %3ld%%\n", lastPercentFileProgress);
+ }
+
+ if (fread(segHead, sizeof(SegmentHeader), 1, imageFile) != 1) {
+ return 0;
+ }
+ *fileOffset = ftell(imageFile);
+
+ //"prettify + print lol"
+// printSegmentHeader(segHead);
+ fprintf(jsonOutput,"{\n");
+ writeSegmentHeader(segHead, jsonOutput);
+
+ //deal with the specific kind of segement.
+ switch (findSegmentID()) {
+
+ //FileTitle
+ case 1:
+ loadMainHeader(imageFile, jsonOutput, fileOffset);
+ break;
+
+ //Directory
+ case 2:
+ loadZisDirectories(zisDirectory, imageFile);
+ writeSubBlockDirectory(zisDirectory, jsonOutput);
+ freeZisDirectories(zisDirectory);
+ break;
+
+ //Subblock
+ case 3:
+ loadSubBlockSegment(zisSubBlock, imageFile);
+// printSubBlockSegment(zisSubBlock);
+ writeSubBlockSegment(zisSubBlock, jsonOutput);
+ freeSubBlockSegment(zisSubBlock);
+ break;
+
+ //MetaData
+ case 4:
+ loadMetadataSegment(metadataSegment, imageFile);
+// printMetadataSegment(metadataSegment);
+ writeMetadataSegment(metadataSegment, jsonOutput);
+ loadAndWriteMetadataData(metadataSegment, imageFile);
+ break;
+
+ //Attseg
+ case 5:
+ loadAttachmentSegment(attachmentSegment, imageFile);
+// printAttachmentSegment(attachmentSegment);
+ writeAttachmentSegment(attachmentSegment, jsonOutput);
+ freeAttachmentSegment(attachmentSegment);
+ break;
+
+ //Attdir
+ case 6:
+ loadAttachmentDirectory(attachmentDirectory, imageFile);
+// printAttachmentDirectory(attachmentDirectory);
+ writeAttachmentDirectory(attachmentDirectory, jsonOutput);
+ freeAttachmentDirectory(attachmentDirectory);
+ break;
+
+ //DELETED
+ case 7:
+ fprintf(jsonOutput, "{}");
+ break;
+
+ default:
+ fprintf(stderr, "FAILED TO PARSE SEGMENT HEADER: %s", segHead->name);
+ exit(1);
+ }
+
+ setFileOffset(imageFile, *fileOffset, segHead);
+ fprintf(jsonOutput,"},\n");
+ return 1;
+}
+
+int main(int argc, char* argv[]) {
+
+ //Check program input arguments.
+ if (argc < 2 || argc > 4) {
+ printf("Invalid number of arguments passed in.\nUsage:\n\n./prog <input file> <outputjson> <pythonJxrConvertor>\n\n");
+ exit(1);
+ }
+
+ //create file objects;
+ FILE* imageFile;
+ FILE* jsonOutput;
+ long fileOffset = 0;
+ strcpy(extractDirName, argv[2]);
+
+ /* open file for input */
+ if ((imageFile = fopen(argv[1], "r"))==NULL){
+ printf("Read error occurred, check file path.");
+ exit(1);
+ }
+ fseek(imageFile, 0, SEEK_END);
+ totalFileSize = ftell(imageFile);
+ fseek(imageFile, 0, SEEK_SET);
+
+ /* open file for Output */
+ char jsonName[90];
+ strcpy(jsonName, extractDirName);
+ strcat(jsonName, "outputjson.json");
+ if ((jsonOutput = fopen(jsonName, "w"))==NULL){
+ printf("Write error occurred, check file path.");
+ exit(1);
+ }
+ fprintf(jsonOutput,"{ \"czi\": [\n");
+
+
+ //create heap space for a header and directory stuff.
+ segHead = malloc(sizeof(SegmentHeader));
+ zisDirectory = malloc(sizeof(SubBlockDirectory));
+ zisSubBlock = malloc(sizeof(SubBlockSegment));
+ attachmentSegment = malloc(sizeof(AttachmentSegment));
+ attachmentDirectory = malloc(sizeof(AttachmentDirectory));
+ metadataSegment = malloc(sizeof(MetadataSegment));
+
+
+ printf("\n=========== BEGIN CZI EXTRACTION ===========\n\n");
+ while (functionRouter(imageFile, jsonOutput, &fileOffset));
+ //get rid of the last comma
+ fseek(jsonOutput, -2, SEEK_CUR);
+ //close stuff
+ free(segHead);
+ free(zisDirectory);
+ free(zisSubBlock);
+ free(attachmentSegment);
+ free(attachmentDirectory);
+ free(metadataSegment);
+ fclose(imageFile);
+ fprintf(jsonOutput,"\n]}\n");
+ fclose(jsonOutput);
+
+ printf("\n=========== FINISH CZI EXTRACTION ===========\n\n\n\n");
+
+ //convert all the data's to jxr;
+ char jxrLoc[200];
+ sprintf(jxrLoc, "%s %s %s", "python3", argv[3], argv[2]);
+ system(jxrLoc);
+
+
+ //begin work on re-factoring the image structure into a "smooth" grid
+
+
+ return 0;
+}