File: cmsgmt.c

package info (click to toggle)
foo2zjs 20050217-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,364 kB
  • ctags: 2,122
  • sloc: ansic: 15,074; xml: 1,751; makefile: 503; sh: 269; perl: 102
file content (853 lines) | stat: -rwxr-xr-x 22,833 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
//
//  Little cms
//  Copyright (C) 1998-2000 Marti Maria
//
// THIS SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
// EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
// WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
//
// IN NO EVENT SHALL MARTI MARIA BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
// INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
// OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
// LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
// OF THIS SOFTWARE.
//
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#include "lcms.h"

// #define DEBUG 1

/*
Gamut check by default is a catching of 0xFFFF/0xFFFF/0xFFFF PCS values, used
internally by lcms to hold invalid values. Matrix LUT's, operates in a way that
unencodeable values are marked as this combination, if PCS is XYZ, this is a very
high value since encoding is a 1.15 fixed point, something like 1.9997, 1.9997, 1.9997
not a very common color after all. Lab PCS is not to be a problem, since L>100 are truely
undefined. There is a posibility than ICC comitee defines L>100 as a valid means
to use highlights, then it will be lost.

(1.10 - Actually ICC did it, so this should be checked for full ICC 4.0 support)

*/


BOOL _cmsEndPointsBySpace(icColorSpaceSignature Space, WORD **White, WORD **Black,
                            int *nOutputs)
{
       // Only most common spaces

       static WORD RGBblack[4]  = { 0, 0, 0 };
       static WORD RGBwhite[4]  = { 0xffff, 0xffff, 0xffff };
       static WORD CMYKblack[4] = { 0, 0, 0, 0xffff };
       static WORD CMYKwhite[4] = { 0, 0, 0, 0 };
       static WORD LABblack[4]  = { 0, 0, 0 };
       static WORD LABwhite[4]  = { 0xFF00, 0x8000, 0x8000 };


       switch (Space) {

       case icSigRgbData:  *White = RGBwhite;
                           *Black = RGBblack;
                           *nOutputs = 3;
                           return TRUE;

       case icSigLabData:  *White = LABwhite;
                           *Black = LABblack;
                           *nOutputs = 3;
                           return TRUE;

       case icSigCmykData: *White = CMYKwhite;
                           *Black = CMYKblack;
                           *nOutputs = 4;
                           return TRUE;

       default:;
       }

  return FALSE;
}


WORD *_cmsWhiteBySpace(icColorSpaceSignature Space)
{
       WORD *White= NULL, *Black = NULL;
       int Dummy;
       static WORD Default[MAXCHANNELS];

       if (_cmsEndPointsBySpace(Space, &White, &Black, &Dummy))
              return White;

       return Default;

}


WORD Clamp_XYZ(int in)
{
       if (in < 0) return 0;
       if (in > 0xFFFF) return 0xFFFFU;   // Including marker
       return (WORD) in;
}

WORD Clamp_RGB(int in)
{
       if (in < 0) return 0;
       if (in > 0xFFFF) return 0xFFFFU;   // Including marker
       return (WORD) in;
}


WORD Clamp_L(Fixed32 in)
{
       if (in == 0xFFFF) return 0xFFFFU;  // Marker

       if (in > 0xFF00) return 0xFF00U;  // L* = 100.0
       return (WORD) in;
}


#define ENCODE_AB(x) (WORD) (((x) + 128.0) * 256.0 + 0.5)

WORD Clamp_ab(Fixed32 in)
{
       if (in == 0xFFFF) return 0xFFFFU;            // Marker

       if (in < 0) return ENCODE_AB(-128.0);         // 0;         // Max negative number
       if (in > 0xFFFF) return ENCODE_AB(+127.9961); // 0xFFFF;    // Max positive number
       return (WORD) in;
}



// Returns dE on two Lab values

double LCMSEXPORT cmsDeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2)
{
        double dL, da, db;
        
        if (Lab1 -> L < 0 ||
            Lab2 -> L < 0) return 65536.;

        if (Lab1 -> a < -200 || Lab1 -> a > 200) return 65536.;
        if (Lab1 -> b < -200 || Lab1 -> b > 200) return 65536.;

        if (Lab2 -> a < -200 || Lab2 -> a > 200) return 65536.;
        if (Lab2 -> b < -200 || Lab2 -> b > 200) return 65536.;

        if (Lab1 ->L == 0 && Lab2 ->L == 0) return 0;
        
        dL = fabs(Lab1 -> L - Lab2 -> L);
        da = fabs(Lab1 -> a - Lab2 -> a);
        db = fabs(Lab1 -> b - Lab2 -> b);

        return pow(dL*dL + da * da + db * db, 0.5);

}


