Merge pull request #528 from mayeut/zlib-1.2.8
[openjpeg.git] / thirdparty / liblcms2 / src / cmsio0.c
1 //---------------------------------------------------------------------------------
2 //
3 //  Little Color Management System
4 //  Copyright (c) 1998-2012 Marti Maria Saguer
5 //
6 // Permission is hereby granted, free of charge, to any person obtaining
7 // a copy of this software and associated documentation files (the "Software"),
8 // to deal in the Software without restriction, including without limitation
9 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 // and/or sell copies of the Software, and to permit persons to whom the Software
11 // is furnished to do so, subject to the following conditions:
12 //
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
15 //
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
18 // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 //
24 //---------------------------------------------------------------------------------
25 //
26
27 #include "lcms2_internal.h"
28
29 // Generic I/O, tag dictionary management, profile struct
30
31 // IOhandlers are abstractions used by littleCMS to read from whatever file, stream,
32 // memory block or any storage. Each IOhandler provides implementations for read,
33 // write, seek and tell functions. LittleCMS code deals with IO across those objects.
34 // In this way, is easier to add support for new storage media.
35
36 // NULL stream, for taking care of used space -------------------------------------
37
38 // NULL IOhandler basically does nothing but keep track on how many bytes have been
39 // written. This is handy when creating profiles, where the file size is needed in the
40 // header. Then, whole profile is serialized across NULL IOhandler and a second pass
41 // writes the bytes to the pertinent IOhandler.
42
43 typedef struct {
44     cmsUInt32Number Pointer;         // Points to current location
45 } FILENULL;
46
47 static
48 cmsUInt32Number NULLRead(cmsIOHANDLER* iohandler, void *Buffer, cmsUInt32Number size, cmsUInt32Number count)
49 {
50     FILENULL* ResData = (FILENULL*) iohandler ->stream;
51
52     cmsUInt32Number len = size * count;
53     ResData -> Pointer += len;
54     return count;
55
56     cmsUNUSED_PARAMETER(Buffer);
57 }
58
59 static
60 cmsBool  NULLSeek(cmsIOHANDLER* iohandler, cmsUInt32Number offset)
61 {
62     FILENULL* ResData = (FILENULL*) iohandler ->stream;
63
64     ResData ->Pointer = offset;
65     return TRUE;
66 }
67
68 static
69 cmsUInt32Number NULLTell(cmsIOHANDLER* iohandler)
70 {
71     FILENULL* ResData = (FILENULL*) iohandler ->stream;
72     return ResData -> Pointer;
73 }
74
75 static
76 cmsBool  NULLWrite(cmsIOHANDLER* iohandler, cmsUInt32Number size, const void *Ptr)
77 {
78     FILENULL* ResData = (FILENULL*) iohandler ->stream;
79
80     ResData ->Pointer += size;
81     if (ResData ->Pointer > iohandler->UsedSpace)
82         iohandler->UsedSpace = ResData ->Pointer;
83
84     return TRUE;
85
86     cmsUNUSED_PARAMETER(Ptr);
87 }
88
89 static
90 cmsBool  NULLClose(cmsIOHANDLER* iohandler)
91 {
92     FILENULL* ResData = (FILENULL*) iohandler ->stream;
93
94     _cmsFree(iohandler ->ContextID, ResData);
95     _cmsFree(iohandler ->ContextID, iohandler);
96     return TRUE;
97 }
98
99 // The NULL IOhandler creator
100 cmsIOHANDLER*  CMSEXPORT cmsOpenIOhandlerFromNULL(cmsContext ContextID)
101 {
102     struct _cms_io_handler* iohandler = NULL;
103     FILENULL* fm = NULL;
104
105     iohandler = (struct _cms_io_handler*) _cmsMallocZero(ContextID, sizeof(struct _cms_io_handler));
106     if (iohandler == NULL) return NULL;
107
108     fm = (FILENULL*) _cmsMallocZero(ContextID, sizeof(FILENULL));
109     if (fm == NULL) goto Error;
110
111     fm ->Pointer = 0;
112
113     iohandler ->ContextID = ContextID;
114     iohandler ->stream  = (void*) fm;
115     iohandler ->UsedSpace = 0;
116     iohandler ->ReportedSize = 0;
117     iohandler ->PhysicalFile[0] = 0;
118
119     iohandler ->Read    = NULLRead;
120     iohandler ->Seek    = NULLSeek;
121     iohandler ->Close   = NULLClose;
122     iohandler ->Tell    = NULLTell;
123     iohandler ->Write   = NULLWrite;
124
125     return iohandler;
126
127 Error:    
128     if (iohandler) _cmsFree(ContextID, iohandler);
129     return NULL;
130
131 }
132
133
134 // Memory-based stream --------------------------------------------------------------
135
136 // Those functions implements an iohandler which takes a block of memory as storage medium.
137
138 typedef struct {
139     cmsUInt8Number* Block;    // Points to allocated memory
140     cmsUInt32Number Size;     // Size of allocated memory
141     cmsUInt32Number Pointer;  // Points to current location
142     int FreeBlockOnClose;     // As title
143
144 } FILEMEM;
145
146 static
147 cmsUInt32Number MemoryRead(struct _cms_io_handler* iohandler, void *Buffer, cmsUInt32Number size, cmsUInt32Number count)
148 {
149     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
150     cmsUInt8Number* Ptr;
151     cmsUInt32Number len = size * count;
152
153     if (ResData -> Pointer + len > ResData -> Size){
154
155         len = (ResData -> Size - ResData -> Pointer);
156         cmsSignalError(iohandler ->ContextID, cmsERROR_READ, "Read from memory error. Got %d bytes, block should be of %d bytes", len, count * size);
157         return 0;
158     }
159
160     Ptr  = ResData -> Block;
161     Ptr += ResData -> Pointer;
162     memmove(Buffer, Ptr, len);
163     ResData -> Pointer += len;
164
165     return count;
166 }
167
168 // SEEK_CUR is assumed
169 static
170 cmsBool  MemorySeek(struct _cms_io_handler* iohandler, cmsUInt32Number offset)
171 {
172     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
173
174     if (offset > ResData ->Size) {
175         cmsSignalError(iohandler ->ContextID, cmsERROR_SEEK,  "Too few data; probably corrupted profile");
176         return FALSE;
177     }
178
179     ResData ->Pointer = offset;
180     return TRUE;
181 }
182
183 // Tell for memory
184 static
185 cmsUInt32Number MemoryTell(struct _cms_io_handler* iohandler)
186 {
187     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
188
189     if (ResData == NULL) return 0;
190     return ResData -> Pointer;
191 }
192
193
194 // Writes data to memory, also keeps used space for further reference.
195 static
196 cmsBool MemoryWrite(struct _cms_io_handler* iohandler, cmsUInt32Number size, const void *Ptr)
197 {
198     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
199
200     if (ResData == NULL) return FALSE; // Housekeeping
201
202     // Check for available space. Clip.
203     if (ResData->Pointer + size > ResData->Size) {
204         size = ResData ->Size - ResData->Pointer;
205     }
206       
207     if (size == 0) return TRUE;     // Write zero bytes is ok, but does nothing
208
209     memmove(ResData ->Block + ResData ->Pointer, Ptr, size);
210     ResData ->Pointer += size;
211
212     if (ResData ->Pointer > iohandler->UsedSpace)
213         iohandler->UsedSpace = ResData ->Pointer;
214
215     return TRUE;
216 }
217
218
219 static
220 cmsBool  MemoryClose(struct _cms_io_handler* iohandler)
221 {
222     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
223
224     if (ResData ->FreeBlockOnClose) {
225
226         if (ResData ->Block) _cmsFree(iohandler ->ContextID, ResData ->Block);
227     }
228
229     _cmsFree(iohandler ->ContextID, ResData);
230     _cmsFree(iohandler ->ContextID, iohandler);
231
232     return TRUE;
233 }
234
235 // Create a iohandler for memory block. AccessMode=='r' assumes the iohandler is going to read, and makes
236 // a copy of the memory block for letting user to free the memory after invoking open profile. In write
237 // mode ("w"), Buffere points to the begin of memory block to be written.
238 cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromMem(cmsContext ContextID, void *Buffer, cmsUInt32Number size, const char* AccessMode)
239 {
240     cmsIOHANDLER* iohandler = NULL;
241     FILEMEM* fm = NULL;
242
243     _cmsAssert(AccessMode != NULL);
244
245     iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
246     if (iohandler == NULL) return NULL;
247
248     switch (*AccessMode) {
249
250     case 'r':
251         fm = (FILEMEM*) _cmsMallocZero(ContextID, sizeof(FILEMEM));
252         if (fm == NULL) goto Error;
253
254         if (Buffer == NULL) {
255             cmsSignalError(ContextID, cmsERROR_READ, "Couldn't read profile from NULL pointer");
256             goto Error;
257         }
258
259         fm ->Block = (cmsUInt8Number*) _cmsMalloc(ContextID, size);
260         if (fm ->Block == NULL) {
261
262             _cmsFree(ContextID, fm);
263             _cmsFree(ContextID, iohandler);
264             cmsSignalError(ContextID, cmsERROR_READ, "Couldn't allocate %ld bytes for profile", size);
265             return NULL;
266         }
267
268
269         memmove(fm->Block, Buffer, size);
270         fm ->FreeBlockOnClose = TRUE;
271         fm ->Size    = size;
272         fm ->Pointer = 0;
273         iohandler -> ReportedSize = size;
274         break;
275
276     case 'w':
277         fm = (FILEMEM*) _cmsMallocZero(ContextID, sizeof(FILEMEM));
278         if (fm == NULL) goto Error;
279
280         fm ->Block = (cmsUInt8Number*) Buffer;
281         fm ->FreeBlockOnClose = FALSE;
282         fm ->Size    = size;
283         fm ->Pointer = 0;
284         iohandler -> ReportedSize = 0;
285         break;
286
287     default:
288         cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown access mode '%c'", *AccessMode);
289         return NULL;
290     }
291
292     iohandler ->ContextID = ContextID;
293     iohandler ->stream  = (void*) fm;
294     iohandler ->UsedSpace = 0;
295     iohandler ->PhysicalFile[0] = 0;
296
297     iohandler ->Read    = MemoryRead;
298     iohandler ->Seek    = MemorySeek;
299     iohandler ->Close   = MemoryClose;
300     iohandler ->Tell    = MemoryTell;
301     iohandler ->Write   = MemoryWrite;
302
303     return iohandler;
304
305 Error:
306     if (fm) _cmsFree(ContextID, fm);
307     if (iohandler) _cmsFree(ContextID, iohandler);
308     return NULL;
309 }
310
311 // File-based stream -------------------------------------------------------
312
313 // Read count elements of size bytes each. Return number of elements read
314 static
315 cmsUInt32Number FileRead(cmsIOHANDLER* iohandler, void *Buffer, cmsUInt32Number size, cmsUInt32Number count)
316 {
317     cmsUInt32Number nReaded = (cmsUInt32Number) fread(Buffer, size, count, (FILE*) iohandler->stream);
318
319     if (nReaded != count) {
320             cmsSignalError(iohandler ->ContextID, cmsERROR_FILE, "Read error. Got %d bytes, block should be of %d bytes", nReaded * size, count * size);
321             return 0;
322     }
323
324     return nReaded;
325 }
326
327 // Postion file pointer in the file
328 static
329 cmsBool  FileSeek(cmsIOHANDLER* iohandler, cmsUInt32Number offset)
330 {
331     if (fseek((FILE*) iohandler ->stream, (long) offset, SEEK_SET) != 0) {
332
333        cmsSignalError(iohandler ->ContextID, cmsERROR_FILE, "Seek error; probably corrupted file");
334        return FALSE;
335     }
336
337     return TRUE;
338 }
339
340 // Returns file pointer position
341 static
342 cmsUInt32Number FileTell(cmsIOHANDLER* iohandler)
343 {
344     return (cmsUInt32Number) ftell((FILE*)iohandler ->stream);
345 }
346
347 // Writes data to stream, also keeps used space for further reference. Returns TRUE on success, FALSE on error
348 static
349 cmsBool  FileWrite(cmsIOHANDLER* iohandler, cmsUInt32Number size, const void* Buffer)
350 {
351        if (size == 0) return TRUE;  // We allow to write 0 bytes, but nothing is written
352
353        iohandler->UsedSpace += size;
354        return (fwrite(Buffer, size, 1, (FILE*) iohandler->stream) == 1);
355 }
356
357 // Closes the file
358 static
359 cmsBool  FileClose(cmsIOHANDLER* iohandler)
360 {
361     if (fclose((FILE*) iohandler ->stream) != 0) return FALSE;
362     _cmsFree(iohandler ->ContextID, iohandler);
363     return TRUE;
364 }
365
366 // Create a iohandler for disk based files.
367 cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromFile(cmsContext ContextID, const char* FileName, const char* AccessMode)
368 {
369     cmsIOHANDLER* iohandler = NULL;
370     FILE* fm = NULL;
371
372     _cmsAssert(FileName != NULL);
373     _cmsAssert(AccessMode != NULL);
374
375     iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
376     if (iohandler == NULL) return NULL;
377
378     switch (*AccessMode) {
379
380     case 'r':
381         fm = fopen(FileName, "rb");
382         if (fm == NULL) {
383             _cmsFree(ContextID, iohandler);
384              cmsSignalError(ContextID, cmsERROR_FILE, "File '%s' not found", FileName);
385             return NULL;
386         }
387         iohandler -> ReportedSize = (cmsUInt32Number) cmsfilelength(fm);
388         break;
389
390     case 'w':
391         fm = fopen(FileName, "wb");
392         if (fm == NULL) {
393             _cmsFree(ContextID, iohandler);
394              cmsSignalError(ContextID, cmsERROR_FILE, "Couldn't create '%s'", FileName);
395             return NULL;
396         }
397         iohandler -> ReportedSize = 0;
398         break;
399
400     default:
401         _cmsFree(ContextID, iohandler);
402          cmsSignalError(ContextID, cmsERROR_FILE, "Unknown access mode '%c'", *AccessMode);
403         return NULL;
404     }
405
406     iohandler ->ContextID = ContextID;
407     iohandler ->stream = (void*) fm;
408     iohandler ->UsedSpace = 0;
409
410     // Keep track of the original file    
411     strncpy(iohandler -> PhysicalFile, FileName, sizeof(iohandler -> PhysicalFile)-1);
412     iohandler -> PhysicalFile[sizeof(iohandler -> PhysicalFile)-1] = 0;
413
414     iohandler ->Read    = FileRead;
415     iohandler ->Seek    = FileSeek;
416     iohandler ->Close   = FileClose;
417     iohandler ->Tell    = FileTell;
418     iohandler ->Write   = FileWrite;
419
420     return iohandler;
421 }
422
423 // Create a iohandler for stream based files
424 cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromStream(cmsContext ContextID, FILE* Stream)
425 {
426     cmsIOHANDLER* iohandler = NULL;
427
428     iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
429     if (iohandler == NULL) return NULL;
430
431     iohandler -> ContextID = ContextID;
432     iohandler -> stream = (void*) Stream;
433     iohandler -> UsedSpace = 0;
434     iohandler -> ReportedSize = (cmsUInt32Number) cmsfilelength(Stream);
435     iohandler -> PhysicalFile[0] = 0;
436
437     iohandler ->Read    = FileRead;
438     iohandler ->Seek    = FileSeek;
439     iohandler ->Close   = FileClose;
440     iohandler ->Tell    = FileTell;
441     iohandler ->Write   = FileWrite;
442
443     return iohandler;
444 }
445
446
447
448 // Close an open IO handler
449 cmsBool CMSEXPORT cmsCloseIOhandler(cmsIOHANDLER* io)
450 {
451     return io -> Close(io);
452 }
453
454 // -------------------------------------------------------------------------------------------------------
455
456 // Creates an empty structure holding all required parameters
457 cmsHPROFILE CMSEXPORT cmsCreateProfilePlaceholder(cmsContext ContextID)
458 {
459     time_t now = time(NULL);
460     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) _cmsMallocZero(ContextID, sizeof(_cmsICCPROFILE));
461     if (Icc == NULL) return NULL;
462
463     Icc ->ContextID = ContextID;
464
465     // Set it to empty
466     Icc -> TagCount   = 0;
467
468     // Set default version
469     Icc ->Version =  0x02100000;
470
471     // Set creation date/time
472     memmove(&Icc ->Created, gmtime(&now), sizeof(Icc ->Created));
473
474     // Create a mutex if the user provided proper plugin. NULL otherwise
475     Icc ->UsrMutex = _cmsCreateMutex(ContextID);
476
477     // Return the handle
478     return (cmsHPROFILE) Icc;
479 }
480
481 cmsContext CMSEXPORT cmsGetProfileContextID(cmsHPROFILE hProfile)
482 {
483      _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
484
485     if (Icc == NULL) return NULL;
486     return Icc -> ContextID;
487 }
488
489
490 // Return the number of tags
491 cmsInt32Number CMSEXPORT cmsGetTagCount(cmsHPROFILE hProfile)
492 {
493     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
494     if (Icc == NULL) return -1;
495
496     return  Icc->TagCount;
497 }
498
499 // Return the tag signature of a given tag number
500 cmsTagSignature CMSEXPORT cmsGetTagSignature(cmsHPROFILE hProfile, cmsUInt32Number n)
501 {
502     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
503
504     if (n > Icc->TagCount) return (cmsTagSignature) 0;  // Mark as not available
505     if (n >= MAX_TABLE_TAG) return (cmsTagSignature) 0; // As double check
506
507     return Icc ->TagNames[n];
508 }
509
510
511 static
512 int SearchOneTag(_cmsICCPROFILE* Profile, cmsTagSignature sig)
513 {
514     cmsUInt32Number i;
515
516     for (i=0; i < Profile -> TagCount; i++) {
517
518         if (sig == Profile -> TagNames[i])
519             return i;
520     }
521
522     return -1;
523 }
524
525 // Search for a specific tag in tag dictionary. Returns position or -1 if tag not found.
526 // If followlinks is turned on, then the position of the linked tag is returned
527 int _cmsSearchTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, cmsBool lFollowLinks)
528 {
529     int n;
530     cmsTagSignature LinkedSig;
531
532     do {
533
534         // Search for given tag in ICC profile directory
535         n = SearchOneTag(Icc, sig);
536         if (n < 0)
537             return -1;        // Not found
538
539         if (!lFollowLinks)
540             return n;         // Found, don't follow links
541
542         // Is this a linked tag?
543         LinkedSig = Icc ->TagLinked[n];
544
545         // Yes, follow link
546         if (LinkedSig != (cmsTagSignature) 0) {
547             sig = LinkedSig;
548         }
549
550     } while (LinkedSig != (cmsTagSignature) 0);
551
552     return n;
553 }
554
555 // Deletes a tag entry
556
557 static
558 void _cmsDeleteTagByPos(_cmsICCPROFILE* Icc, int i)
559 {
560     _cmsAssert(Icc != NULL);
561     _cmsAssert(i >= 0);
562
563    
564     if (Icc -> TagPtrs[i] != NULL) {
565
566         // Free previous version
567         if (Icc ->TagSaveAsRaw[i]) {
568             _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
569         }
570         else {
571             cmsTagTypeHandler* TypeHandler = Icc ->TagTypeHandlers[i];
572
573             if (TypeHandler != NULL) {
574
575                 cmsTagTypeHandler LocalTypeHandler = *TypeHandler;
576                 LocalTypeHandler.ContextID = Icc ->ContextID;              // As an additional parameter
577                 LocalTypeHandler.ICCVersion = Icc ->Version;
578                 LocalTypeHandler.FreePtr(&LocalTypeHandler, Icc -> TagPtrs[i]);
579                 Icc ->TagPtrs[i] = NULL;
580             }
581         }
582
583     } 
584 }
585
586
587 // Creates a new tag entry
588 static
589 cmsBool _cmsNewTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, int* NewPos)
590 {
591     int i;
592
593     // Search for the tag
594     i = _cmsSearchTag(Icc, sig, FALSE);
595     if (i >= 0) {
596
597         // Already exists? delete it
598         _cmsDeleteTagByPos(Icc, i);
599         *NewPos = i;
600     }
601     else  {
602
603         // No, make a new one
604
605         if (Icc -> TagCount >= MAX_TABLE_TAG) {
606             cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", MAX_TABLE_TAG);
607             return FALSE;
608         }
609
610         *NewPos = Icc ->TagCount;
611         Icc -> TagCount++;
612     }
613
614     return TRUE;
615 }
616
617
618 // Check existance
619 cmsBool CMSEXPORT cmsIsTag(cmsHPROFILE hProfile, cmsTagSignature sig)
620 {
621        _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) (void*) hProfile;
622        return _cmsSearchTag(Icc, sig, FALSE) >= 0;
623 }
624
625
626 // Read profile header and validate it
627 cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
628 {
629     cmsTagEntry Tag;
630     cmsICCHeader Header;
631     cmsUInt32Number i, j;
632     cmsUInt32Number HeaderSize;
633     cmsIOHANDLER* io = Icc ->IOhandler;
634     cmsUInt32Number TagCount;
635
636
637     // Read the header
638     if (io -> Read(io, &Header, sizeof(cmsICCHeader), 1) != 1) {
639         return FALSE;
640     }
641
642     // Validate file as an ICC profile
643     if (_cmsAdjustEndianess32(Header.magic) != cmsMagicNumber) {
644         cmsSignalError(Icc ->ContextID, cmsERROR_BAD_SIGNATURE, "not an ICC profile, invalid signature");
645         return FALSE;
646     }
647
648     // Adjust endianess of the used parameters
649     Icc -> DeviceClass     = (cmsProfileClassSignature) _cmsAdjustEndianess32(Header.deviceClass);
650     Icc -> ColorSpace      = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.colorSpace);
651     Icc -> PCS             = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.pcs);
652    
653     Icc -> RenderingIntent = _cmsAdjustEndianess32(Header.renderingIntent);
654     Icc -> flags           = _cmsAdjustEndianess32(Header.flags);
655     Icc -> manufacturer    = _cmsAdjustEndianess32(Header.manufacturer);
656     Icc -> model           = _cmsAdjustEndianess32(Header.model);
657     Icc -> creator         = _cmsAdjustEndianess32(Header.creator);
658     
659     _cmsAdjustEndianess64(&Icc -> attributes, &Header.attributes);
660     Icc -> Version         = _cmsAdjustEndianess32(Header.version);
661
662     // Get size as reported in header
663     HeaderSize = _cmsAdjustEndianess32(Header.size);
664
665     // Make sure HeaderSize is lower than profile size
666     if (HeaderSize >= Icc ->IOhandler ->ReportedSize)
667             HeaderSize = Icc ->IOhandler ->ReportedSize;
668
669
670     // Get creation date/time
671     _cmsDecodeDateTimeNumber(&Header.date, &Icc ->Created);
672
673     // The profile ID are 32 raw bytes
674     memmove(Icc ->ProfileID.ID32, Header.profileID.ID32, 16);
675
676
677     // Read tag directory
678     if (!_cmsReadUInt32Number(io, &TagCount)) return FALSE;
679     if (TagCount > MAX_TABLE_TAG) {
680
681         cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", TagCount);
682         return FALSE;
683     }
684
685
686     // Read tag directory
687     Icc -> TagCount = 0;
688     for (i=0; i < TagCount; i++) {
689
690         if (!_cmsReadUInt32Number(io, (cmsUInt32Number *) &Tag.sig)) return FALSE;
691         if (!_cmsReadUInt32Number(io, &Tag.offset)) return FALSE;
692         if (!_cmsReadUInt32Number(io, &Tag.size)) return FALSE;
693
694         // Perform some sanity check. Offset + size should fall inside file.
695         if (Tag.offset + Tag.size > HeaderSize ||
696             Tag.offset + Tag.size < Tag.offset)
697                   continue;
698
699         Icc -> TagNames[Icc ->TagCount]   = Tag.sig;
700         Icc -> TagOffsets[Icc ->TagCount] = Tag.offset;
701         Icc -> TagSizes[Icc ->TagCount]   = Tag.size;
702
703        // Search for links
704         for (j=0; j < Icc ->TagCount; j++) {
705
706             if ((Icc ->TagOffsets[j] == Tag.offset) &&
707                 (Icc ->TagSizes[j]   == Tag.size)) {
708
709                 Icc ->TagLinked[Icc ->TagCount] = Icc ->TagNames[j];
710             }
711
712         }
713
714         Icc ->TagCount++;
715     }
716
717     return TRUE;
718 }
719
720 // Saves profile header
721 cmsBool _cmsWriteHeader(_cmsICCPROFILE* Icc, cmsUInt32Number UsedSpace)
722 {
723     cmsICCHeader Header;
724     cmsUInt32Number i;
725     cmsTagEntry Tag;
726     cmsInt32Number Count = 0;
727
728     Header.size        = _cmsAdjustEndianess32(UsedSpace);
729     Header.cmmId       = _cmsAdjustEndianess32(lcmsSignature);
730     Header.version     = _cmsAdjustEndianess32(Icc ->Version);
731
732     Header.deviceClass = (cmsProfileClassSignature) _cmsAdjustEndianess32(Icc -> DeviceClass);
733     Header.colorSpace  = (cmsColorSpaceSignature) _cmsAdjustEndianess32(Icc -> ColorSpace);
734     Header.pcs         = (cmsColorSpaceSignature) _cmsAdjustEndianess32(Icc -> PCS);
735
736     //   NOTE: in v4 Timestamp must be in UTC rather than in local time
737     _cmsEncodeDateTimeNumber(&Header.date, &Icc ->Created);
738
739     Header.magic       = _cmsAdjustEndianess32(cmsMagicNumber);
740
741 #ifdef CMS_IS_WINDOWS_
742     Header.platform    = (cmsPlatformSignature) _cmsAdjustEndianess32(cmsSigMicrosoft);
743 #else
744     Header.platform    = (cmsPlatformSignature) _cmsAdjustEndianess32(cmsSigMacintosh);
745 #endif
746
747     Header.flags        = _cmsAdjustEndianess32(Icc -> flags);
748     Header.manufacturer = _cmsAdjustEndianess32(Icc -> manufacturer);
749     Header.model        = _cmsAdjustEndianess32(Icc -> model);
750
751     _cmsAdjustEndianess64(&Header.attributes, &Icc -> attributes);
752
753     // Rendering intent in the header (for embedded profiles)
754     Header.renderingIntent = _cmsAdjustEndianess32(Icc -> RenderingIntent);
755
756     // Illuminant is always D50
757     Header.illuminant.X = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(cmsD50_XYZ()->X));
758     Header.illuminant.Y = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(cmsD50_XYZ()->Y));
759     Header.illuminant.Z = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(cmsD50_XYZ()->Z));
760
761     // Created by LittleCMS (that's me!)
762     Header.creator      = _cmsAdjustEndianess32(lcmsSignature);
763
764     memset(&Header.reserved, 0, sizeof(Header.reserved));
765
766     // Set profile ID. Endianess is always big endian
767     memmove(&Header.profileID, &Icc ->ProfileID, 16);
768
769     // Dump the header
770     if (!Icc -> IOhandler->Write(Icc->IOhandler, sizeof(cmsICCHeader), &Header)) return FALSE;
771
772     // Saves Tag directory
773
774     // Get true count
775     for (i=0;  i < Icc -> TagCount; i++) {
776         if (Icc ->TagNames[i] != 0)
777             Count++;
778     }
779
780     // Store number of tags
781     if (!_cmsWriteUInt32Number(Icc ->IOhandler, Count)) return FALSE;
782
783     for (i=0; i < Icc -> TagCount; i++) {
784
785         if (Icc ->TagNames[i] == 0) continue;   // It is just a placeholder
786
787         Tag.sig    = (cmsTagSignature) _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagNames[i]);
788         Tag.offset = _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagOffsets[i]);
789         Tag.size   = _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagSizes[i]);
790
791         if (!Icc ->IOhandler -> Write(Icc-> IOhandler, sizeof(cmsTagEntry), &Tag)) return FALSE;
792     }
793
794     return TRUE;
795 }
796
797 // ----------------------------------------------------------------------- Set/Get several struct members
798
799
800 cmsUInt32Number CMSEXPORT cmsGetHeaderRenderingIntent(cmsHPROFILE hProfile)
801 {
802     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
803     return Icc -> RenderingIntent;
804 }
805
806 void CMSEXPORT cmsSetHeaderRenderingIntent(cmsHPROFILE hProfile, cmsUInt32Number RenderingIntent)
807 {
808     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
809     Icc -> RenderingIntent = RenderingIntent;
810 }
811
812 cmsUInt32Number CMSEXPORT cmsGetHeaderFlags(cmsHPROFILE hProfile)
813 {
814     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
815     return (cmsUInt32Number) Icc -> flags;
816 }
817
818 void CMSEXPORT cmsSetHeaderFlags(cmsHPROFILE hProfile, cmsUInt32Number Flags)
819 {
820     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
821     Icc -> flags = (cmsUInt32Number) Flags;
822 }
823
824 cmsUInt32Number CMSEXPORT cmsGetHeaderManufacturer(cmsHPROFILE hProfile)
825 {
826     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
827     return Icc ->manufacturer;
828 }
829
830 void CMSEXPORT cmsSetHeaderManufacturer(cmsHPROFILE hProfile, cmsUInt32Number manufacturer)
831 {
832     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
833     Icc -> manufacturer = manufacturer;
834 }
835
836 cmsUInt32Number CMSEXPORT cmsGetHeaderCreator(cmsHPROFILE hProfile)
837 {
838     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
839     return Icc ->creator;
840 }
841
842 cmsUInt32Number CMSEXPORT cmsGetHeaderModel(cmsHPROFILE hProfile)
843 {
844     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
845     return Icc ->model;
846 }
847
848 void CMSEXPORT cmsSetHeaderModel(cmsHPROFILE hProfile, cmsUInt32Number model)
849 {
850     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
851     Icc -> model = model;
852 }
853
854 void CMSEXPORT cmsGetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number* Flags)
855 {
856     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
857     memmove(Flags, &Icc -> attributes, sizeof(cmsUInt64Number));
858 }
859
860 void CMSEXPORT cmsSetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number Flags)
861 {
862     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
863     memmove(&Icc -> attributes, &Flags, sizeof(cmsUInt64Number));
864 }
865
866 void CMSEXPORT cmsGetHeaderProfileID(cmsHPROFILE hProfile, cmsUInt8Number* ProfileID)
867 {
868     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
869     memmove(ProfileID, Icc ->ProfileID.ID8, 16);
870 }
871
872 void CMSEXPORT cmsSetHeaderProfileID(cmsHPROFILE hProfile, cmsUInt8Number* ProfileID)
873 {
874     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
875     memmove(&Icc -> ProfileID, ProfileID, 16);
876 }
877
878 cmsBool  CMSEXPORT cmsGetHeaderCreationDateTime(cmsHPROFILE hProfile, struct tm *Dest)
879 {
880     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
881     memmove(Dest, &Icc ->Created, sizeof(struct tm));
882     return TRUE;
883 }
884
885 cmsColorSpaceSignature CMSEXPORT cmsGetPCS(cmsHPROFILE hProfile)
886 {
887     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
888     return Icc -> PCS;
889 }
890
891 void CMSEXPORT cmsSetPCS(cmsHPROFILE hProfile, cmsColorSpaceSignature pcs)
892 {
893     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
894     Icc -> PCS = pcs;
895 }
896
897 cmsColorSpaceSignature CMSEXPORT cmsGetColorSpace(cmsHPROFILE hProfile)
898 {
899     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
900     return Icc -> ColorSpace;
901 }
902
903 void CMSEXPORT cmsSetColorSpace(cmsHPROFILE hProfile, cmsColorSpaceSignature sig)
904 {
905     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
906     Icc -> ColorSpace = sig;
907 }
908
909 cmsProfileClassSignature CMSEXPORT cmsGetDeviceClass(cmsHPROFILE hProfile)
910 {
911     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
912     return Icc -> DeviceClass;
913 }
914
915 void CMSEXPORT cmsSetDeviceClass(cmsHPROFILE hProfile, cmsProfileClassSignature sig)
916 {
917     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
918     Icc -> DeviceClass = sig;
919 }
920
921 cmsUInt32Number CMSEXPORT cmsGetEncodedICCversion(cmsHPROFILE hProfile)
922 {
923     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
924     return Icc -> Version;
925 }
926
927 void CMSEXPORT cmsSetEncodedICCversion(cmsHPROFILE hProfile, cmsUInt32Number Version)
928 {
929     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
930     Icc -> Version = Version;
931 }
932
933 // Get an hexadecimal number with same digits as v
934 static
935 cmsUInt32Number BaseToBase(cmsUInt32Number in, int BaseIn, int BaseOut)
936 {
937     char Buff[100];
938     int i, len;
939     cmsUInt32Number out;
940
941     for (len=0; in > 0 && len < 100; len++) {
942
943         Buff[len] = (char) (in % BaseIn);
944         in /= BaseIn;
945     }
946
947     for (i=len-1, out=0; i >= 0; --i) {
948         out = out * BaseOut + Buff[i];
949     }
950
951     return out;
952 }
953
954 void  CMSEXPORT cmsSetProfileVersion(cmsHPROFILE hProfile, cmsFloat64Number Version)
955 {
956     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
957
958     // 4.2 -> 0x4200000
959
960     Icc -> Version = BaseToBase((cmsUInt32Number) floor(Version * 100.0 + 0.5), 10, 16) << 16;
961 }
962
963 cmsFloat64Number CMSEXPORT cmsGetProfileVersion(cmsHPROFILE hProfile)
964 {
965     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
966     cmsUInt32Number n = Icc -> Version >> 16;
967
968     return BaseToBase(n, 16, 10) / 100.0;
969 }
970 // --------------------------------------------------------------------------------------------------------------
971
972
973 // Create profile from IOhandler
974 cmsHPROFILE CMSEXPORT cmsOpenProfileFromIOhandlerTHR(cmsContext ContextID, cmsIOHANDLER* io)
975 {
976     _cmsICCPROFILE* NewIcc;
977     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
978
979     if (hEmpty == NULL) return NULL;
980
981     NewIcc = (_cmsICCPROFILE*) hEmpty;
982
983     NewIcc ->IOhandler = io;
984     if (!_cmsReadHeader(NewIcc)) goto Error;
985     return hEmpty;
986
987 Error:
988     cmsCloseProfile(hEmpty);
989     return NULL;
990 }
991
992 // Create profile from IOhandler
993 cmsHPROFILE CMSEXPORT cmsOpenProfileFromIOhandler2THR(cmsContext ContextID, cmsIOHANDLER* io, cmsBool write)
994 {
995     _cmsICCPROFILE* NewIcc;
996     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
997
998     if (hEmpty == NULL) return NULL;
999
1000     NewIcc = (_cmsICCPROFILE*) hEmpty;
1001
1002     NewIcc ->IOhandler = io;
1003     if (write) {
1004
1005         NewIcc -> IsWrite = TRUE;
1006         return hEmpty;
1007     }
1008
1009     if (!_cmsReadHeader(NewIcc)) goto Error;
1010     return hEmpty;
1011
1012 Error:
1013     cmsCloseProfile(hEmpty);
1014     return NULL;
1015 }
1016
1017
1018 // Create profile from disk file
1019 cmsHPROFILE CMSEXPORT cmsOpenProfileFromFileTHR(cmsContext ContextID, const char *lpFileName, const char *sAccess)
1020 {
1021     _cmsICCPROFILE* NewIcc;
1022     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
1023
1024     if (hEmpty == NULL) return NULL;
1025
1026     NewIcc = (_cmsICCPROFILE*) hEmpty;
1027
1028     NewIcc ->IOhandler = cmsOpenIOhandlerFromFile(ContextID, lpFileName, sAccess);
1029     if (NewIcc ->IOhandler == NULL) goto Error;
1030
1031     if (*sAccess == 'W' || *sAccess == 'w') {
1032
1033         NewIcc -> IsWrite = TRUE;
1034
1035         return hEmpty;
1036     }
1037
1038     if (!_cmsReadHeader(NewIcc)) goto Error;
1039     return hEmpty;
1040
1041 Error:
1042     cmsCloseProfile(hEmpty);
1043     return NULL;
1044 }
1045
1046
1047 cmsHPROFILE CMSEXPORT cmsOpenProfileFromFile(const char *ICCProfile, const char *sAccess)
1048 {
1049     return cmsOpenProfileFromFileTHR(NULL, ICCProfile, sAccess);
1050 }
1051
1052
1053 cmsHPROFILE  CMSEXPORT cmsOpenProfileFromStreamTHR(cmsContext ContextID, FILE* ICCProfile, const char *sAccess)
1054 {
1055     _cmsICCPROFILE* NewIcc;
1056     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
1057
1058     if (hEmpty == NULL) return NULL;
1059
1060     NewIcc = (_cmsICCPROFILE*) hEmpty;
1061
1062     NewIcc ->IOhandler = cmsOpenIOhandlerFromStream(ContextID, ICCProfile);
1063     if (NewIcc ->IOhandler == NULL) goto Error;
1064
1065     if (*sAccess == 'w') {
1066
1067         NewIcc -> IsWrite = TRUE;
1068         return hEmpty;
1069     }
1070
1071     if (!_cmsReadHeader(NewIcc)) goto Error;
1072     return hEmpty;
1073
1074 Error:
1075     cmsCloseProfile(hEmpty);
1076     return NULL;
1077
1078 }
1079
1080 cmsHPROFILE  CMSEXPORT cmsOpenProfileFromStream(FILE* ICCProfile, const char *sAccess)
1081 {
1082     return cmsOpenProfileFromStreamTHR(NULL, ICCProfile, sAccess);
1083 }
1084
1085
1086 // Open from memory block
1087 cmsHPROFILE CMSEXPORT cmsOpenProfileFromMemTHR(cmsContext ContextID, const void* MemPtr, cmsUInt32Number dwSize)
1088 {
1089     _cmsICCPROFILE* NewIcc;
1090     cmsHPROFILE hEmpty;
1091
1092     hEmpty = cmsCreateProfilePlaceholder(ContextID);
1093     if (hEmpty == NULL) return NULL;
1094
1095     NewIcc = (_cmsICCPROFILE*) hEmpty;
1096
1097     // Ok, in this case const void* is casted to void* just because open IO handler
1098     // shares read and writting modes. Don't abuse this feature!
1099     NewIcc ->IOhandler = cmsOpenIOhandlerFromMem(ContextID, (void*) MemPtr, dwSize, "r");
1100     if (NewIcc ->IOhandler == NULL) goto Error;
1101
1102     if (!_cmsReadHeader(NewIcc)) goto Error;
1103
1104     return hEmpty;
1105
1106 Error:
1107     cmsCloseProfile(hEmpty);
1108     return NULL;
1109 }
1110
1111 cmsHPROFILE CMSEXPORT cmsOpenProfileFromMem(const void* MemPtr, cmsUInt32Number dwSize)
1112 {
1113     return cmsOpenProfileFromMemTHR(NULL, MemPtr, dwSize);
1114 }
1115
1116
1117
1118 // Dump tag contents. If the profile is being modified, untouched tags are copied from FileOrig
1119 static
1120 cmsBool SaveTags(_cmsICCPROFILE* Icc, _cmsICCPROFILE* FileOrig)
1121 {
1122     cmsUInt8Number* Data;
1123     cmsUInt32Number i;
1124     cmsUInt32Number Begin;
1125     cmsIOHANDLER* io = Icc ->IOhandler;
1126     cmsTagDescriptor* TagDescriptor;
1127     cmsTagTypeSignature TypeBase;
1128     cmsTagTypeSignature Type;
1129     cmsTagTypeHandler* TypeHandler;
1130     cmsFloat64Number   Version = cmsGetProfileVersion((cmsHPROFILE) Icc);
1131     cmsTagTypeHandler LocalTypeHandler;
1132
1133     for (i=0; i < Icc -> TagCount; i++) {
1134
1135         if (Icc ->TagNames[i] == 0) continue;
1136
1137         // Linked tags are not written
1138         if (Icc ->TagLinked[i] != (cmsTagSignature) 0) continue;
1139
1140         Icc -> TagOffsets[i] = Begin = io ->UsedSpace;
1141
1142         Data = (cmsUInt8Number*)  Icc -> TagPtrs[i];
1143
1144         if (!Data) {
1145
1146             // Reach here if we are copying a tag from a disk-based ICC profile which has not been modified by user.
1147             // In this case a blind copy of the block data is performed
1148             if (FileOrig != NULL && Icc -> TagOffsets[i]) {
1149
1150                 cmsUInt32Number TagSize   = FileOrig -> TagSizes[i];
1151                 cmsUInt32Number TagOffset = FileOrig -> TagOffsets[i];
1152                 void* Mem;
1153
1154                 if (!FileOrig ->IOhandler->Seek(FileOrig ->IOhandler, TagOffset)) return FALSE;
1155
1156                 Mem = _cmsMalloc(Icc ->ContextID, TagSize);
1157                 if (Mem == NULL) return FALSE;
1158
1159                 if (FileOrig ->IOhandler->Read(FileOrig->IOhandler, Mem, TagSize, 1) != 1) return FALSE;
1160                 if (!io ->Write(io, TagSize, Mem)) return FALSE;
1161                 _cmsFree(Icc ->ContextID, Mem);
1162
1163                 Icc -> TagSizes[i] = (io ->UsedSpace - Begin);
1164
1165
1166                 // Align to 32 bit boundary.
1167                 if (! _cmsWriteAlignment(io))
1168                     return FALSE;
1169             }
1170
1171             continue;
1172         }
1173
1174
1175         // Should this tag be saved as RAW? If so, tagsizes should be specified in advance (no further cooking is done)
1176         if (Icc ->TagSaveAsRaw[i]) {
1177
1178             if (io -> Write(io, Icc ->TagSizes[i], Data) != 1) return FALSE;
1179         }
1180         else {
1181
1182             // Search for support on this tag
1183             TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, Icc -> TagNames[i]);
1184             if (TagDescriptor == NULL) continue;                        // Unsupported, ignore it
1185            
1186             if (TagDescriptor ->DecideType != NULL) {
1187
1188                 Type = TagDescriptor ->DecideType(Version, Data);
1189             }
1190             else {
1191
1192                 Type = TagDescriptor ->SupportedTypes[0];
1193             }
1194
1195             TypeHandler =  _cmsGetTagTypeHandler(Icc->ContextID, Type);
1196
1197             if (TypeHandler == NULL) {
1198                 cmsSignalError(Icc ->ContextID, cmsERROR_INTERNAL, "(Internal) no handler for tag %x", Icc -> TagNames[i]);
1199                 continue;
1200             }
1201
1202             TypeBase = TypeHandler ->Signature;
1203             if (!_cmsWriteTypeBase(io, TypeBase))
1204                 return FALSE;
1205
1206             LocalTypeHandler = *TypeHandler;
1207             LocalTypeHandler.ContextID  = Icc ->ContextID;
1208             LocalTypeHandler.ICCVersion = Icc ->Version;
1209             if (!LocalTypeHandler.WritePtr(&LocalTypeHandler, io, Data, TagDescriptor ->ElemCount)) {
1210
1211                 char String[5];
1212
1213                 _cmsTagSignature2String(String, (cmsTagSignature) TypeBase);
1214                 cmsSignalError(Icc ->ContextID, cmsERROR_WRITE, "Couldn't write type '%s'", String);
1215                 return FALSE;
1216             }
1217         }
1218
1219
1220         Icc -> TagSizes[i] = (io ->UsedSpace - Begin);
1221
1222         // Align to 32 bit boundary.
1223         if (! _cmsWriteAlignment(io))
1224             return FALSE;
1225     }
1226
1227
1228     return TRUE;
1229 }
1230
1231
1232 // Fill the offset and size fields for all linked tags
1233 static
1234 cmsBool SetLinks( _cmsICCPROFILE* Icc)
1235 {
1236     cmsUInt32Number i;
1237
1238     for (i=0; i < Icc -> TagCount; i++) {
1239
1240         cmsTagSignature lnk = Icc ->TagLinked[i];
1241         if (lnk != (cmsTagSignature) 0) {
1242
1243             int j = _cmsSearchTag(Icc, lnk, FALSE);
1244             if (j >= 0) {
1245
1246                 Icc ->TagOffsets[i] = Icc ->TagOffsets[j];
1247                 Icc ->TagSizes[i]   = Icc ->TagSizes[j];
1248             }
1249
1250         }
1251     }
1252
1253     return TRUE;
1254 }
1255
1256 // Low-level save to IOHANDLER. It returns the number of bytes used to
1257 // store the profile, or zero on error. io may be NULL and in this case
1258 // no data is written--only sizes are calculated
1259 cmsUInt32Number CMSEXPORT cmsSaveProfileToIOhandler(cmsHPROFILE hProfile, cmsIOHANDLER* io)
1260 {
1261     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1262     _cmsICCPROFILE Keep;
1263     cmsIOHANDLER* PrevIO = NULL;
1264     cmsUInt32Number UsedSpace;
1265     cmsContext ContextID;
1266
1267     _cmsAssert(hProfile != NULL);
1268
1269     memmove(&Keep, Icc, sizeof(_cmsICCPROFILE));
1270
1271     ContextID = cmsGetProfileContextID(hProfile);
1272     PrevIO = Icc ->IOhandler = cmsOpenIOhandlerFromNULL(ContextID);
1273     if (PrevIO == NULL) return 0;
1274
1275     // Pass #1 does compute offsets
1276
1277     if (!_cmsWriteHeader(Icc, 0)) goto Error;
1278     if (!SaveTags(Icc, &Keep)) goto Error;
1279
1280     UsedSpace = PrevIO ->UsedSpace;
1281
1282     // Pass #2 does save to iohandler
1283
1284     if (io != NULL) {
1285
1286         Icc ->IOhandler = io;
1287         if (!SetLinks(Icc)) goto Error;
1288         if (!_cmsWriteHeader(Icc, UsedSpace)) goto Error;
1289         if (!SaveTags(Icc, &Keep)) goto Error;
1290     }
1291
1292     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
1293     if (!cmsCloseIOhandler(PrevIO)) return 0;
1294
1295     return UsedSpace;
1296
1297
1298 Error:
1299     cmsCloseIOhandler(PrevIO);
1300     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
1301     return 0;
1302 }
1303
1304
1305 // Low-level save to disk.
1306 cmsBool  CMSEXPORT cmsSaveProfileToFile(cmsHPROFILE hProfile, const char* FileName)
1307 {
1308     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1309     cmsIOHANDLER* io = cmsOpenIOhandlerFromFile(ContextID, FileName, "w");
1310     cmsBool rc;
1311
1312     if (io == NULL) return FALSE;
1313
1314     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1315     rc &= cmsCloseIOhandler(io);
1316
1317     if (rc == FALSE) {          // remove() is C99 per 7.19.4.1
1318             remove(FileName);   // We have to IGNORE return value in this case
1319     }
1320     return rc;
1321 }
1322
1323 // Same as anterior, but for streams
1324 cmsBool CMSEXPORT cmsSaveProfileToStream(cmsHPROFILE hProfile, FILE* Stream)
1325 {
1326     cmsBool rc;
1327     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1328     cmsIOHANDLER* io = cmsOpenIOhandlerFromStream(ContextID, Stream);
1329
1330     if (io == NULL) return FALSE;
1331
1332     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1333     rc &= cmsCloseIOhandler(io);
1334
1335     return rc;
1336 }
1337
1338
1339 // Same as anterior, but for memory blocks. In this case, a NULL as MemPtr means calculate needed space only
1340 cmsBool CMSEXPORT cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr, cmsUInt32Number* BytesNeeded)
1341 {
1342     cmsBool rc;
1343     cmsIOHANDLER* io;
1344     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1345
1346     _cmsAssert(BytesNeeded != NULL);
1347
1348     // Should we just calculate the needed space?
1349     if (MemPtr == NULL) {
1350
1351            *BytesNeeded =  cmsSaveProfileToIOhandler(hProfile, NULL);
1352             return (*BytesNeeded == 0) ? FALSE : TRUE;
1353     }
1354
1355     // That is a real write operation
1356     io =  cmsOpenIOhandlerFromMem(ContextID, MemPtr, *BytesNeeded, "w");
1357     if (io == NULL) return FALSE;
1358
1359     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1360     rc &= cmsCloseIOhandler(io);
1361
1362     return rc;
1363 }
1364
1365
1366
1367 // Closes a profile freeing any involved resources
1368 cmsBool  CMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile)
1369 {
1370     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1371     cmsBool  rc = TRUE;
1372     cmsUInt32Number i;
1373
1374     if (!Icc) return FALSE;
1375
1376     // Was open in write mode?
1377     if (Icc ->IsWrite) {
1378
1379         Icc ->IsWrite = FALSE;      // Assure no further writting
1380         rc &= cmsSaveProfileToFile(hProfile, Icc ->IOhandler->PhysicalFile);
1381     }
1382
1383     for (i=0; i < Icc -> TagCount; i++) {
1384
1385         if (Icc -> TagPtrs[i]) {
1386
1387             cmsTagTypeHandler* TypeHandler = Icc ->TagTypeHandlers[i];
1388
1389             if (TypeHandler != NULL) {
1390                 cmsTagTypeHandler LocalTypeHandler = *TypeHandler;
1391
1392                 LocalTypeHandler.ContextID = Icc ->ContextID;              // As an additional parameters
1393                 LocalTypeHandler.ICCVersion = Icc ->Version;
1394                 LocalTypeHandler.FreePtr(&LocalTypeHandler, Icc -> TagPtrs[i]);
1395             }
1396             else
1397                 _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
1398         }
1399     }
1400
1401     if (Icc ->IOhandler != NULL) {
1402         rc &= cmsCloseIOhandler(Icc->IOhandler);
1403     }
1404
1405     _cmsDestroyMutex(Icc->ContextID, Icc->UsrMutex);
1406
1407     _cmsFree(Icc ->ContextID, Icc);   // Free placeholder memory
1408
1409     return rc;
1410 }
1411
1412
1413 // -------------------------------------------------------------------------------------------------------------------
1414
1415
1416 // Returns TRUE if a given tag is supported by a plug-in
1417 static
1418 cmsBool IsTypeSupported(cmsTagDescriptor* TagDescriptor, cmsTagTypeSignature Type)
1419 {
1420     cmsUInt32Number i, nMaxTypes;
1421
1422     nMaxTypes = TagDescriptor->nSupportedTypes;
1423     if (nMaxTypes >= MAX_TYPES_IN_LCMS_PLUGIN)
1424         nMaxTypes = MAX_TYPES_IN_LCMS_PLUGIN;
1425
1426     for (i=0; i < nMaxTypes; i++) {
1427         if (Type == TagDescriptor ->SupportedTypes[i]) return TRUE;
1428     }
1429
1430     return FALSE;
1431 }
1432
1433
1434 // That's the main read function
1435 void* CMSEXPORT cmsReadTag(cmsHPROFILE hProfile, cmsTagSignature sig)
1436 {
1437     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1438     cmsIOHANDLER* io = Icc ->IOhandler;
1439     cmsTagTypeHandler* TypeHandler;
1440     cmsTagTypeHandler LocalTypeHandler;
1441     cmsTagDescriptor*  TagDescriptor;
1442     cmsTagTypeSignature BaseType;
1443     cmsUInt32Number Offset, TagSize;
1444     cmsUInt32Number ElemCount;
1445     int n;
1446
1447     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return NULL;
1448
1449     n = _cmsSearchTag(Icc, sig, TRUE);
1450     if (n < 0) goto Error;               // Not found, return NULL
1451
1452
1453     // If the element is already in memory, return the pointer
1454     if (Icc -> TagPtrs[n]) {
1455
1456         if (Icc ->TagSaveAsRaw[n]) goto Error;  // We don't support read raw tags as cooked
1457
1458         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1459         return Icc -> TagPtrs[n];
1460     }
1461
1462     // We need to read it. Get the offset and size to the file
1463     Offset    = Icc -> TagOffsets[n];
1464     TagSize   = Icc -> TagSizes[n];
1465
1466     // Seek to its location
1467     if (!io -> Seek(io, Offset))
1468         goto Error;
1469
1470     // Search for support on this tag
1471     TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
1472     if (TagDescriptor == NULL) {
1473
1474         char String[5];
1475
1476         _cmsTagSignature2String(String, sig);
1477
1478         // An unknown element was found.
1479         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown tag type '%s' found.", String);
1480         goto Error;     // Unsupported.
1481     }
1482
1483     // if supported, get type and check if in list
1484     BaseType = _cmsReadTypeBase(io);
1485     if (BaseType == 0) goto Error;
1486
1487     if (!IsTypeSupported(TagDescriptor, BaseType)) goto Error;
1488
1489     TagSize  -= 8;                      // Alredy read by the type base logic
1490
1491     // Get type handler
1492     TypeHandler = _cmsGetTagTypeHandler(Icc ->ContextID, BaseType);
1493     if (TypeHandler == NULL) goto Error;
1494     LocalTypeHandler = *TypeHandler;
1495
1496
1497     // Read the tag
1498     Icc -> TagTypeHandlers[n] = TypeHandler;
1499
1500     LocalTypeHandler.ContextID = Icc ->ContextID;
1501     LocalTypeHandler.ICCVersion = Icc ->Version;
1502     Icc -> TagPtrs[n] = LocalTypeHandler.ReadPtr(&LocalTypeHandler, io, &ElemCount, TagSize);
1503
1504     // The tag type is supported, but something wrong happend and we cannot read the tag.
1505     // let know the user about this (although it is just a warning)
1506     if (Icc -> TagPtrs[n] == NULL) {
1507
1508         char String[5];
1509
1510         _cmsTagSignature2String(String, sig);
1511         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "Corrupted tag '%s'", String);
1512         goto Error;
1513     }
1514
1515     // This is a weird error that may be a symptom of something more serious, the number of
1516     // stored item is actually less than the number of required elements.
1517     if (ElemCount < TagDescriptor ->ElemCount) {
1518
1519         char String[5];
1520
1521         _cmsTagSignature2String(String, sig);
1522         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "'%s' Inconsistent number of items: expected %d, got %d",
1523             String, TagDescriptor ->ElemCount, ElemCount);
1524     }
1525
1526
1527     // Return the data
1528     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1529     return Icc -> TagPtrs[n];
1530
1531
1532     // Return error and unlock tha data
1533 Error:
1534     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1535     return NULL;
1536 }
1537
1538
1539 // Get true type of data
1540 cmsTagTypeSignature _cmsGetTagTrueType(cmsHPROFILE hProfile, cmsTagSignature sig)
1541 {
1542     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1543     cmsTagTypeHandler* TypeHandler;
1544     int n;
1545
1546     // Search for given tag in ICC profile directory
1547     n = _cmsSearchTag(Icc, sig, TRUE);
1548     if (n < 0) return (cmsTagTypeSignature) 0;                // Not found, return NULL
1549
1550     // Get the handler. The true type is there
1551     TypeHandler =  Icc -> TagTypeHandlers[n];
1552     return TypeHandler ->Signature;
1553 }
1554
1555
1556 // Write a single tag. This just keeps track of the tak into a list of "to be written". If the tag is already
1557 // in that list, the previous version is deleted.
1558 cmsBool CMSEXPORT cmsWriteTag(cmsHPROFILE hProfile, cmsTagSignature sig, const void* data)
1559 {
1560     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1561     cmsTagTypeHandler* TypeHandler = NULL;
1562     cmsTagTypeHandler LocalTypeHandler;
1563     cmsTagDescriptor* TagDescriptor = NULL;
1564     cmsTagTypeSignature Type;
1565     int i;
1566     cmsFloat64Number Version;
1567     char TypeString[5], SigString[5];
1568
1569     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return FALSE;
1570
1571     // To delete tags.
1572     if (data == NULL) {
1573
1574          // Delete the tag
1575          i = _cmsSearchTag(Icc, sig, FALSE);
1576          if (i >= 0) {
1577                 
1578              // Use zero as a mark of deleted 
1579              _cmsDeleteTagByPos(Icc, i);
1580              Icc ->TagNames[i] = (cmsTagSignature) 0;
1581              _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1582              return TRUE;
1583          }
1584          // Didn't find the tag
1585         goto Error;
1586     }
1587
1588     if (!_cmsNewTag(Icc, sig, &i)) goto Error;
1589
1590     // This is not raw
1591     Icc ->TagSaveAsRaw[i] = FALSE;
1592
1593     // This is not a link
1594     Icc ->TagLinked[i] = (cmsTagSignature) 0;
1595
1596     // Get information about the TAG.
1597     TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
1598     if (TagDescriptor == NULL){
1599          cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported tag '%x'", sig);
1600         goto Error;
1601     }
1602
1603
1604     // Now we need to know which type to use. It depends on the version.
1605     Version = cmsGetProfileVersion(hProfile);
1606
1607     if (TagDescriptor ->DecideType != NULL) {
1608
1609         // Let the tag descriptor to decide the type base on depending on
1610         // the data. This is useful for example on parametric curves, where
1611         // curves specified by a table cannot be saved as parametric and needs
1612         // to be casted to single v2-curves, even on v4 profiles.
1613
1614         Type = TagDescriptor ->DecideType(Version, data);
1615     }
1616     else {
1617
1618         Type = TagDescriptor ->SupportedTypes[0];
1619     }
1620
1621     // Does the tag support this type?
1622     if (!IsTypeSupported(TagDescriptor, Type)) {
1623
1624         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1625         _cmsTagSignature2String(SigString,  sig);
1626
1627         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported type '%s' for tag '%s'", TypeString, SigString);
1628         goto Error;
1629     }
1630
1631     // Does we have a handler for this type?
1632     TypeHandler =  _cmsGetTagTypeHandler(Icc->ContextID, Type);
1633     if (TypeHandler == NULL) {
1634
1635         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1636         _cmsTagSignature2String(SigString,  sig);
1637
1638         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported type '%s' for tag '%s'", TypeString, SigString);
1639         goto Error;           // Should never happen
1640     }
1641
1642
1643     // Fill fields on icc structure
1644     Icc ->TagTypeHandlers[i]  = TypeHandler;
1645     Icc ->TagNames[i]         = sig;
1646     Icc ->TagSizes[i]         = 0;
1647     Icc ->TagOffsets[i]       = 0;
1648
1649     LocalTypeHandler = *TypeHandler;
1650     LocalTypeHandler.ContextID  = Icc ->ContextID;
1651     LocalTypeHandler.ICCVersion = Icc ->Version;
1652     Icc ->TagPtrs[i]            = LocalTypeHandler.DupPtr(&LocalTypeHandler, data, TagDescriptor ->ElemCount);
1653
1654     if (Icc ->TagPtrs[i] == NULL)  {
1655
1656         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1657         _cmsTagSignature2String(SigString,  sig);
1658         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "Malformed struct in type '%s' for tag '%s'", TypeString, SigString);
1659
1660         goto Error;
1661     }
1662
1663     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1664     return TRUE;
1665
1666 Error:
1667     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1668     return FALSE;
1669
1670 }
1671
1672 // Read and write raw data. The only way those function would work and keep consistence with normal read and write
1673 // is to do an additional step of serialization. That means, readRaw would issue a normal read and then convert the obtained
1674 // data to raw bytes by using the "write" serialization logic. And vice-versa. I know this may end in situations where
1675 // raw data written does not exactly correspond with the raw data proposed to cmsWriteRaw data, but this approach allows
1676 // to write a tag as raw data and the read it as handled.
1677
1678 cmsInt32Number CMSEXPORT cmsReadRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, void* data, cmsUInt32Number BufferSize)
1679 {
1680     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1681     void *Object;
1682     int i;
1683     cmsIOHANDLER* MemIO;
1684     cmsTagTypeHandler* TypeHandler = NULL;
1685     cmsTagTypeHandler LocalTypeHandler;
1686     cmsTagDescriptor* TagDescriptor = NULL;
1687     cmsUInt32Number rc;
1688     cmsUInt32Number Offset, TagSize;
1689
1690     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
1691
1692     // Search for given tag in ICC profile directory
1693     i = _cmsSearchTag(Icc, sig, TRUE);
1694     if (i < 0) goto Error;                 // Not found, 
1695
1696     // It is already read?
1697     if (Icc -> TagPtrs[i] == NULL) {
1698
1699         // No yet, get original position
1700         Offset   = Icc ->TagOffsets[i];
1701         TagSize  = Icc ->TagSizes[i];
1702
1703         // read the data directly, don't keep copy
1704         if (data != NULL) {
1705
1706             if (BufferSize < TagSize)
1707                 TagSize = BufferSize;
1708
1709             if (!Icc ->IOhandler ->Seek(Icc ->IOhandler, Offset)) goto Error;
1710             if (!Icc ->IOhandler ->Read(Icc ->IOhandler, data, 1, TagSize)) goto Error;
1711
1712             _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1713             return TagSize;
1714         }
1715
1716         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1717         return Icc ->TagSizes[i];
1718     }
1719
1720     // The data has been already read, or written. But wait!, maybe the user choosed to save as
1721     // raw data. In this case, return the raw data directly
1722     if (Icc ->TagSaveAsRaw[i]) {
1723
1724         if (data != NULL)  {
1725
1726             TagSize  = Icc ->TagSizes[i];
1727             if (BufferSize < TagSize)
1728                 TagSize = BufferSize;
1729
1730             memmove(data, Icc ->TagPtrs[i], TagSize);
1731
1732             _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1733             return TagSize;
1734         }
1735
1736         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1737         return Icc ->TagSizes[i];
1738     }
1739
1740     // Already readed, or previously set by cmsWriteTag(). We need to serialize that
1741     // data to raw in order to maintain consistency.
1742
1743     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1744     Object = cmsReadTag(hProfile, sig);
1745     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
1746
1747     if (Object == NULL) goto Error;
1748
1749     // Now we need to serialize to a memory block: just use a memory iohandler
1750
1751     if (data == NULL) {
1752         MemIO = cmsOpenIOhandlerFromNULL(cmsGetProfileContextID(hProfile));
1753     } else{
1754         MemIO = cmsOpenIOhandlerFromMem(cmsGetProfileContextID(hProfile), data, BufferSize, "w");
1755     }
1756     if (MemIO == NULL) goto Error;
1757
1758     // Obtain type handling for the tag
1759     TypeHandler = Icc ->TagTypeHandlers[i];
1760     TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
1761     if (TagDescriptor == NULL) {
1762         cmsCloseIOhandler(MemIO);
1763         goto Error;
1764     }
1765     
1766     if (TypeHandler == NULL) goto Error;
1767
1768     // Serialize
1769     LocalTypeHandler = *TypeHandler;
1770     LocalTypeHandler.ContextID  = Icc ->ContextID;
1771     LocalTypeHandler.ICCVersion = Icc ->Version;
1772
1773     if (!_cmsWriteTypeBase(MemIO, TypeHandler ->Signature)) {
1774         cmsCloseIOhandler(MemIO);
1775         goto Error;
1776     }
1777
1778     if (!LocalTypeHandler.WritePtr(&LocalTypeHandler, MemIO, Object, TagDescriptor ->ElemCount)) {
1779         cmsCloseIOhandler(MemIO);
1780         goto Error;
1781     }
1782
1783     // Get Size and close
1784     rc = MemIO ->Tell(MemIO);
1785     cmsCloseIOhandler(MemIO);      // Ignore return code this time
1786
1787     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1788     return rc;
1789
1790 Error:
1791     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1792     return 0;
1793 }
1794
1795 // Similar to the anterior. This function allows to write directly to the ICC profile any data, without
1796 // checking anything. As a rule, mixing Raw with cooked doesn't work, so writting a tag as raw and then reading
1797 // it as cooked without serializing does result into an error. If that is wha you want, you will need to dump
1798 // the profile to memry or disk and then reopen it.
1799 cmsBool CMSEXPORT cmsWriteRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, const void* data, cmsUInt32Number Size)
1800 {
1801     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1802     int i;
1803
1804     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
1805
1806     if (!_cmsNewTag(Icc, sig, &i)) {
1807         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1808          return FALSE;
1809     }
1810
1811     // Mark the tag as being written as RAW
1812     Icc ->TagSaveAsRaw[i] = TRUE;
1813     Icc ->TagNames[i]     = sig;
1814     Icc ->TagLinked[i]    = (cmsTagSignature) 0;
1815
1816     // Keep a copy of the block
1817     Icc ->TagPtrs[i]  = _cmsDupMem(Icc ->ContextID, data, Size);
1818     Icc ->TagSizes[i] = Size;
1819
1820     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1821     return TRUE;
1822 }
1823
1824 // Using this function you can collapse several tag entries to the same block in the profile
1825 cmsBool CMSEXPORT cmsLinkTag(cmsHPROFILE hProfile, cmsTagSignature sig, cmsTagSignature dest)
1826 {
1827     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1828     int i;
1829
1830      if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return FALSE;
1831
1832     if (!_cmsNewTag(Icc, sig, &i)) {
1833         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1834         return FALSE;
1835     }
1836
1837     // Keep necessary information
1838     Icc ->TagSaveAsRaw[i] = FALSE;
1839     Icc ->TagNames[i]     = sig;
1840     Icc ->TagLinked[i]    = dest;
1841
1842     Icc ->TagPtrs[i]    = NULL;
1843     Icc ->TagSizes[i]   = 0;
1844     Icc ->TagOffsets[i] = 0;
1845
1846     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1847     return TRUE;
1848 }
1849
1850
1851 // Returns the tag linked to sig, in the case two tags are sharing same resource
1852 cmsTagSignature  CMSEXPORT cmsTagLinkedTo(cmsHPROFILE hProfile, cmsTagSignature sig)
1853 {
1854     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1855     int i;
1856
1857     // Search for given tag in ICC profile directory
1858     i = _cmsSearchTag(Icc, sig, FALSE);
1859     if (i < 0) return (cmsTagSignature) 0;                 // Not found, return 0
1860
1861     return Icc -> TagLinked[i];
1862 }