Update lcms (#544)
[openjpeg.git] / thirdparty / liblcms2 / src / cmsio0.c
1 //---------------------------------------------------------------------------------
2 //
3 //  Little Color Management System
4 //  Copyright (c) 1998-2016 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 cmsIOHANDLER* CMSEXPORT cmsGetProfileIOhandler(cmsHPROFILE hProfile)
457 {
458         _cmsICCPROFILE* Icc = (_cmsICCPROFILE*)hProfile;
459
460         if (Icc == NULL) return NULL;
461         return Icc->IOhandler;
462 }
463
464 // Creates an empty structure holding all required parameters
465 cmsHPROFILE CMSEXPORT cmsCreateProfilePlaceholder(cmsContext ContextID)
466 {
467     time_t now = time(NULL);
468     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) _cmsMallocZero(ContextID, sizeof(_cmsICCPROFILE));
469     if (Icc == NULL) return NULL;
470
471     Icc ->ContextID = ContextID;
472
473     // Set it to empty
474     Icc -> TagCount   = 0;
475
476     // Set default version
477     Icc ->Version =  0x02100000;
478
479     // Set creation date/time
480     memmove(&Icc ->Created, gmtime(&now), sizeof(Icc ->Created));
481
482     // Create a mutex if the user provided proper plugin. NULL otherwise
483     Icc ->UsrMutex = _cmsCreateMutex(ContextID);
484
485     // Return the handle
486     return (cmsHPROFILE) Icc;
487 }
488
489 cmsContext CMSEXPORT cmsGetProfileContextID(cmsHPROFILE hProfile)
490 {
491      _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
492
493     if (Icc == NULL) return NULL;
494     return Icc -> ContextID;
495 }
496
497
498 // Return the number of tags
499 cmsInt32Number CMSEXPORT cmsGetTagCount(cmsHPROFILE hProfile)
500 {
501     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
502     if (Icc == NULL) return -1;
503
504     return  Icc->TagCount;
505 }
506
507 // Return the tag signature of a given tag number
508 cmsTagSignature CMSEXPORT cmsGetTagSignature(cmsHPROFILE hProfile, cmsUInt32Number n)
509 {
510     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
511
512     if (n > Icc->TagCount) return (cmsTagSignature) 0;  // Mark as not available
513     if (n >= MAX_TABLE_TAG) return (cmsTagSignature) 0; // As double check
514
515     return Icc ->TagNames[n];
516 }
517
518
519 static
520 int SearchOneTag(_cmsICCPROFILE* Profile, cmsTagSignature sig)
521 {
522     cmsUInt32Number i;
523
524     for (i=0; i < Profile -> TagCount; i++) {
525
526         if (sig == Profile -> TagNames[i])
527             return i;
528     }
529
530     return -1;
531 }
532
533 // Search for a specific tag in tag dictionary. Returns position or -1 if tag not found.
534 // If followlinks is turned on, then the position of the linked tag is returned
535 int _cmsSearchTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, cmsBool lFollowLinks)
536 {
537     int n;
538     cmsTagSignature LinkedSig;
539
540     do {
541
542         // Search for given tag in ICC profile directory
543         n = SearchOneTag(Icc, sig);
544         if (n < 0)
545             return -1;        // Not found
546
547         if (!lFollowLinks)
548             return n;         // Found, don't follow links
549
550         // Is this a linked tag?
551         LinkedSig = Icc ->TagLinked[n];
552
553         // Yes, follow link
554         if (LinkedSig != (cmsTagSignature) 0) {
555             sig = LinkedSig;
556         }
557
558     } while (LinkedSig != (cmsTagSignature) 0);
559
560     return n;
561 }
562
563 // Deletes a tag entry
564
565 static
566 void _cmsDeleteTagByPos(_cmsICCPROFILE* Icc, int i)
567 {
568     _cmsAssert(Icc != NULL);
569     _cmsAssert(i >= 0);
570
571    
572     if (Icc -> TagPtrs[i] != NULL) {
573
574         // Free previous version
575         if (Icc ->TagSaveAsRaw[i]) {
576             _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
577         }
578         else {
579             cmsTagTypeHandler* TypeHandler = Icc ->TagTypeHandlers[i];
580
581             if (TypeHandler != NULL) {
582
583                 cmsTagTypeHandler LocalTypeHandler = *TypeHandler;
584                 LocalTypeHandler.ContextID = Icc ->ContextID;              // As an additional parameter
585                 LocalTypeHandler.ICCVersion = Icc ->Version;
586                 LocalTypeHandler.FreePtr(&LocalTypeHandler, Icc -> TagPtrs[i]);
587                 Icc ->TagPtrs[i] = NULL;
588             }
589         }
590
591     } 
592 }
593
594
595 // Creates a new tag entry
596 static
597 cmsBool _cmsNewTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, int* NewPos)
598 {
599     int i;
600
601     // Search for the tag
602     i = _cmsSearchTag(Icc, sig, FALSE);
603     if (i >= 0) {
604
605         // Already exists? delete it
606         _cmsDeleteTagByPos(Icc, i);
607         *NewPos = i;
608     }
609     else  {
610
611         // No, make a new one
612
613         if (Icc -> TagCount >= MAX_TABLE_TAG) {
614             cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", MAX_TABLE_TAG);
615             return FALSE;
616         }
617
618         *NewPos = Icc ->TagCount;
619         Icc -> TagCount++;
620     }
621
622     return TRUE;
623 }
624
625
626 // Check existance
627 cmsBool CMSEXPORT cmsIsTag(cmsHPROFILE hProfile, cmsTagSignature sig)
628 {
629        _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) (void*) hProfile;
630        return _cmsSearchTag(Icc, sig, FALSE) >= 0;
631 }
632
633
634
635 // Enforces that the profile version is per. spec.
636 // Operates on the big endian bytes from the profile.
637 // Called before converting to platform endianness.
638 // Byte 0 is BCD major version, so max 9.
639 // Byte 1 is 2 BCD digits, one per nibble.
640 // Reserved bytes 2 & 3 must be 0.
641 static 
642 cmsUInt32Number _validatedVersion(cmsUInt32Number DWord)
643 {
644     cmsUInt8Number* pByte = (cmsUInt8Number*) &DWord;
645     cmsUInt8Number temp1;
646     cmsUInt8Number temp2;
647
648     if (*pByte > 0x09) *pByte = (cmsUInt8Number) 0x09;
649     temp1 = *(pByte+1) & 0xf0;
650     temp2 = *(pByte+1) & 0x0f;
651     if (temp1 > 0x90) temp1 = 0x90;
652     if (temp2 > 0x09) temp2 = 0x09;
653     *(pByte+1) = (cmsUInt8Number)(temp1 | temp2);
654     *(pByte+2) = (cmsUInt8Number)0;
655     *(pByte+3) = (cmsUInt8Number)0;
656
657     return DWord;
658 }
659
660 // Read profile header and validate it
661 cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
662 {
663     cmsTagEntry Tag;
664     cmsICCHeader Header;
665     cmsUInt32Number i, j;
666     cmsUInt32Number HeaderSize;
667     cmsIOHANDLER* io = Icc ->IOhandler;
668     cmsUInt32Number TagCount;
669
670
671     // Read the header
672     if (io -> Read(io, &Header, sizeof(cmsICCHeader), 1) != 1) {
673         return FALSE;
674     }
675
676     // Validate file as an ICC profile
677     if (_cmsAdjustEndianess32(Header.magic) != cmsMagicNumber) {
678         cmsSignalError(Icc ->ContextID, cmsERROR_BAD_SIGNATURE, "not an ICC profile, invalid signature");
679         return FALSE;
680     }
681
682     // Adjust endianess of the used parameters
683     Icc -> DeviceClass     = (cmsProfileClassSignature) _cmsAdjustEndianess32(Header.deviceClass);
684     Icc -> ColorSpace      = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.colorSpace);
685     Icc -> PCS             = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.pcs);
686    
687     Icc -> RenderingIntent = _cmsAdjustEndianess32(Header.renderingIntent);
688     Icc -> flags           = _cmsAdjustEndianess32(Header.flags);
689     Icc -> manufacturer    = _cmsAdjustEndianess32(Header.manufacturer);
690     Icc -> model           = _cmsAdjustEndianess32(Header.model);
691     Icc -> creator         = _cmsAdjustEndianess32(Header.creator);
692     
693     _cmsAdjustEndianess64(&Icc -> attributes, &Header.attributes);
694     Icc -> Version         = _cmsAdjustEndianess32(_validatedVersion(Header.version));
695
696     // Get size as reported in header
697     HeaderSize = _cmsAdjustEndianess32(Header.size);
698
699     // Make sure HeaderSize is lower than profile size
700     if (HeaderSize >= Icc ->IOhandler ->ReportedSize)
701             HeaderSize = Icc ->IOhandler ->ReportedSize;
702
703
704     // Get creation date/time
705     _cmsDecodeDateTimeNumber(&Header.date, &Icc ->Created);
706
707     // The profile ID are 32 raw bytes
708     memmove(Icc ->ProfileID.ID32, Header.profileID.ID32, 16);
709
710
711     // Read tag directory
712     if (!_cmsReadUInt32Number(io, &TagCount)) return FALSE;
713     if (TagCount > MAX_TABLE_TAG) {
714
715         cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", TagCount);
716         return FALSE;
717     }
718
719
720     // Read tag directory
721     Icc -> TagCount = 0;
722     for (i=0; i < TagCount; i++) {
723
724         if (!_cmsReadUInt32Number(io, (cmsUInt32Number *) &Tag.sig)) return FALSE;
725         if (!_cmsReadUInt32Number(io, &Tag.offset)) return FALSE;
726         if (!_cmsReadUInt32Number(io, &Tag.size)) return FALSE;
727
728         // Perform some sanity check. Offset + size should fall inside file.
729         if (Tag.offset + Tag.size > HeaderSize ||
730             Tag.offset + Tag.size < Tag.offset)
731                   continue;
732
733         Icc -> TagNames[Icc ->TagCount]   = Tag.sig;
734         Icc -> TagOffsets[Icc ->TagCount] = Tag.offset;
735         Icc -> TagSizes[Icc ->TagCount]   = Tag.size;
736
737        // Search for links
738         for (j=0; j < Icc ->TagCount; j++) {
739
740             if ((Icc ->TagOffsets[j] == Tag.offset) &&
741                 (Icc ->TagSizes[j]   == Tag.size)) {
742
743                 Icc ->TagLinked[Icc ->TagCount] = Icc ->TagNames[j];
744             }
745
746         }
747
748         Icc ->TagCount++;
749     }
750
751     return TRUE;
752 }
753
754 // Saves profile header
755 cmsBool _cmsWriteHeader(_cmsICCPROFILE* Icc, cmsUInt32Number UsedSpace)
756 {
757     cmsICCHeader Header;
758     cmsUInt32Number i;
759     cmsTagEntry Tag;
760     cmsInt32Number Count = 0;
761
762     Header.size        = _cmsAdjustEndianess32(UsedSpace);
763     Header.cmmId       = _cmsAdjustEndianess32(lcmsSignature);
764     Header.version     = _cmsAdjustEndianess32(Icc ->Version);
765
766     Header.deviceClass = (cmsProfileClassSignature) _cmsAdjustEndianess32(Icc -> DeviceClass);
767     Header.colorSpace  = (cmsColorSpaceSignature) _cmsAdjustEndianess32(Icc -> ColorSpace);
768     Header.pcs         = (cmsColorSpaceSignature) _cmsAdjustEndianess32(Icc -> PCS);
769
770     //   NOTE: in v4 Timestamp must be in UTC rather than in local time
771     _cmsEncodeDateTimeNumber(&Header.date, &Icc ->Created);
772
773     Header.magic       = _cmsAdjustEndianess32(cmsMagicNumber);
774
775 #ifdef CMS_IS_WINDOWS_
776     Header.platform    = (cmsPlatformSignature) _cmsAdjustEndianess32(cmsSigMicrosoft);
777 #else
778     Header.platform    = (cmsPlatformSignature) _cmsAdjustEndianess32(cmsSigMacintosh);
779 #endif
780
781     Header.flags        = _cmsAdjustEndianess32(Icc -> flags);
782     Header.manufacturer = _cmsAdjustEndianess32(Icc -> manufacturer);
783     Header.model        = _cmsAdjustEndianess32(Icc -> model);
784
785     _cmsAdjustEndianess64(&Header.attributes, &Icc -> attributes);
786
787     // Rendering intent in the header (for embedded profiles)
788     Header.renderingIntent = _cmsAdjustEndianess32(Icc -> RenderingIntent);
789
790     // Illuminant is always D50
791     Header.illuminant.X = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(cmsD50_XYZ()->X));
792     Header.illuminant.Y = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(cmsD50_XYZ()->Y));
793     Header.illuminant.Z = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(cmsD50_XYZ()->Z));
794
795     // Created by LittleCMS (that's me!)
796     Header.creator      = _cmsAdjustEndianess32(lcmsSignature);
797
798     memset(&Header.reserved, 0, sizeof(Header.reserved));
799
800     // Set profile ID. Endianess is always big endian
801     memmove(&Header.profileID, &Icc ->ProfileID, 16);
802
803     // Dump the header
804     if (!Icc -> IOhandler->Write(Icc->IOhandler, sizeof(cmsICCHeader), &Header)) return FALSE;
805
806     // Saves Tag directory
807
808     // Get true count
809     for (i=0;  i < Icc -> TagCount; i++) {
810         if (Icc ->TagNames[i] != (cmsTagSignature) 0)
811             Count++;
812     }
813
814     // Store number of tags
815     if (!_cmsWriteUInt32Number(Icc ->IOhandler, Count)) return FALSE;
816
817     for (i=0; i < Icc -> TagCount; i++) {
818
819         if (Icc ->TagNames[i] == (cmsTagSignature) 0) continue;   // It is just a placeholder
820
821         Tag.sig    = (cmsTagSignature) _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagNames[i]);
822         Tag.offset = _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagOffsets[i]);
823         Tag.size   = _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagSizes[i]);
824
825         if (!Icc ->IOhandler -> Write(Icc-> IOhandler, sizeof(cmsTagEntry), &Tag)) return FALSE;
826     }
827
828     return TRUE;
829 }
830
831 // ----------------------------------------------------------------------- Set/Get several struct members
832
833
834 cmsUInt32Number CMSEXPORT cmsGetHeaderRenderingIntent(cmsHPROFILE hProfile)
835 {
836     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
837     return Icc -> RenderingIntent;
838 }
839
840 void CMSEXPORT cmsSetHeaderRenderingIntent(cmsHPROFILE hProfile, cmsUInt32Number RenderingIntent)
841 {
842     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
843     Icc -> RenderingIntent = RenderingIntent;
844 }
845
846 cmsUInt32Number CMSEXPORT cmsGetHeaderFlags(cmsHPROFILE hProfile)
847 {
848     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
849     return (cmsUInt32Number) Icc -> flags;
850 }
851
852 void CMSEXPORT cmsSetHeaderFlags(cmsHPROFILE hProfile, cmsUInt32Number Flags)
853 {
854     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
855     Icc -> flags = (cmsUInt32Number) Flags;
856 }
857
858 cmsUInt32Number CMSEXPORT cmsGetHeaderManufacturer(cmsHPROFILE hProfile)
859 {
860     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
861     return Icc ->manufacturer;
862 }
863
864 void CMSEXPORT cmsSetHeaderManufacturer(cmsHPROFILE hProfile, cmsUInt32Number manufacturer)
865 {
866     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
867     Icc -> manufacturer = manufacturer;
868 }
869
870 cmsUInt32Number CMSEXPORT cmsGetHeaderCreator(cmsHPROFILE hProfile)
871 {
872     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
873     return Icc ->creator;
874 }
875
876 cmsUInt32Number CMSEXPORT cmsGetHeaderModel(cmsHPROFILE hProfile)
877 {
878     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
879     return Icc ->model;
880 }
881
882 void CMSEXPORT cmsSetHeaderModel(cmsHPROFILE hProfile, cmsUInt32Number model)
883 {
884     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
885     Icc -> model = model;
886 }
887
888 void CMSEXPORT cmsGetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number* Flags)
889 {
890     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
891     memmove(Flags, &Icc -> attributes, sizeof(cmsUInt64Number));
892 }
893
894 void CMSEXPORT cmsSetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number Flags)
895 {
896     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
897     memmove(&Icc -> attributes, &Flags, sizeof(cmsUInt64Number));
898 }
899
900 void CMSEXPORT cmsGetHeaderProfileID(cmsHPROFILE hProfile, cmsUInt8Number* ProfileID)
901 {
902     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
903     memmove(ProfileID, Icc ->ProfileID.ID8, 16);
904 }
905
906 void CMSEXPORT cmsSetHeaderProfileID(cmsHPROFILE hProfile, cmsUInt8Number* ProfileID)
907 {
908     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
909     memmove(&Icc -> ProfileID, ProfileID, 16);
910 }
911
912 cmsBool  CMSEXPORT cmsGetHeaderCreationDateTime(cmsHPROFILE hProfile, struct tm *Dest)
913 {
914     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
915     memmove(Dest, &Icc ->Created, sizeof(struct tm));
916     return TRUE;
917 }
918
919 cmsColorSpaceSignature CMSEXPORT cmsGetPCS(cmsHPROFILE hProfile)
920 {
921     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
922     return Icc -> PCS;
923 }
924
925 void CMSEXPORT cmsSetPCS(cmsHPROFILE hProfile, cmsColorSpaceSignature pcs)
926 {
927     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
928     Icc -> PCS = pcs;
929 }
930
931 cmsColorSpaceSignature CMSEXPORT cmsGetColorSpace(cmsHPROFILE hProfile)
932 {
933     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
934     return Icc -> ColorSpace;
935 }
936
937 void CMSEXPORT cmsSetColorSpace(cmsHPROFILE hProfile, cmsColorSpaceSignature sig)
938 {
939     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
940     Icc -> ColorSpace = sig;
941 }
942
943 cmsProfileClassSignature CMSEXPORT cmsGetDeviceClass(cmsHPROFILE hProfile)
944 {
945     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
946     return Icc -> DeviceClass;
947 }
948
949 void CMSEXPORT cmsSetDeviceClass(cmsHPROFILE hProfile, cmsProfileClassSignature sig)
950 {
951     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
952     Icc -> DeviceClass = sig;
953 }
954
955 cmsUInt32Number CMSEXPORT cmsGetEncodedICCversion(cmsHPROFILE hProfile)
956 {
957     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
958     return Icc -> Version;
959 }
960
961 void CMSEXPORT cmsSetEncodedICCversion(cmsHPROFILE hProfile, cmsUInt32Number Version)
962 {
963     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
964     Icc -> Version = Version;
965 }
966
967 // Get an hexadecimal number with same digits as v
968 static
969 cmsUInt32Number BaseToBase(cmsUInt32Number in, int BaseIn, int BaseOut)
970 {
971     char Buff[100];
972     int i, len;
973     cmsUInt32Number out;
974
975     for (len=0; in > 0 && len < 100; len++) {
976
977         Buff[len] = (char) (in % BaseIn);
978         in /= BaseIn;
979     }
980
981     for (i=len-1, out=0; i >= 0; --i) {
982         out = out * BaseOut + Buff[i];
983     }
984
985     return out;
986 }
987
988 void  CMSEXPORT cmsSetProfileVersion(cmsHPROFILE hProfile, cmsFloat64Number Version)
989 {
990     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
991
992     // 4.2 -> 0x4200000
993
994     Icc -> Version = BaseToBase((cmsUInt32Number) floor(Version * 100.0 + 0.5), 10, 16) << 16;
995 }
996
997 cmsFloat64Number CMSEXPORT cmsGetProfileVersion(cmsHPROFILE hProfile)
998 {
999     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
1000     cmsUInt32Number n = Icc -> Version >> 16;
1001
1002     return BaseToBase(n, 16, 10) / 100.0;
1003 }
1004 // --------------------------------------------------------------------------------------------------------------
1005
1006
1007 // Create profile from IOhandler
1008 cmsHPROFILE CMSEXPORT cmsOpenProfileFromIOhandlerTHR(cmsContext ContextID, cmsIOHANDLER* io)
1009 {
1010     _cmsICCPROFILE* NewIcc;
1011     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
1012
1013     if (hEmpty == NULL) return NULL;
1014
1015     NewIcc = (_cmsICCPROFILE*) hEmpty;
1016
1017     NewIcc ->IOhandler = io;
1018     if (!_cmsReadHeader(NewIcc)) goto Error;
1019     return hEmpty;
1020
1021 Error:
1022     cmsCloseProfile(hEmpty);
1023     return NULL;
1024 }
1025
1026 // Create profile from IOhandler
1027 cmsHPROFILE CMSEXPORT cmsOpenProfileFromIOhandler2THR(cmsContext ContextID, cmsIOHANDLER* io, cmsBool write)
1028 {
1029     _cmsICCPROFILE* NewIcc;
1030     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
1031
1032     if (hEmpty == NULL) return NULL;
1033
1034     NewIcc = (_cmsICCPROFILE*) hEmpty;
1035
1036     NewIcc ->IOhandler = io;
1037     if (write) {
1038
1039         NewIcc -> IsWrite = TRUE;
1040         return hEmpty;
1041     }
1042
1043     if (!_cmsReadHeader(NewIcc)) goto Error;
1044     return hEmpty;
1045
1046 Error:
1047     cmsCloseProfile(hEmpty);
1048     return NULL;
1049 }
1050
1051
1052 // Create profile from disk file
1053 cmsHPROFILE CMSEXPORT cmsOpenProfileFromFileTHR(cmsContext ContextID, const char *lpFileName, 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 = cmsOpenIOhandlerFromFile(ContextID, lpFileName, sAccess);
1063     if (NewIcc ->IOhandler == NULL) goto Error;
1064
1065     if (*sAccess == 'W' || *sAccess == 'w') {
1066
1067         NewIcc -> IsWrite = TRUE;
1068
1069         return hEmpty;
1070     }
1071
1072     if (!_cmsReadHeader(NewIcc)) goto Error;
1073     return hEmpty;
1074
1075 Error:
1076     cmsCloseProfile(hEmpty);
1077     return NULL;
1078 }
1079
1080
1081 cmsHPROFILE CMSEXPORT cmsOpenProfileFromFile(const char *ICCProfile, const char *sAccess)
1082 {
1083     return cmsOpenProfileFromFileTHR(NULL, ICCProfile, sAccess);
1084 }
1085
1086
1087 cmsHPROFILE  CMSEXPORT cmsOpenProfileFromStreamTHR(cmsContext ContextID, FILE* ICCProfile, const char *sAccess)
1088 {
1089     _cmsICCPROFILE* NewIcc;
1090     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
1091
1092     if (hEmpty == NULL) return NULL;
1093
1094     NewIcc = (_cmsICCPROFILE*) hEmpty;
1095
1096     NewIcc ->IOhandler = cmsOpenIOhandlerFromStream(ContextID, ICCProfile);
1097     if (NewIcc ->IOhandler == NULL) goto Error;
1098
1099     if (*sAccess == 'w') {
1100
1101         NewIcc -> IsWrite = TRUE;
1102         return hEmpty;
1103     }
1104
1105     if (!_cmsReadHeader(NewIcc)) goto Error;
1106     return hEmpty;
1107
1108 Error:
1109     cmsCloseProfile(hEmpty);
1110     return NULL;
1111
1112 }
1113
1114 cmsHPROFILE  CMSEXPORT cmsOpenProfileFromStream(FILE* ICCProfile, const char *sAccess)
1115 {
1116     return cmsOpenProfileFromStreamTHR(NULL, ICCProfile, sAccess);
1117 }
1118
1119
1120 // Open from memory block
1121 cmsHPROFILE CMSEXPORT cmsOpenProfileFromMemTHR(cmsContext ContextID, const void* MemPtr, cmsUInt32Number dwSize)
1122 {
1123     _cmsICCPROFILE* NewIcc;
1124     cmsHPROFILE hEmpty;
1125
1126     hEmpty = cmsCreateProfilePlaceholder(ContextID);
1127     if (hEmpty == NULL) return NULL;
1128
1129     NewIcc = (_cmsICCPROFILE*) hEmpty;
1130
1131     // Ok, in this case const void* is casted to void* just because open IO handler
1132     // shares read and writting modes. Don't abuse this feature!
1133     NewIcc ->IOhandler = cmsOpenIOhandlerFromMem(ContextID, (void*) MemPtr, dwSize, "r");
1134     if (NewIcc ->IOhandler == NULL) goto Error;
1135
1136     if (!_cmsReadHeader(NewIcc)) goto Error;
1137
1138     return hEmpty;
1139
1140 Error:
1141     cmsCloseProfile(hEmpty);
1142     return NULL;
1143 }
1144
1145 cmsHPROFILE CMSEXPORT cmsOpenProfileFromMem(const void* MemPtr, cmsUInt32Number dwSize)
1146 {
1147     return cmsOpenProfileFromMemTHR(NULL, MemPtr, dwSize);
1148 }
1149
1150
1151
1152 // Dump tag contents. If the profile is being modified, untouched tags are copied from FileOrig
1153 static
1154 cmsBool SaveTags(_cmsICCPROFILE* Icc, _cmsICCPROFILE* FileOrig)
1155 {
1156     cmsUInt8Number* Data;
1157     cmsUInt32Number i;
1158     cmsUInt32Number Begin;
1159     cmsIOHANDLER* io = Icc ->IOhandler;
1160     cmsTagDescriptor* TagDescriptor;
1161     cmsTagTypeSignature TypeBase;
1162     cmsTagTypeSignature Type;
1163     cmsTagTypeHandler* TypeHandler;
1164     cmsFloat64Number   Version = cmsGetProfileVersion((cmsHPROFILE) Icc);
1165     cmsTagTypeHandler LocalTypeHandler;
1166
1167     for (i=0; i < Icc -> TagCount; i++) {
1168
1169         if (Icc ->TagNames[i] == (cmsTagSignature) 0) continue;
1170
1171         // Linked tags are not written
1172         if (Icc ->TagLinked[i] != (cmsTagSignature) 0) continue;
1173
1174         Icc -> TagOffsets[i] = Begin = io ->UsedSpace;
1175
1176         Data = (cmsUInt8Number*)  Icc -> TagPtrs[i];
1177
1178         if (!Data) {
1179
1180             // Reach here if we are copying a tag from a disk-based ICC profile which has not been modified by user.
1181             // In this case a blind copy of the block data is performed
1182             if (FileOrig != NULL && Icc -> TagOffsets[i]) {
1183
1184                 cmsUInt32Number TagSize   = FileOrig -> TagSizes[i];
1185                 cmsUInt32Number TagOffset = FileOrig -> TagOffsets[i];
1186                 void* Mem;
1187
1188                 if (!FileOrig ->IOhandler->Seek(FileOrig ->IOhandler, TagOffset)) return FALSE;
1189
1190                 Mem = _cmsMalloc(Icc ->ContextID, TagSize);
1191                 if (Mem == NULL) return FALSE;
1192
1193                 if (FileOrig ->IOhandler->Read(FileOrig->IOhandler, Mem, TagSize, 1) != 1) return FALSE;
1194                 if (!io ->Write(io, TagSize, Mem)) return FALSE;
1195                 _cmsFree(Icc ->ContextID, Mem);
1196
1197                 Icc -> TagSizes[i] = (io ->UsedSpace - Begin);
1198
1199
1200                 // Align to 32 bit boundary.
1201                 if (! _cmsWriteAlignment(io))
1202                     return FALSE;
1203             }
1204
1205             continue;
1206         }
1207
1208
1209         // Should this tag be saved as RAW? If so, tagsizes should be specified in advance (no further cooking is done)
1210         if (Icc ->TagSaveAsRaw[i]) {
1211
1212             if (io -> Write(io, Icc ->TagSizes[i], Data) != 1) return FALSE;
1213         }
1214         else {
1215
1216             // Search for support on this tag
1217             TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, Icc -> TagNames[i]);
1218             if (TagDescriptor == NULL) continue;                        // Unsupported, ignore it
1219            
1220             if (TagDescriptor ->DecideType != NULL) {
1221
1222                 Type = TagDescriptor ->DecideType(Version, Data);
1223             }
1224             else {
1225
1226                 Type = TagDescriptor ->SupportedTypes[0];
1227             }
1228
1229             TypeHandler =  _cmsGetTagTypeHandler(Icc->ContextID, Type);
1230
1231             if (TypeHandler == NULL) {
1232                 cmsSignalError(Icc ->ContextID, cmsERROR_INTERNAL, "(Internal) no handler for tag %x", Icc -> TagNames[i]);
1233                 continue;
1234             }
1235
1236             TypeBase = TypeHandler ->Signature;
1237             if (!_cmsWriteTypeBase(io, TypeBase))
1238                 return FALSE;
1239
1240             LocalTypeHandler = *TypeHandler;
1241             LocalTypeHandler.ContextID  = Icc ->ContextID;
1242             LocalTypeHandler.ICCVersion = Icc ->Version;
1243             if (!LocalTypeHandler.WritePtr(&LocalTypeHandler, io, Data, TagDescriptor ->ElemCount)) {
1244
1245                 char String[5];
1246
1247                 _cmsTagSignature2String(String, (cmsTagSignature) TypeBase);
1248                 cmsSignalError(Icc ->ContextID, cmsERROR_WRITE, "Couldn't write type '%s'", String);
1249                 return FALSE;
1250             }
1251         }
1252
1253
1254         Icc -> TagSizes[i] = (io ->UsedSpace - Begin);
1255
1256         // Align to 32 bit boundary.
1257         if (! _cmsWriteAlignment(io))
1258             return FALSE;
1259     }
1260
1261
1262     return TRUE;
1263 }
1264
1265
1266 // Fill the offset and size fields for all linked tags
1267 static
1268 cmsBool SetLinks( _cmsICCPROFILE* Icc)
1269 {
1270     cmsUInt32Number i;
1271
1272     for (i=0; i < Icc -> TagCount; i++) {
1273
1274         cmsTagSignature lnk = Icc ->TagLinked[i];
1275         if (lnk != (cmsTagSignature) 0) {
1276
1277             int j = _cmsSearchTag(Icc, lnk, FALSE);
1278             if (j >= 0) {
1279
1280                 Icc ->TagOffsets[i] = Icc ->TagOffsets[j];
1281                 Icc ->TagSizes[i]   = Icc ->TagSizes[j];
1282             }
1283
1284         }
1285     }
1286
1287     return TRUE;
1288 }
1289
1290 // Low-level save to IOHANDLER. It returns the number of bytes used to
1291 // store the profile, or zero on error. io may be NULL and in this case
1292 // no data is written--only sizes are calculated
1293 cmsUInt32Number CMSEXPORT cmsSaveProfileToIOhandler(cmsHPROFILE hProfile, cmsIOHANDLER* io)
1294 {
1295     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1296     _cmsICCPROFILE Keep;
1297     cmsIOHANDLER* PrevIO = NULL;
1298     cmsUInt32Number UsedSpace;
1299     cmsContext ContextID;
1300
1301     _cmsAssert(hProfile != NULL);
1302     
1303     if (!_cmsLockMutex(Icc->ContextID, Icc->UsrMutex)) return 0;
1304     memmove(&Keep, Icc, sizeof(_cmsICCPROFILE));
1305
1306     ContextID = cmsGetProfileContextID(hProfile);
1307     PrevIO = Icc ->IOhandler = cmsOpenIOhandlerFromNULL(ContextID);
1308     if (PrevIO == NULL) {
1309         _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
1310         return 0;
1311     }
1312
1313     // Pass #1 does compute offsets
1314
1315     if (!_cmsWriteHeader(Icc, 0)) goto Error;
1316     if (!SaveTags(Icc, &Keep)) goto Error;
1317
1318     UsedSpace = PrevIO ->UsedSpace;
1319
1320     // Pass #2 does save to iohandler
1321
1322     if (io != NULL) {
1323
1324         Icc ->IOhandler = io;
1325         if (!SetLinks(Icc)) goto Error;
1326         if (!_cmsWriteHeader(Icc, UsedSpace)) goto Error;
1327         if (!SaveTags(Icc, &Keep)) goto Error;
1328     }
1329
1330     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
1331     if (!cmsCloseIOhandler(PrevIO)) 
1332         UsedSpace = 0; // As a error marker
1333
1334     _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
1335
1336     return UsedSpace;
1337
1338
1339 Error:
1340     cmsCloseIOhandler(PrevIO);
1341     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
1342     _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
1343
1344     return 0;
1345 }
1346
1347
1348 // Low-level save to disk.
1349 cmsBool  CMSEXPORT cmsSaveProfileToFile(cmsHPROFILE hProfile, const char* FileName)
1350 {
1351     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1352     cmsIOHANDLER* io = cmsOpenIOhandlerFromFile(ContextID, FileName, "w");
1353     cmsBool rc;
1354
1355     if (io == NULL) return FALSE;
1356
1357     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1358     rc &= cmsCloseIOhandler(io);
1359
1360     if (rc == FALSE) {          // remove() is C99 per 7.19.4.1
1361             remove(FileName);   // We have to IGNORE return value in this case
1362     }
1363     return rc;
1364 }
1365
1366 // Same as anterior, but for streams
1367 cmsBool CMSEXPORT cmsSaveProfileToStream(cmsHPROFILE hProfile, FILE* Stream)
1368 {
1369     cmsBool rc;
1370     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1371     cmsIOHANDLER* io = cmsOpenIOhandlerFromStream(ContextID, Stream);
1372
1373     if (io == NULL) return FALSE;
1374
1375     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1376     rc &= cmsCloseIOhandler(io);
1377
1378     return rc;
1379 }
1380
1381
1382 // Same as anterior, but for memory blocks. In this case, a NULL as MemPtr means calculate needed space only
1383 cmsBool CMSEXPORT cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr, cmsUInt32Number* BytesNeeded)
1384 {
1385     cmsBool rc;
1386     cmsIOHANDLER* io;
1387     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1388
1389     _cmsAssert(BytesNeeded != NULL);
1390
1391     // Should we just calculate the needed space?
1392     if (MemPtr == NULL) {
1393
1394            *BytesNeeded =  cmsSaveProfileToIOhandler(hProfile, NULL);
1395             return (*BytesNeeded == 0) ? FALSE : TRUE;
1396     }
1397
1398     // That is a real write operation
1399     io =  cmsOpenIOhandlerFromMem(ContextID, MemPtr, *BytesNeeded, "w");
1400     if (io == NULL) return FALSE;
1401
1402     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1403     rc &= cmsCloseIOhandler(io);
1404
1405     return rc;
1406 }
1407
1408
1409
1410 // Closes a profile freeing any involved resources
1411 cmsBool  CMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile)
1412 {
1413     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1414     cmsBool  rc = TRUE;
1415     cmsUInt32Number i;
1416
1417     if (!Icc) return FALSE;
1418
1419     // Was open in write mode?
1420     if (Icc ->IsWrite) {
1421
1422         Icc ->IsWrite = FALSE;      // Assure no further writting
1423         rc &= cmsSaveProfileToFile(hProfile, Icc ->IOhandler->PhysicalFile);
1424     }
1425
1426     for (i=0; i < Icc -> TagCount; i++) {
1427
1428         if (Icc -> TagPtrs[i]) {
1429
1430             cmsTagTypeHandler* TypeHandler = Icc ->TagTypeHandlers[i];
1431
1432             if (TypeHandler != NULL) {
1433                 cmsTagTypeHandler LocalTypeHandler = *TypeHandler;
1434
1435                 LocalTypeHandler.ContextID = Icc ->ContextID;              // As an additional parameters
1436                 LocalTypeHandler.ICCVersion = Icc ->Version;
1437                 LocalTypeHandler.FreePtr(&LocalTypeHandler, Icc -> TagPtrs[i]);
1438             }
1439             else
1440                 _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
1441         }
1442     }
1443
1444     if (Icc ->IOhandler != NULL) {
1445         rc &= cmsCloseIOhandler(Icc->IOhandler);
1446     }
1447
1448     _cmsDestroyMutex(Icc->ContextID, Icc->UsrMutex);
1449
1450     _cmsFree(Icc ->ContextID, Icc);   // Free placeholder memory
1451
1452     return rc;
1453 }
1454
1455
1456 // -------------------------------------------------------------------------------------------------------------------
1457
1458
1459 // Returns TRUE if a given tag is supported by a plug-in
1460 static
1461 cmsBool IsTypeSupported(cmsTagDescriptor* TagDescriptor, cmsTagTypeSignature Type)
1462 {
1463     cmsUInt32Number i, nMaxTypes;
1464
1465     nMaxTypes = TagDescriptor->nSupportedTypes;
1466     if (nMaxTypes >= MAX_TYPES_IN_LCMS_PLUGIN)
1467         nMaxTypes = MAX_TYPES_IN_LCMS_PLUGIN;
1468
1469     for (i=0; i < nMaxTypes; i++) {
1470         if (Type == TagDescriptor ->SupportedTypes[i]) return TRUE;
1471     }
1472
1473     return FALSE;
1474 }
1475
1476
1477 // That's the main read function
1478 void* CMSEXPORT cmsReadTag(cmsHPROFILE hProfile, cmsTagSignature sig)
1479 {
1480     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1481     cmsIOHANDLER* io = Icc ->IOhandler;
1482     cmsTagTypeHandler* TypeHandler;
1483     cmsTagTypeHandler LocalTypeHandler;
1484     cmsTagDescriptor*  TagDescriptor;
1485     cmsTagTypeSignature BaseType;
1486     cmsUInt32Number Offset, TagSize;
1487     cmsUInt32Number ElemCount;
1488     int n;
1489
1490     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return NULL;
1491
1492     n = _cmsSearchTag(Icc, sig, TRUE);
1493     if (n < 0) goto Error;               // Not found, return NULL
1494
1495
1496     // If the element is already in memory, return the pointer
1497     if (Icc -> TagPtrs[n]) {
1498
1499         if (Icc ->TagSaveAsRaw[n]) goto Error;  // We don't support read raw tags as cooked
1500
1501         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1502         return Icc -> TagPtrs[n];
1503     }
1504
1505     // We need to read it. Get the offset and size to the file
1506     Offset    = Icc -> TagOffsets[n];
1507     TagSize   = Icc -> TagSizes[n];
1508
1509     // Seek to its location
1510     if (!io -> Seek(io, Offset))
1511         goto Error;
1512
1513     // Search for support on this tag
1514     TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
1515     if (TagDescriptor == NULL) {
1516
1517         char String[5];
1518
1519         _cmsTagSignature2String(String, sig);
1520
1521         // An unknown element was found.
1522         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown tag type '%s' found.", String);
1523         goto Error;     // Unsupported.
1524     }
1525
1526     // if supported, get type and check if in list
1527     BaseType = _cmsReadTypeBase(io);
1528     if (BaseType == 0) goto Error;
1529
1530     if (!IsTypeSupported(TagDescriptor, BaseType)) goto Error;
1531
1532     TagSize  -= 8;                      // Alredy read by the type base logic
1533
1534     // Get type handler
1535     TypeHandler = _cmsGetTagTypeHandler(Icc ->ContextID, BaseType);
1536     if (TypeHandler == NULL) goto Error;
1537     LocalTypeHandler = *TypeHandler;
1538
1539
1540     // Read the tag
1541     Icc -> TagTypeHandlers[n] = TypeHandler;
1542
1543     LocalTypeHandler.ContextID = Icc ->ContextID;
1544     LocalTypeHandler.ICCVersion = Icc ->Version;
1545     Icc -> TagPtrs[n] = LocalTypeHandler.ReadPtr(&LocalTypeHandler, io, &ElemCount, TagSize);
1546
1547     // The tag type is supported, but something wrong happend and we cannot read the tag.
1548     // let know the user about this (although it is just a warning)
1549     if (Icc -> TagPtrs[n] == NULL) {
1550
1551         char String[5];
1552
1553         _cmsTagSignature2String(String, sig);
1554         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "Corrupted tag '%s'", String);
1555         goto Error;
1556     }
1557
1558     // This is a weird error that may be a symptom of something more serious, the number of
1559     // stored item is actually less than the number of required elements.
1560     if (ElemCount < TagDescriptor ->ElemCount) {
1561
1562         char String[5];
1563
1564         _cmsTagSignature2String(String, sig);
1565         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "'%s' Inconsistent number of items: expected %d, got %d",
1566             String, TagDescriptor ->ElemCount, ElemCount);
1567     }
1568
1569
1570     // Return the data
1571     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1572     return Icc -> TagPtrs[n];
1573
1574
1575     // Return error and unlock tha data
1576 Error:
1577     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1578     return NULL;
1579 }
1580
1581
1582 // Get true type of data
1583 cmsTagTypeSignature _cmsGetTagTrueType(cmsHPROFILE hProfile, cmsTagSignature sig)
1584 {
1585     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1586     cmsTagTypeHandler* TypeHandler;
1587     int n;
1588
1589     // Search for given tag in ICC profile directory
1590     n = _cmsSearchTag(Icc, sig, TRUE);
1591     if (n < 0) return (cmsTagTypeSignature) 0;                // Not found, return NULL
1592
1593     // Get the handler. The true type is there
1594     TypeHandler =  Icc -> TagTypeHandlers[n];
1595     return TypeHandler ->Signature;
1596 }
1597
1598
1599 // Write a single tag. This just keeps track of the tak into a list of "to be written". If the tag is already
1600 // in that list, the previous version is deleted.
1601 cmsBool CMSEXPORT cmsWriteTag(cmsHPROFILE hProfile, cmsTagSignature sig, const void* data)
1602 {
1603     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1604     cmsTagTypeHandler* TypeHandler = NULL;
1605     cmsTagTypeHandler LocalTypeHandler;
1606     cmsTagDescriptor* TagDescriptor = NULL;
1607     cmsTagTypeSignature Type;
1608     int i;
1609     cmsFloat64Number Version;
1610     char TypeString[5], SigString[5];
1611
1612     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return FALSE;
1613
1614     // To delete tags.
1615     if (data == NULL) {
1616
1617          // Delete the tag
1618          i = _cmsSearchTag(Icc, sig, FALSE);
1619          if (i >= 0) {
1620                 
1621              // Use zero as a mark of deleted 
1622              _cmsDeleteTagByPos(Icc, i);
1623              Icc ->TagNames[i] = (cmsTagSignature) 0;
1624              _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1625              return TRUE;
1626          }
1627          // Didn't find the tag
1628         goto Error;
1629     }
1630
1631     if (!_cmsNewTag(Icc, sig, &i)) goto Error;
1632
1633     // This is not raw
1634     Icc ->TagSaveAsRaw[i] = FALSE;
1635
1636     // This is not a link
1637     Icc ->TagLinked[i] = (cmsTagSignature) 0;
1638
1639     // Get information about the TAG.
1640     TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
1641     if (TagDescriptor == NULL){
1642          cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported tag '%x'", sig);
1643         goto Error;
1644     }
1645
1646
1647     // Now we need to know which type to use. It depends on the version.
1648     Version = cmsGetProfileVersion(hProfile);
1649
1650     if (TagDescriptor ->DecideType != NULL) {
1651
1652         // Let the tag descriptor to decide the type base on depending on
1653         // the data. This is useful for example on parametric curves, where
1654         // curves specified by a table cannot be saved as parametric and needs
1655         // to be casted to single v2-curves, even on v4 profiles.
1656
1657         Type = TagDescriptor ->DecideType(Version, data);
1658     }
1659     else {
1660
1661         Type = TagDescriptor ->SupportedTypes[0];
1662     }
1663
1664     // Does the tag support this type?
1665     if (!IsTypeSupported(TagDescriptor, Type)) {
1666
1667         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1668         _cmsTagSignature2String(SigString,  sig);
1669
1670         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported type '%s' for tag '%s'", TypeString, SigString);
1671         goto Error;
1672     }
1673
1674     // Does we have a handler for this type?
1675     TypeHandler =  _cmsGetTagTypeHandler(Icc->ContextID, Type);
1676     if (TypeHandler == NULL) {
1677
1678         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1679         _cmsTagSignature2String(SigString,  sig);
1680
1681         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported type '%s' for tag '%s'", TypeString, SigString);
1682         goto Error;           // Should never happen
1683     }
1684
1685
1686     // Fill fields on icc structure
1687     Icc ->TagTypeHandlers[i]  = TypeHandler;
1688     Icc ->TagNames[i]         = sig;
1689     Icc ->TagSizes[i]         = 0;
1690     Icc ->TagOffsets[i]       = 0;
1691
1692     LocalTypeHandler = *TypeHandler;
1693     LocalTypeHandler.ContextID  = Icc ->ContextID;
1694     LocalTypeHandler.ICCVersion = Icc ->Version;
1695     Icc ->TagPtrs[i]            = LocalTypeHandler.DupPtr(&LocalTypeHandler, data, TagDescriptor ->ElemCount);
1696
1697     if (Icc ->TagPtrs[i] == NULL)  {
1698
1699         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1700         _cmsTagSignature2String(SigString,  sig);
1701         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "Malformed struct in type '%s' for tag '%s'", TypeString, SigString);
1702
1703         goto Error;
1704     }
1705
1706     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1707     return TRUE;
1708
1709 Error:
1710     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1711     return FALSE;
1712
1713 }
1714
1715 // Read and write raw data. The only way those function would work and keep consistence with normal read and write
1716 // is to do an additional step of serialization. That means, readRaw would issue a normal read and then convert the obtained
1717 // data to raw bytes by using the "write" serialization logic. And vice-versa. I know this may end in situations where
1718 // raw data written does not exactly correspond with the raw data proposed to cmsWriteRaw data, but this approach allows
1719 // to write a tag as raw data and the read it as handled.
1720
1721 cmsInt32Number CMSEXPORT cmsReadRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, void* data, cmsUInt32Number BufferSize)
1722 {
1723     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1724     void *Object;
1725     int i;
1726     cmsIOHANDLER* MemIO;
1727     cmsTagTypeHandler* TypeHandler = NULL;
1728     cmsTagTypeHandler LocalTypeHandler;
1729     cmsTagDescriptor* TagDescriptor = NULL;
1730     cmsUInt32Number rc;
1731     cmsUInt32Number Offset, TagSize;
1732
1733     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
1734
1735     // Search for given tag in ICC profile directory
1736     i = _cmsSearchTag(Icc, sig, TRUE);
1737     if (i < 0) goto Error;                 // Not found, 
1738
1739     // It is already read?
1740     if (Icc -> TagPtrs[i] == NULL) {
1741
1742         // No yet, get original position
1743         Offset   = Icc ->TagOffsets[i];
1744         TagSize  = Icc ->TagSizes[i];
1745
1746         // read the data directly, don't keep copy
1747         if (data != NULL) {
1748
1749             if (BufferSize < TagSize)
1750                 TagSize = BufferSize;
1751
1752             if (!Icc ->IOhandler ->Seek(Icc ->IOhandler, Offset)) goto Error;
1753             if (!Icc ->IOhandler ->Read(Icc ->IOhandler, data, 1, TagSize)) goto Error;
1754
1755             _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1756             return TagSize;
1757         }
1758
1759         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1760         return Icc ->TagSizes[i];
1761     }
1762
1763     // The data has been already read, or written. But wait!, maybe the user choosed to save as
1764     // raw data. In this case, return the raw data directly
1765     if (Icc ->TagSaveAsRaw[i]) {
1766
1767         if (data != NULL)  {
1768
1769             TagSize  = Icc ->TagSizes[i];
1770             if (BufferSize < TagSize)
1771                 TagSize = BufferSize;
1772
1773             memmove(data, Icc ->TagPtrs[i], TagSize);
1774
1775             _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1776             return TagSize;
1777         }
1778
1779         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1780         return Icc ->TagSizes[i];
1781     }
1782
1783     // Already readed, or previously set by cmsWriteTag(). We need to serialize that
1784     // data to raw in order to maintain consistency.
1785
1786     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1787     Object = cmsReadTag(hProfile, sig);
1788     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
1789
1790     if (Object == NULL) goto Error;
1791
1792     // Now we need to serialize to a memory block: just use a memory iohandler
1793
1794     if (data == NULL) {
1795         MemIO = cmsOpenIOhandlerFromNULL(cmsGetProfileContextID(hProfile));
1796     } else{
1797         MemIO = cmsOpenIOhandlerFromMem(cmsGetProfileContextID(hProfile), data, BufferSize, "w");
1798     }
1799     if (MemIO == NULL) goto Error;
1800
1801     // Obtain type handling for the tag
1802     TypeHandler = Icc ->TagTypeHandlers[i];
1803     TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
1804     if (TagDescriptor == NULL) {
1805         cmsCloseIOhandler(MemIO);
1806         goto Error;
1807     }
1808     
1809     if (TypeHandler == NULL) goto Error;
1810
1811     // Serialize
1812     LocalTypeHandler = *TypeHandler;
1813     LocalTypeHandler.ContextID  = Icc ->ContextID;
1814     LocalTypeHandler.ICCVersion = Icc ->Version;
1815
1816     if (!_cmsWriteTypeBase(MemIO, TypeHandler ->Signature)) {
1817         cmsCloseIOhandler(MemIO);
1818         goto Error;
1819     }
1820
1821     if (!LocalTypeHandler.WritePtr(&LocalTypeHandler, MemIO, Object, TagDescriptor ->ElemCount)) {
1822         cmsCloseIOhandler(MemIO);
1823         goto Error;
1824     }
1825
1826     // Get Size and close
1827     rc = MemIO ->Tell(MemIO);
1828     cmsCloseIOhandler(MemIO);      // Ignore return code this time
1829
1830     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1831     return rc;
1832
1833 Error:
1834     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1835     return 0;
1836 }
1837
1838 // Similar to the anterior. This function allows to write directly to the ICC profile any data, without
1839 // checking anything. As a rule, mixing Raw with cooked doesn't work, so writting a tag as raw and then reading
1840 // it as cooked without serializing does result into an error. If that is what you want, you will need to dump
1841 // the profile to memry or disk and then reopen it.
1842 cmsBool CMSEXPORT cmsWriteRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, const void* data, cmsUInt32Number Size)
1843 {
1844     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1845     int i;
1846
1847     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
1848
1849     if (!_cmsNewTag(Icc, sig, &i)) {
1850         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1851          return FALSE;
1852     }
1853
1854     // Mark the tag as being written as RAW
1855     Icc ->TagSaveAsRaw[i] = TRUE;
1856     Icc ->TagNames[i]     = sig;
1857     Icc ->TagLinked[i]    = (cmsTagSignature) 0;
1858
1859     // Keep a copy of the block
1860     Icc ->TagPtrs[i]  = _cmsDupMem(Icc ->ContextID, data, Size);
1861     Icc ->TagSizes[i] = Size;
1862
1863     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1864
1865     if (Icc->TagPtrs[i] == NULL) {           
1866            Icc->TagNames[i] = (cmsTagSignature) 0;
1867            return FALSE;
1868     }
1869     return TRUE;
1870 }
1871
1872 // Using this function you can collapse several tag entries to the same block in the profile
1873 cmsBool CMSEXPORT cmsLinkTag(cmsHPROFILE hProfile, cmsTagSignature sig, cmsTagSignature dest)
1874 {
1875     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1876     int i;
1877
1878      if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return FALSE;
1879
1880     if (!_cmsNewTag(Icc, sig, &i)) {
1881         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1882         return FALSE;
1883     }
1884
1885     // Keep necessary information
1886     Icc ->TagSaveAsRaw[i] = FALSE;
1887     Icc ->TagNames[i]     = sig;
1888     Icc ->TagLinked[i]    = dest;
1889
1890     Icc ->TagPtrs[i]    = NULL;
1891     Icc ->TagSizes[i]   = 0;
1892     Icc ->TagOffsets[i] = 0;
1893
1894     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1895     return TRUE;
1896 }
1897
1898
1899 // Returns the tag linked to sig, in the case two tags are sharing same resource
1900 cmsTagSignature  CMSEXPORT cmsTagLinkedTo(cmsHPROFILE hProfile, cmsTagSignature sig)
1901 {
1902     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1903     int i;
1904
1905     // Search for given tag in ICC profile directory
1906     i = _cmsSearchTag(Icc, sig, FALSE);
1907     if (i < 0) return (cmsTagSignature) 0;                 // Not found, return 0
1908
1909     return Icc -> TagLinked[i];
1910 }