// Square
static
double Sqr(double v)
{
    return v *  v; 
}

// Return the CIE94 Delta E 
double LCMSEXPORT cmsCIE94DeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2)
{
    cmsCIELCh LCh1, LCh2;
    double dE, dL, dC, dh, dhsq;
    double c12, sc, sh;

    if (Lab1 ->L == 0 && Lab2 ->L == 0) return 0;

    dL = fabs(Lab1 ->L - Lab2 ->L);

    cmsLab2LCh(&LCh1, Lab1);
    cmsLab2LCh(&LCh2, Lab2);

    dC  = fabs(LCh1.C - LCh2.C);
    dE  = cmsDeltaE(Lab1, Lab2);
    
    dhsq = Sqr(dE) - Sqr(dL) - Sqr(dC);
    if (dhsq < 0)
        dh = 0;
    else
        dh = pow(dhsq, 0.5);

    c12 = sqrt(LCh1.C * LCh2.C);

    sc = 1.0 + (0.048 * c12);
    sh = 1.0 + (0.014 * c12);
            
    return sqrt(Sqr(dL)  + Sqr(dC) / Sqr(sc) + Sqr(dh) / Sqr(sh));
}


// Auxiliary

static
double ComputeLBFD(LPcmsCIELab Lab)
{
  double yt;

  if (Lab->L > 7.996969)
        yt = (Sqr((Lab->L+16)/116)*((Lab->L+16)/116))*100;
  else
        yt = 100 * (Lab->L / 903.3);

  return (54.6 * (LOGE * (log(yt + 1.5))) - 9.6);
}



// bfd - gets BFD(1:1) difference between Lab1, Lab2
double LCMSEXPORT cmsBFDdeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2)
{
  double lbfd1,lbfd2,AveC,Aveh,dE,deltaL,
  deltaC,deltah,dc,t,g,dh,rh,rc,rt,bfd;
  cmsCIELCh LCh1, LCh2;


  if (Lab1 ->L == 0 && Lab2 ->L == 0) return 0;

  lbfd1 = ComputeLBFD(Lab1);
  lbfd2 = ComputeLBFD(Lab2);
  deltaL = lbfd2 - lbfd1;

  cmsLab2LCh(&LCh1, Lab1);
  cmsLab2LCh(&LCh2, Lab2);

  deltaC = LCh2.C - LCh1.C;
  AveC = (LCh1.C+LCh2.C)/2;
  Aveh = (LCh1.h+LCh2.h)/2;

  dE = cmsDeltaE(Lab1, Lab2);

  if (Sqr(dE)>(Sqr(Lab2->L-Lab1->L)+Sqr(deltaC)))
    deltah = sqrt(Sqr(dE)-Sqr(Lab2->L-Lab1->L)-Sqr(deltaC));
  else
    deltah =0;

  
  dc   = 0.035 * AveC / (1 + 0.00365 * AveC)+0.521;
  g    = sqrt(Sqr(Sqr(AveC))/(Sqr(Sqr(AveC))+14000));
  t    = 0.627+(0.055*cos((Aveh-254)/(180/M_PI))-       
         0.040*cos((2*Aveh-136)/(180/M_PI))+
         0.070*cos((3*Aveh-31)/(180/M_PI))+
         0.049*cos((4*Aveh+114)/(180/M_PI))-
         0.015*cos((5*Aveh-103)/(180/M_PI)));

  dh    = dc*(g*t+1-g);
  rh    = -0.260*cos((Aveh-308)/(180/M_PI))-
         0.379*cos((2*Aveh-160)/(180/M_PI))-
         0.636*cos((3*Aveh+254)/(180/M_PI))+
         0.226*cos((4*Aveh+140)/(180/M_PI))-
         0.194*cos((5*Aveh+280)/(180/M_PI));
  
    rc = sqrt((AveC*AveC*AveC*AveC*AveC*AveC)/((AveC*AveC*AveC*AveC*AveC*AveC)+70000000));
    rt = rh*rc;
  
    bfd = sqrt(Sqr(deltaL)+Sqr(deltaC/dc)+Sqr(deltah/dh)+(rt*(deltaC/dc)*(deltah/dh)));

    return bfd;
}


