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