//  cmc - CMC(1:1) difference between Lab1, Lab2
double LCMSEXPORT cmsCMCdeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2)
{
  double dE,dL,dC,dh,sl,sc,sh,t,f,cmc;
  cmsCIELCh LCh1, LCh2;

  if (Lab1 ->L == 0 && Lab2 ->L == 0) return 0;

  cmsLab2LCh(&LCh1, Lab1);
  cmsLab2LCh(&LCh2, Lab2);

  
  dL = Lab2->L-Lab1->L;
  dC = LCh2.C-LCh1.C;

  dE = cmsDeltaE(Lab1, Lab2);
  if (Sqr(dE)>(Sqr(dL)+Sqr(dC))) 
            dh = sqrt(Sqr(dE)-Sqr(dL)-Sqr(dC));
  else
            dh =0;

  if ((LCh1.h > 164) && (LCh1.h<345)) 
      t = 0.56 + fabs(0.2 * cos(((LCh1.h + 168)/(180/M_PI))));
  else 
      t = 0.36 + fabs(0.4 * cos(((LCh1.h + 35 )/(180/M_PI))));

   sc  = 0.0638   * LCh1.C / (1 + 0.0131  * LCh1.C) + 0.638;
   sl  = 0.040975 * Lab1->L /(1 + 0.01765 * Lab1->L);
   
   if (Lab1->L<16)
         sl = 0.511; 

   f   = sqrt((LCh1.C * LCh1.C * LCh1.C * LCh1.C)/((LCh1.C * LCh1.C * LCh1.C * LCh1.C)+1900));
   sh  = sc*(t*f+1-f);
   cmc = sqrt(Sqr(dL/sl)+Sqr(dC/sc)+Sqr(dh/sh));

   return cmc;
}

   
    

// Carefully,  clamp on CIELab space. WARNING: Lab is not very adequate to do that!!

void LCMSEXPORT cmsClampLab(LPcmsCIELab Lab, double amax, double amin,
                                   double bmax, double bmin)
{

            // Whole Luma surface to zero

        if (Lab -> L < 0) {

                Lab-> L = Lab->a = Lab-> b = 0.0;
                return;
            }

            // Clamp white, DISCARD HIGHLIGHTS. This is done
            // in such way because icc spec doesn't allow the
            // use of L>100 as a highlight means.

            if (Lab->L > 100)
                        Lab -> L = 100;

            // Check out gamut prism, on a, b faces

            if (Lab -> a < amin || Lab->a > amax||
                Lab -> b < bmin || Lab->b > bmax) {

                 cmsCIELCh LCh;
                 double h, slope;

                 // Falls outside a, b limits. Transports to LCh space,
                 // and then do the clipping


                 if (Lab -> a == 0.0) { // Is hue exactly 90?

                        // atan will not work, so clamp here
                        Lab -> b = Lab->b < 0 ? bmin : bmax;
                        return;
                 }

                 cmsLab2LCh(&LCh, Lab);

                 slope = Lab -> b / Lab -> a;
                 h = LCh.h;

                 // There are 4 zones

                 if ((h >= 0. && h < 45.) ||
                     (h >= 315 && h <= 360.)) {

                     // clip by amax
                     Lab -> a = amax;
                     Lab -> b = amax * slope;
                 }
                 else
                 if (h >= 45. && h < 135)
                 {
                        // clip by bmax
                        Lab -> b = bmax;
                        Lab -> a = bmax / slope;
                 }
                 else
                 if (h >= 135 && h < 225) {
                        // clip by amin
                        Lab -> a = amin;
                        Lab -> b = amin * slope;

                 }
                 else
                 if (h >= 225 && h < 315) {
                        // clip by bmin
                        Lab -> b = bmin;
                        Lab -> a = bmin / slope;
                 }
                 else
                        cmsSignalError(-1, "Invalid angle");

        }
}

// Several utilities -------------------------------------------------------

// Translate from our colorspace to ICC representation

icColorSpaceSignature LCMSEXPORT _cmsICCcolorSpace(int OurNotation)
{
       switch (OurNotation) {

       case 1:
       case PT_GRAY: return  icSigGrayData;

       case 2:
       case PT_RGB:  return  icSigRgbData;

       case PT_CMY:  return  icSigCmyData;
       case PT_CMYK: return  icSigCmykData;
       case PT_YCbCr:return  icSigYCbCrData;
       case PT_YUV:  return  icSigLuvData;
       case PT_XYZ:  return  icSigXYZData;
       case PT_Lab:  return  icSigLabData;
       case PT_YUVK: return  icSigLuvKData;
       case PT_HSV:  return  icSigHsvData;
       case PT_HLS:  return  icSigHlsData;
       case PT_Yxy:  return  icSigYxyData;
       case PT_HiFi: return  icSigHexachromeData;

       default:  return icMaxEnumData;
       }
}

int LCMSEXPORT _cmsChannelsOf(icColorSpaceSignature ColorSpace)
{

    switch (ColorSpace) {

    case icSigGrayData: return 1;

    case icSig2colorData:  return 2;
        
    case icSigXYZData:
    case icSigLabData:
    case icSigLuvData:
    case icSigYCbCrData:
    case icSigYxyData:
    case icSigRgbData:   
    case icSigHsvData:
    case icSigHlsData:
    case icSigCmyData: 
    case icSig3colorData:  return 3;

        
            
    case icSigLuvKData:
    case icSigCmykData:
    case icSig4colorData:  return 4;


    case icSig5colorData:  return 5;  

    case icSigHexachromeData:   
    case icSig6colorData:  return 6;
        
    case icSig7colorData:  return  7;
    case icSig8colorData:  return  8;
    case icSig9colorData:  return  9;
    case icSig10colorData: return 10;
    case icSig11colorData: return 11;
    case icSig12colorData: return 12;
    case icSig13colorData: return 13;
    case icSig14colorData: return 14;
    case icSig15colorData: return 15;

    default: return 3;
    }

}



// Used by gamut & softproofing

typedef struct {

    cmsHTRANSFORM hForward, hReverse;
    
    } GAMUTCHAIN,FAR* LPGAMUTCHAIN;

// This sampler does compute gamut boundaries by comparing original
// values with a transform going back and forth. Values above 15% 
// of maximum are considered out of gamut.



#define ERR_THERESHOLD	12
static
int GamutSampler(register WORD In[], register WORD Out[], register LPVOID Cargo)
{
	LPGAMUTCHAIN t = (LPGAMUTCHAIN) Cargo;
	WORD Proof[MAXCHANNELS], Check[MAXCHANNELS];
	WORD Proof2[MAXCHANNELS], Check2[MAXCHANNELS];
	cmsCIELab LabIn1, LabOut1;  
	cmsCIELab LabIn2, LabOut2;  
	double dE1, dE2, ErrorRatio;
	
	// Assume in-gamut by default.
	dE1 = 0.;
	dE2 = 0;
	ErrorRatio = 1.0;
	
	// converts from pcs to colorant. This always
	// does return in-gamut values, 
	cmsDoTransform(t -> hForward, In, Proof, 1);
	
	// Now, do the inverse, from colorant to pcs.
	cmsDoTransform(t -> hReverse, Proof, Check, 1);
	
	
	// Try again, but this time taking Check as input
	cmsDoTransform(t -> hForward, Check, Proof2,  1);
	cmsDoTransform(t -> hReverse, Proof2, Check2, 1);
	
	
	
	// Does the transform returns out-of-gamut?
	if (Check[0] == 0xFFFF && 
		Check[1] == 0xFFFF && 
		Check[2] == 0xFFFF) 
		
		Out[0] = 0xF000;    // Out of gamut!
	else {
		
		// Transport encoded values
		cmsLabEncoded2Float(&LabIn1, In);
		cmsLabEncoded2Float(&LabOut1, Check);
        
		// Take difference of direct value
		dE1 = cmsDeltaE(&LabIn1, &LabOut1);        
		
		
		cmsLabEncoded2Float(&LabIn2, Check);
		cmsLabEncoded2Float(&LabOut2, Check2);
        
		// Take difference of converted value
		dE2 = cmsDeltaE(&LabIn2, &LabOut2);        			
		       
		
		// if dE1 is small and dE2 is small, value is likely to be in gamut
		if (dE1 < ERR_THERESHOLD && dE2 < ERR_THERESHOLD) 
			Out[0] = 0;
		else
			// if dE1 is small and dE2 is big, undefined. Assume in gamut
			if (dE1 < ERR_THERESHOLD && dE2 > ERR_THERESHOLD)
				Out[0] = 0;
			else
				// dE1 is big and dE2 is small, clearly out of gamut
				if (dE1 > ERR_THERESHOLD && dE2 < ERR_THERESHOLD)
					Out[0] = (WORD) floor((dE1 - ERR_THERESHOLD) + .5);
				else  {
					
					// dE1 is big and dE2 is also big, could be due to perceptual mapping
					// so take error ratio
					if (dE2 == 0.0)
						ErrorRatio = dE1;
					else
						ErrorRatio = dE1 / dE2;
					
					if (ErrorRatio > ERR_THERESHOLD) 
						Out[0] = (WORD)  floor((ErrorRatio - ERR_THERESHOLD) + .5);
					else
						Out[0] = 0;
				}
			
	}    
    
	return TRUE;
}


// Does compute a gamut LUT going back and forth across 
// pcs -> relativ. colorimetric intent -> pcs
// the dE obtained is then annotated on the LUT.
// values truely out of gamut, are clipped to dE = 0xFFFE
// and values changed are supposed to be handled by
// any gamut remapping, so, are out of gamut as well.
//
// **WARNING: This algorithm does assume that gamut
// remapping algorithms does NOT move in-gamut colors,
// of course, many perceptual and saturation intents does
// not work in such way, but relativ. ones should.


LPLUT _cmsComputeGamutLUT(cmsHPROFILE hProfile, int Intent)
{

    cmsHPROFILE hLab;
    LPLUT Gamut;
    DWORD dwFormat;
    GAMUTCHAIN Chain;
    int nErrState;
        

    ZeroMemory(&Chain, sizeof(GAMUTCHAIN)); 

    hLab = cmsCreateLabProfile(NULL);

    // ONLY 4 channels  
    dwFormat = (CHANNELS_SH(4)|BYTES_SH(2));
    
    // Safeguard against early abortion
    nErrState = cmsErrorAction(LCMS_ERROR_IGNORE);

    // Does create the first step
    Chain.hForward = cmsCreateTransform(hLab, TYPE_Lab_16, 
                                        hProfile, dwFormat, 
                                        Intent, 
                                        cmsFLAGS_NOTPRECALC);

    // Does create the last step
    Chain.hReverse = cmsCreateTransform(hProfile, dwFormat, 
                                        hLab, TYPE_Lab_16,                                      
                                        Intent, 
                                        cmsFLAGS_NOTPRECALC);

    // Restores error handler previous state
    cmsErrorAction(nErrState);

    // All ok?
    if (Chain.hForward && Chain.hReverse) {
            
    // Go on, try to compute gamut LUT from PCS.
    // This consist on a single channel containing 
    // dE when doing a transform back and forth on
    // the colorimetric intent. This table will
    // take 42 points to give some accurancy, 
    // 42 * 42 * 42 * 2 = 203K

    Gamut = cmsAllocLUT();
    Gamut = cmsAlloc3DGrid(Gamut, 42, 3, 1);
    
    cmsSample3DGrid(Gamut, GamutSampler, (LPVOID) &Chain, 0);
    
    }
    else 
        Gamut = NULL;   // Didn't work...

    // Free all needed stuff.
    if (Chain.hForward) cmsDeleteTransform(Chain.hForward);
    if (Chain.hReverse) cmsDeleteTransform(Chain.hReverse);

    cmsCloseProfile(hLab);


    // And return computed hull
    return Gamut;
}

// SoftProofing. Convert from Lab to device, then back to Lab, 
// any gamut remapping is applied

static
int SoftProofSampler(register WORD In[], register WORD Out[], register LPVOID Cargo)
{
        LPGAMUTCHAIN t = (LPGAMUTCHAIN) Cargo;
        WORD Colorant[MAXCHANNELS];
                
        // From pcs to colorant
        cmsDoTransform(t -> hForward, In, Colorant, 1);

        // Now, do the inverse, from colorant to pcs.
        cmsDoTransform(t -> hReverse, Colorant, Out, 1);
                
        return TRUE;
}

// Does return Softproofing LUT on desired intent

LPLUT _cmsComputeSoftProofLUT(cmsHPROFILE hProfile, int nIntent)
{
    cmsHPROFILE hLab;
    LPLUT SoftProof;
    DWORD dwFormat;
    GAMUTCHAIN Chain;
    int nErrState;
        

    ZeroMemory(&Chain, sizeof(GAMUTCHAIN));

    hLab = cmsCreateLabProfile(NULL);

    // ONLY 4 channels  
    dwFormat = (CHANNELS_SH(4)|BYTES_SH(2));
    
    // Safeguard against early abortion
    nErrState = cmsErrorAction(LCMS_ERROR_IGNORE);

    // Does create the first step
    Chain.hForward = cmsCreateTransform(hLab, TYPE_Lab_16, 
                                        hProfile, dwFormat, 
                                        nIntent,
                                        cmsFLAGS_NOTPRECALC);

    // Does create the last step
    Chain.hReverse = cmsCreateTransform(hProfile, dwFormat, 
                                        hLab, TYPE_Lab_16,                                      
                                        nIntent, 
                                        cmsFLAGS_NOTPRECALC);

    // Restores error handler previous state
    cmsErrorAction(nErrState);

    // All ok?
    if (Chain.hForward && Chain.hReverse) {
                
    // This is Lab -> Lab, so 33 point should hold anything
    SoftProof = cmsAllocLUT();
    SoftProof = cmsAlloc3DGrid(SoftProof, 33, 3, 3);

    cmsSample3DGrid(SoftProof, SoftProofSampler, (LPVOID) &Chain, 0);
    }
    else 
        SoftProof = NULL;   // Didn't work...

    // Free all needed stuff.
    if (Chain.hForward) cmsDeleteTransform(Chain.hForward);
    if (Chain.hReverse) cmsDeleteTransform(Chain.hReverse);

    cmsCloseProfile(hLab);

    return SoftProof;
}



#ifdef DEBUG
static
void ASAVE(LPGAMMATABLE p, const char* dump)
{
    FILE* f;
    int i;

        f = fopen(dump, "wt");
        if (!f)
                return;

        if (p) {

    for (i=0; i < p -> nEntries; i++)
        fprintf(f, "%g\n", (double) p -> GammaTable[i]);
        }

    fclose(f);
}
#endif


static
int MostlyLinear(WORD Table[], int nEntries)
{
       register int i;
       int diff;

       for (i=5; i < nEntries; i++) {

           diff = abs((int) Table[i] - (int) _cmsQuantizeVal(i, nEntries));              
           if (diff > 0x0300)
                     return 0;
       }

       return 1;
}


#define PRELINEARIZATION_POINTS 1024

static
int ConvertCurvesToPureExponential(LPGAMMATABLE t[], int nChannels)
{
        int i;
        double GammaValues[MAXCHANNELS];

        for (i=0; i < nChannels; i++){
        
                GammaValues[i] = cmsEstimateGamma(t[i]);
                if (GammaValues[i] < 0) 
                                return 0;       // Was unable to convert

        }

        // Replace curve by its pure-exponential homologue

        for (i=0; i < nChannels; i++){
        
                cmsFreeGamma(t[i]);
                t[i] = cmsBuildGamma(PRELINEARIZATION_POINTS, GammaValues[i]);              

        }

        return 1;   // Ok, done
}


// Fixes the gamma balancing of transform. Thanks to Mike Chaney
// for pointing this subtle bug.


void _cmsComputePrelinearizationTablesFromXFORM(cmsHTRANSFORM h[], int nTransforms, LPLUT Grid)
{
    LPGAMMATABLE Trans[MAXCHANNELS];
    unsigned int t, i, v;
    int j;
    WORD In[MAXCHANNELS], Out[MAXCHANNELS];
    BOOL lIsSuitable;
    
    for (t = 0; t < Grid -> InputChan; t++) 
            Trans[t] = cmsAllocGamma(PRELINEARIZATION_POINTS);

    for (i=0; i < PRELINEARIZATION_POINTS; i++) {

                v = _cmsQuantizeVal(i, PRELINEARIZATION_POINTS);

                for (t=0; t < Grid -> InputChan; t++)
                        In[t] = (WORD) v;

                cmsDoTransform(h[0], In, Out, 1);
                for (j=1; j < nTransforms; j++)
                        cmsDoTransform(h[j], Out, Out, 1);

                for (t=0; t < Grid -> InputChan; t++)
                        Trans[t] ->GammaTable[i] = Out[t];

    }
    

    // Check transfer curves
    lIsSuitable = TRUE;
    for (t=0; (lIsSuitable && (t < Grid->InputChan)); t++) {

  
        // Exclude if already linear
        if (MostlyLinear(Trans[t]->GammaTable, PRELINEARIZATION_POINTS))
                    lIsSuitable = FALSE;
    }



    if (lIsSuitable) {

        // Some reality check -- Credits to Auke Nauta to discover some broken
        // profiles does not accept that on relative colorimetric intent

        if (ConvertCurvesToPureExponential(Trans, Grid -> InputChan))
                            cmsAllocLinearTable(Grid, Trans, 1);
    }
    

    for (t = 0; t < Grid ->InputChan; t++) 
                        cmsFreeGamma(Trans[t]);

}