File: rmimage.cpp

package info (click to toggle)
ruby-rmagick 6.0.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,232 kB
  • sloc: cpp: 19,563; ruby: 17,147; sh: 88; javascript: 36; makefile: 13
file content (16430 lines) | stat: -rw-r--r-- 518,757 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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
/**************************************************************************//**
 * Image class method definitions for RMagick.
 *
 * Copyright © 2002 - 2009 by Timothy P. Hunter
 *
 * Changes since Nov. 2009 copyright © by Benjamin Thomas and Omer Bar-or
 *
 * @file     rmimage.cpp
 * @version  $Id: rmimage.cpp,v 1.361 2010/05/03 03:34:48 baror Exp $
 * @author   Tim Hunter
 ******************************************************************************/

#include "rmagick.h"
#include <signal.h>

#define BEGIN_CHANNEL_MASK(image, channels) \
  { \
    ChannelType channel_mask = SetPixelChannelMask(image, (ChannelType)channels);

#define END_CHANNEL_MASK(image) \
    SetPixelChannelMask(image, channel_mask); \
  }

#define CHANGE_RESULT_CHANNEL_MASK(result) \
    if (result != (Image *)NULL) \
      SetPixelChannelMask(result, channel_mask);

#ifndef magick_module
    #define magick_module module
#endif

static VALUE cropper(int, int, VALUE *, VALUE);
static VALUE effect_image(VALUE, int, VALUE *, gvl_function_t);
static VALUE flipflop(int, VALUE, gvl_function_t);
static VALUE rd_image(VALUE, VALUE, gvl_function_t);
static VALUE rotate(int, int, VALUE *, VALUE);
static VALUE scale(int, int, VALUE *, VALUE, gvl_function_t);
static VALUE threshold_image(int, VALUE *, VALUE, gvl_function_t);
static VALUE xform_image(int, VALUE, VALUE, VALUE, VALUE, VALUE, gvl_function_t);
static VALUE array_from_images(Image *);
static VALUE file_arg_rescue(VALUE, VALUE ATTRIBUTE_UNUSED) ATTRIBUTE_NORETURN;
static size_t rm_image_memsize(const void *img);

const rb_data_type_t rm_image_data_type = {
    "Magick::Image",
    { NULL, rm_image_destroy, rm_image_memsize, },
    0, 0,
    RUBY_TYPED_FROZEN_SHAREABLE,
};

static const char *BlackPointCompensationKey = "PROFILE:black-point-compensation";


DEFINE_GVL_STUB4(AdaptiveBlurImage, const Image *, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB4(AdaptiveResizeImage, const Image *, const size_t, const size_t, ExceptionInfo *);
DEFINE_GVL_STUB4(AdaptiveSharpenImage, const Image *, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB5(AdaptiveThresholdImage, const Image *, const size_t, const size_t, const double, ExceptionInfo *);
DEFINE_GVL_STUB3(AffineTransformImage, const Image *, const AffineMatrix *, ExceptionInfo *);
DEFINE_GVL_STUB2(Base64Decode, const char *, size_t *);
DEFINE_GVL_STUB4(BlobToImage, const ImageInfo *, const void *, const size_t, ExceptionInfo *);
DEFINE_GVL_STUB3(BlueShiftImage, const Image *, const double, ExceptionInfo *);
DEFINE_GVL_STUB4(BlurImage, const Image *, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB4(CharcoalImage, const Image *, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB3(ChopImage, const Image *, const RectangleInfo *, ExceptionInfo *);
DEFINE_GVL_STUB3(ColorMatrixImage, const Image *, const KernelInfo *, ExceptionInfo *);
DEFINE_GVL_STUB3(CropImage, const Image *, const RectangleInfo *, ExceptionInfo *);
DEFINE_GVL_STUB3(DecipherImage, Image *, const char *, ExceptionInfo *);
DEFINE_GVL_STUB3(DeskewImage, const Image *, const double, ExceptionInfo *);
DEFINE_GVL_STUB2(DespeckleImage, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB6(DistortImage, const Image *, DistortMethod, const size_t, const double *, MagickBooleanType, ExceptionInfo *);
DEFINE_GVL_STUB3(EdgeImage, const Image *, const double, ExceptionInfo *);
DEFINE_GVL_STUB4(EmbossImage, const Image *, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB3(EncipherImage, Image *, const char *, ExceptionInfo *);
DEFINE_GVL_STUB2(EnhanceImage, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB3(ExcerptImage, const Image *, const RectangleInfo *, ExceptionInfo *);
DEFINE_GVL_STUB9(ExportImagePixels, const Image *, const ssize_t, const ssize_t, const size_t, const size_t, const char *, const StorageType, void *, ExceptionInfo *);
DEFINE_GVL_STUB3(ExtentImage, const Image *, const RectangleInfo *, ExceptionInfo *);
DEFINE_GVL_STUB2(FlipImage, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB2(FlopImage, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB4(GaussianBlurImage, const Image *, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB6(GetAuthenticPixels, Image *, const ssize_t, const ssize_t, const size_t, const size_t, ExceptionInfo *);
DEFINE_GVL_STUB2(GetImageDepth, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB3(GetImageHistogram, const Image *, size_t *, ExceptionInfo *);
DEFINE_GVL_STUB3(GetNumberColors, const Image *, FILE *, ExceptionInfo *);
DEFINE_GVL_STUB6(GetVirtualPixels, const Image *, const ssize_t, const ssize_t, const size_t, const size_t, ExceptionInfo *);
DEFINE_GVL_STUB4(ImageToBlob, const ImageInfo *, Image *, size_t *, ExceptionInfo *);
DEFINE_GVL_STUB6(LiquidRescaleImage, const Image *, const size_t, const size_t, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB2(MagnifyImage, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB2(MinifyImage, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB5(MotionBlurImage, const Image *, const double, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB2(PingImage, const ImageInfo *, ExceptionInfo *);
DEFINE_GVL_STUB3(PreviewImage, const Image *, const PreviewType, ExceptionInfo *);
DEFINE_GVL_STUB2(ReadImage, const ImageInfo *, ExceptionInfo *);
DEFINE_GVL_STUB4(RollImage, const Image *, const ssize_t, const ssize_t, ExceptionInfo *);
DEFINE_GVL_STUB3(RotateImage, const Image *, const double, ExceptionInfo *);
DEFINE_GVL_STUB4(SampleImage, const Image *, const size_t, const size_t, ExceptionInfo *);
DEFINE_GVL_STUB4(ScaleImage, const Image *, const size_t, const size_t, ExceptionInfo *);
DEFINE_GVL_STUB3(SepiaToneImage, const Image *, const double, ExceptionInfo *);
DEFINE_GVL_STUB5(ShadeImage, const Image *, const MagickBooleanType, const double, const double,ExceptionInfo *);
DEFINE_GVL_STUB6(ShadowImage, const Image *, const double, const double, const ssize_t, const ssize_t,  ExceptionInfo *);
DEFINE_GVL_STUB4(SharpenImage, const Image *, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB3(ShaveImage, const Image *, const RectangleInfo *, ExceptionInfo *);
DEFINE_GVL_STUB4(ShearImage, const Image *, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB5(SketchImage, const Image *, const double, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB3(SpliceImage, const Image *, const RectangleInfo *, ExceptionInfo *);
DEFINE_GVL_STUB5(StatisticImage, const Image *, const StatisticType, const size_t, const size_t, ExceptionInfo *);
DEFINE_GVL_STUB3(SteganoImage, const Image *, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB3(StereoImage, const Image *, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB2(SyncAuthenticPixels, Image *, ExceptionInfo *);
DEFINE_GVL_STUB4(ThumbnailImage, const Image *, const size_t, const size_t, ExceptionInfo *);
DEFINE_GVL_STUB2(TransposeImage, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB2(TransverseImage, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB2(TrimImage, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB2(UniqueImageColors, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB6(UnsharpMaskImage, const Image *, const double, const double, const double, const double,  ExceptionInfo *);
DEFINE_GVL_STUB6(VignetteImage, const Image *, const double, const double, const ssize_t, const ssize_t, ExceptionInfo *);
#if defined(IMAGEMAGICK_7)
DEFINE_GVL_STUB4(AddNoiseImage, const Image *, const NoiseType, const double, ExceptionInfo *);
DEFINE_GVL_STUB2(AutoGammaImage, Image *, ExceptionInfo *);
DEFINE_GVL_STUB2(AutoLevelImage, Image *, ExceptionInfo *);
DEFINE_GVL_STUB3(BilevelImage, Image *, const double, ExceptionInfo *);
DEFINE_GVL_STUB3(BlackThresholdImage, Image *, const char *, ExceptionInfo *);
DEFINE_GVL_STUB4(BorderImage, const Image *, const RectangleInfo *, const CompositeOperator, ExceptionInfo *);
DEFINE_GVL_STUB4(ClutImage, Image *, const Image *, const PixelInterpolateMethod, ExceptionInfo *);
DEFINE_GVL_STUB4(ColorizeImage, const Image *, const char *, const PixelInfo *, ExceptionInfo *);
DEFINE_GVL_STUB5(CompareImages, Image *, const Image *, const MetricType, double *, ExceptionInfo *);
DEFINE_GVL_STUB7(CompositeImage, Image *, const Image *, const CompositeOperator, const MagickBooleanType, const ssize_t, const ssize_t, ExceptionInfo *);
DEFINE_GVL_STUB2(CompressImageColormap, Image *, ExceptionInfo *);
DEFINE_GVL_STUB3(ContrastImage, Image *, const MagickBooleanType, ExceptionInfo *);
DEFINE_GVL_STUB4(ContrastStretchImage, Image *, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB3(ConvolveImage, const Image *, const KernelInfo *, ExceptionInfo *);
DEFINE_GVL_STUB3(CycleColormapImage, Image *, const ssize_t, ExceptionInfo *);
DEFINE_GVL_STUB4(DrawAffineImage, Image *, const Image *, const AffineMatrix *, ExceptionInfo *);
DEFINE_GVL_STUB2(EqualizeImage, Image *, ExceptionInfo *);
DEFINE_GVL_STUB4(EvaluateImage, Image *, const MagickEvaluateOperator, const double, ExceptionInfo *);
DEFINE_GVL_STUB7(FloodfillPaintImage, Image *, const DrawInfo *, const PixelInfo *, const ssize_t, const ssize_t, const MagickBooleanType, ExceptionInfo *);
DEFINE_GVL_STUB4(FrameImage, const Image *, const FrameInfo *, const CompositeOperator, ExceptionInfo *);
DEFINE_GVL_STUB5(FunctionImage, Image *, const MagickFunction, const size_t, const double *, ExceptionInfo *);
DEFINE_GVL_STUB3(FxImage, const Image *, const char *, ExceptionInfo *);
DEFINE_GVL_STUB3(GammaImage, Image *, const double, ExceptionInfo *);
DEFINE_GVL_STUB5(GetImageDistortion, Image *, const Image *, const MetricType, double *, ExceptionInfo *);
DEFINE_GVL_STUB3(GetImageEntropy, const Image *, double *, ExceptionInfo *);
DEFINE_GVL_STUB4(GetImageExtrema, const Image *, size_t *, size_t *, ExceptionInfo *);
DEFINE_GVL_STUB3(GetImageMask, const Image *, const PixelMask, ExceptionInfo *);
DEFINE_GVL_STUB4(GetImageMean, const Image *, double *, double *, ExceptionInfo *);
DEFINE_GVL_STUB4(ImplodeImage, const Image *, const double, const PixelInterpolateMethod, ExceptionInfo *);
DEFINE_GVL_STUB9(ImportImagePixels, Image *, const ssize_t, const ssize_t, const size_t, const size_t, const char *, const StorageType, const void *, ExceptionInfo *);
DEFINE_GVL_STUB5(IsEquivalentImage, const Image *, const Image *, ssize_t *, ssize_t *, ExceptionInfo *);
DEFINE_GVL_STUB5(LevelImage, Image *, const double, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB5(LevelImageColors, Image *, const PixelInfo *, const PixelInfo *, const MagickBooleanType, ExceptionInfo *);
DEFINE_GVL_STUB5(LevelizeImage, Image *, const double, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB4(LinearStretchImage, Image *, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB3(ModulateImage, Image *, const char *, ExceptionInfo *);
DEFINE_GVL_STUB5(MorphologyImage, const Image *, const MorphologyMethod, const ssize_t, const KernelInfo *, ExceptionInfo *);
DEFINE_GVL_STUB3(NegateImage, Image *, const MagickBooleanType, ExceptionInfo *);
DEFINE_GVL_STUB2(NormalizeImage, Image *, ExceptionInfo *);
DEFINE_GVL_STUB4(OilPaintImage, const Image *, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB5(OpaquePaintImage, Image *, const PixelInfo *, const PixelInfo *, const MagickBooleanType, ExceptionInfo *);
DEFINE_GVL_STUB3(OrderedDitherImage, Image *, const char *, ExceptionInfo *);
DEFINE_GVL_STUB6(PolaroidImage, const Image *, const DrawInfo *, const char *, const double, const PixelInterpolateMethod, ExceptionInfo *);
DEFINE_GVL_STUB4(PosterizeImage, Image *, const size_t, const DitherMethod, ExceptionInfo *);
DEFINE_GVL_STUB5(ProfileImage, Image *, const char *, const void *, const size_t, ExceptionInfo *);
DEFINE_GVL_STUB3(QuantizeImage, const QuantizeInfo *, Image *, ExceptionInfo *);
DEFINE_GVL_STUB4(RaiseImage, Image *, const RectangleInfo *, const MagickBooleanType, ExceptionInfo *);
DEFINE_GVL_STUB4(RandomThresholdImage, Image *, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB4(RemapImage, const QuantizeInfo *, Image *, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB5(ResampleImage, const Image *, const double, const double, const FilterType, ExceptionInfo *);
DEFINE_GVL_STUB5(ResizeImage, const Image *, const size_t, const size_t, const FilterType, ExceptionInfo *);
DEFINE_GVL_STUB6(SegmentImage, Image *, const ColorspaceType, const MagickBooleanType, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB5(SelectiveBlurImage, const Image *, const double, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB3(SeparateImage, const Image *, const ChannelType, ExceptionInfo *);
DEFINE_GVL_STUB2(SeparateImages, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB3(SetImageAlphaChannel, Image *, const AlphaChannelOption, ExceptionInfo *);
DEFINE_GVL_STUB2(SetImageBackgroundColor, Image *, ExceptionInfo *);
DEFINE_GVL_STUB3(SetImageDepth, Image *, const size_t, ExceptionInfo *);
DEFINE_GVL_STUB4(SetImageExtent, Image *, const size_t, const size_t, ExceptionInfo *);
DEFINE_GVL_STUB4(SetImageMask, Image *, const PixelMask, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB3(SetImageStorageClass, Image *, const ClassType, ExceptionInfo *);
DEFINE_GVL_STUB5(SigmoidalContrastImage, Image *, const MagickBooleanType, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB2(SignatureImage, Image *, ExceptionInfo *);
DEFINE_GVL_STUB3(SolarizeImage, Image *, const double, ExceptionInfo *);
DEFINE_GVL_STUB5(SparseColorImage, const Image *, const SparseColorMethod, const size_t, const double *, ExceptionInfo *);
DEFINE_GVL_STUB4(SpreadImage, const Image *, const PixelInterpolateMethod, const double, ExceptionInfo *);
DEFINE_GVL_STUB4(SwirlImage, const Image *, double, const PixelInterpolateMethod, ExceptionInfo *);
DEFINE_GVL_STUB2(SyncImage, Image *, ExceptionInfo *);
DEFINE_GVL_STUB4(TintImage, const Image *, const char *, const PixelInfo *, ExceptionInfo *);
DEFINE_GVL_STUB3(TransformImageColorspace, Image *, const ColorspaceType, ExceptionInfo *);
DEFINE_GVL_STUB5(TransparentPaintImage, Image *, const PixelInfo *, const Quantum, const MagickBooleanType, ExceptionInfo *);
DEFINE_GVL_STUB6(TransparentPaintImageChroma, Image *, const PixelInfo *, const PixelInfo *, const Quantum, const MagickBooleanType, ExceptionInfo *);
DEFINE_GVL_STUB5(WaveImage, const Image *, const double, const double, const PixelInterpolateMethod, ExceptionInfo *);
DEFINE_GVL_STUB3(WhiteThresholdImage, Image *, const char *, ExceptionInfo *);
DEFINE_GVL_STUB3(WriteImage, const ImageInfo *, Image *, ExceptionInfo *);
#else
DEFINE_GVL_STUB5(AdaptiveBlurImageChannel, const Image *, const ChannelType, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB5(AdaptiveSharpenImageChannel, const Image *, const ChannelType, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB3(AddNoiseImage, const Image *, const NoiseType, ExceptionInfo *);
DEFINE_GVL_STUB4(AddNoiseImageChannel, const Image *, const ChannelType, const NoiseType, ExceptionInfo *);
DEFINE_GVL_STUB2(AutoGammaImageChannel, Image *, const ChannelType);
DEFINE_GVL_STUB2(AutoLevelImageChannel,Image *, const ChannelType);
DEFINE_GVL_STUB3(BilevelImageChannel, Image *, const ChannelType,const double);
DEFINE_GVL_STUB2(BlackThresholdImage, Image *, const char *);
DEFINE_GVL_STUB5(BlurImageChannel, const Image *, const ChannelType, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB3(BorderImage, const Image *, const RectangleInfo *, ExceptionInfo *);
DEFINE_GVL_STUB3(ClutImageChannel, Image *, const ChannelType, const Image *);
DEFINE_GVL_STUB4(ColorizeImage, const Image *, const char *, const PixelPacket, ExceptionInfo *);
DEFINE_GVL_STUB6(CompareImageChannels, Image *, const Image *, const ChannelType, const MetricType, double *, ExceptionInfo *);
DEFINE_GVL_STUB5(CompositeImage, Image *, const CompositeOperator, const Image *, const ssize_t, const ssize_t);
DEFINE_GVL_STUB6(CompositeImageChannel, Image *, const ChannelType, const CompositeOperator, const Image *, const ssize_t, const ssize_t);
DEFINE_GVL_STUB1(CompressImageColormap, Image *);
DEFINE_GVL_STUB2(ContrastImage, Image *, const MagickBooleanType);
DEFINE_GVL_STUB4(ContrastStretchImageChannel, Image *, const ChannelType, const double, const double);
DEFINE_GVL_STUB4(ConvolveImage, const Image *, const size_t, const double *, ExceptionInfo *);
DEFINE_GVL_STUB5(ConvolveImageChannel, const Image *, const ChannelType, const size_t, const double *, ExceptionInfo *);
DEFINE_GVL_STUB2(CycleColormapImage, Image *, const ssize_t);
DEFINE_GVL_STUB3(DrawAffineImage, Image *, const Image *, const AffineMatrix *);
DEFINE_GVL_STUB1(EqualizeImage, Image *);
DEFINE_GVL_STUB2(EqualizeImageChannel, Image *, const ChannelType);
DEFINE_GVL_STUB5(EvaluateImageChannel, Image *, const ChannelType, const MagickEvaluateOperator, const double, ExceptionInfo *);
DEFINE_GVL_STUB7(FloodfillPaintImage, Image *, const ChannelType, const DrawInfo *, const MagickPixelPacket *, const ssize_t, const ssize_t, const MagickBooleanType);
DEFINE_GVL_STUB3(FrameImage, const Image *, const FrameInfo *, ExceptionInfo *);
DEFINE_GVL_STUB6(FunctionImageChannel, Image *, const ChannelType, const MagickFunction, const size_t, const double *, ExceptionInfo *);
DEFINE_GVL_STUB4(FxImageChannel, const Image *, const ChannelType, const char *, ExceptionInfo *);
DEFINE_GVL_STUB3(GammaImageChannel, Image *, const ChannelType, const double);
DEFINE_GVL_STUB5(GaussianBlurImageChannel, const Image *, const ChannelType, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB3(GetImageChannelDepth, const Image *, const ChannelType, ExceptionInfo *);
DEFINE_GVL_STUB6(GetImageChannelDistortion, Image *, const Image *, const ChannelType, const MetricType, double *, ExceptionInfo *);
DEFINE_GVL_STUB5(GetImageChannelExtrema, const Image *, const ChannelType, size_t *, size_t *, ExceptionInfo *);
DEFINE_GVL_STUB5(GetImageChannelMean, const Image *, const ChannelType, double *, double *, ExceptionInfo *);
DEFINE_GVL_STUB2(GetImageClipMask, const Image *, ExceptionInfo *);
DEFINE_GVL_STUB3(ImplodeImage, const Image *, const double, ExceptionInfo *);
DEFINE_GVL_STUB8(ImportImagePixels, Image *, const ssize_t, const ssize_t, const size_t,const size_t,const char *, const StorageType, const void *);
DEFINE_GVL_STUB5(IsImageSimilar, const Image *, const Image *, ssize_t *, ssize_t *, ExceptionInfo *);
DEFINE_GVL_STUB2(IsImagesEqual, Image *, const Image *);
DEFINE_GVL_STUB5(LevelColorsImageChannel, Image *, const ChannelType, const MagickPixelPacket *, const MagickPixelPacket *, const MagickBooleanType);
DEFINE_GVL_STUB2(LevelImage, Image *, const char *);
DEFINE_GVL_STUB5(LevelImageChannel, Image *, const ChannelType, const double, const double, const double);
DEFINE_GVL_STUB5(LevelizeImageChannel, Image *, const ChannelType, const double, const double, const double);
DEFINE_GVL_STUB3(LinearStretchImage, Image *, const double, const double);
DEFINE_GVL_STUB2(ModulateImage, Image *, const char *);
DEFINE_GVL_STUB6(MorphologyImageChannel, const Image *, const ChannelType, const MorphologyMethod, const ssize_t, const KernelInfo *, ExceptionInfo *);
DEFINE_GVL_STUB2(NegateImage, Image *, const MagickBooleanType);
DEFINE_GVL_STUB3(NegateImageChannel, Image *, const ChannelType, const MagickBooleanType);
DEFINE_GVL_STUB1(NormalizeImage, Image *);
DEFINE_GVL_STUB2(NormalizeImageChannel, Image *, const ChannelType);
DEFINE_GVL_STUB3(OilPaintImage, const Image *, const double, ExceptionInfo *);
DEFINE_GVL_STUB5(OpaquePaintImageChannel, Image *, const ChannelType, const MagickPixelPacket *, const MagickPixelPacket *, const MagickBooleanType);
DEFINE_GVL_STUB3(OrderedPosterizeImage, Image *, const char *, ExceptionInfo *);
DEFINE_GVL_STUB4(PolaroidImage, const Image *, const DrawInfo *, const double, ExceptionInfo *);
DEFINE_GVL_STUB3(PosterizeImage, Image *, const size_t, const MagickBooleanType);
DEFINE_GVL_STUB5(ProfileImage, Image *, const char *, const void *, const size_t, const MagickBooleanType);
DEFINE_GVL_STUB2(QuantizeImage, const QuantizeInfo *, Image *);
DEFINE_GVL_STUB3(RaiseImage, Image *, const RectangleInfo *, const MagickBooleanType);
DEFINE_GVL_STUB4(RandomThresholdImageChannel, Image *, const ChannelType, const char *, ExceptionInfo *);
DEFINE_GVL_STUB3(RemapImage, const QuantizeInfo *, Image *, const Image *);
DEFINE_GVL_STUB6(ResampleImage, const Image *, const double, const double, const FilterTypes, const double, ExceptionInfo *);
DEFINE_GVL_STUB6(ResizeImage, const Image *, const size_t, const size_t, const FilterTypes, const double, ExceptionInfo *);
DEFINE_GVL_STUB5(SegmentImage, Image *, const ColorspaceType, const MagickBooleanType, const double, const double);
DEFINE_GVL_STUB6(SelectiveBlurImageChannel, const Image *, const ChannelType, const double, const double,  const double, ExceptionInfo *);
DEFINE_GVL_STUB2(SeparateImageChannel, Image *, const ChannelType);
DEFINE_GVL_STUB3(SeparateImages, const Image *, const ChannelType, ExceptionInfo *);
DEFINE_GVL_STUB2(SetImageAlphaChannel, Image *, const AlphaChannelType);
DEFINE_GVL_STUB1(SetImageBackgroundColor, Image *);
DEFINE_GVL_STUB3(SetImageChannelDepth, Image *, const ChannelType, const size_t);
DEFINE_GVL_STUB2(SetImageClipMask, Image *, const Image *);
DEFINE_GVL_STUB2(SetImageDepth, Image *, const size_t);
DEFINE_GVL_STUB3(SetImageExtent, Image *, const size_t, const size_t);
DEFINE_GVL_STUB2(SetImageMask, Image *, const Image *);
DEFINE_GVL_STUB2(SetImageStorageClass, Image *, const ClassType);
DEFINE_GVL_STUB5(SharpenImageChannel, const Image *, const ChannelType, const double, const double,  ExceptionInfo *);
DEFINE_GVL_STUB5(SigmoidalContrastImageChannel, Image *, const ChannelType, const MagickBooleanType, const double, const double);
DEFINE_GVL_STUB1(SignatureImage, Image *);
DEFINE_GVL_STUB2(SolarizeImage, Image *, const double);
DEFINE_GVL_STUB6(SparseColorImage, const Image *, const ChannelType, const SparseColorMethod, const size_t, const double *, ExceptionInfo *);
DEFINE_GVL_STUB3(SpreadImage, const Image *, const double, ExceptionInfo *);
DEFINE_GVL_STUB3(SwirlImage, const Image *, double, ExceptionInfo *);
DEFINE_GVL_STUB1(SyncImage, Image *);
DEFINE_GVL_STUB4(TintImage, const Image *, const char *, const PixelPacket, ExceptionInfo *);
DEFINE_GVL_STUB2(TransformImageColorspace, Image *, const ColorspaceType);
DEFINE_GVL_STUB4(TransparentPaintImage, Image *, const MagickPixelPacket *, const Quantum, const MagickBooleanType);
DEFINE_GVL_STUB5(TransparentPaintImageChroma, Image *, const MagickPixelPacket *, const MagickPixelPacket *, const Quantum, const MagickBooleanType);
DEFINE_GVL_STUB7(UnsharpMaskImageChannel, const Image *, const ChannelType, const double, const double,  const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB4(WaveImage, const Image *, const double, const double, ExceptionInfo *);
DEFINE_GVL_STUB2(WhiteThresholdImage, Image *, const char *);
DEFINE_GVL_STUB2(WriteImage, const ImageInfo *, Image *);
#endif

#if defined(HAVE_GETIMAGECHANNELENTROPY)
DEFINE_GVL_STUB4(GetImageChannelEntropy, const Image *, const ChannelType, double *, ExceptionInfo *);
#endif

DEFINE_GVL_STUB3(RotationalBlurImage, const Image *, const double, ExceptionInfo *);

#if defined(IMAGEMAGICK_7)
#else
DEFINE_GVL_STUB4(RotationalBlurImageChannel, const Image *, const ChannelType, const double, ExceptionInfo *);
#endif

/**
 * Returns the alpha value from the hash.
 *
 * No Ruby usage (internal function)
 *
 * @hash the hash
 */
static Quantum
get_named_alpha_value(VALUE hash)
{
    if (TYPE(hash) != T_HASH)
    {
        rb_raise(rb_eArgError, "missing keyword: alpha");
    }

    if (FIX2ULONG(rb_hash_size(hash)) != 1)
    {
        rb_raise(rb_eArgError, "wrong number of arguments");
    }

    VALUE alpha = rb_hash_aref(hash, ID2SYM(rb_intern("alpha")));
    if (NIL_P(alpha))
    {
        rb_raise(rb_eArgError, "missing keyword: alpha");
    }

    return APP2QUANTUM(alpha);
}


// aliases for common use of structure types; AdaptiveBlurImage, AdaptiveSharpenImage
typedef GVL_STRUCT_TYPE(AdaptiveBlurImage) GVL_STRUCT_TYPE(adaptive_method);

/**
 * Call Adaptive(Blur|Sharpen)Image.
 *
 * No Ruby usage (internal function)
 *
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @param fp pointer to the function to call
 * @return a new image
 */
static VALUE
adaptive_method(int argc, VALUE *argv, VALUE self, gvl_function_t fp)
{
    Image *image, *new_image;
    double radius = 0.0;
    double sigma = 1.0;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 2:
            sigma = NUM2DBL(argv[1]);
        case 1:
            radius = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 2)", argc);
            break;
    }

    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(adaptive_method) args = { image, radius, sigma, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(fp, &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


// aliases for common use of structure types; AdaptiveBlurImage, AdaptiveSharpenImage, AdaptiveBlurImageChannel, AdaptiveSharpenImageChannel
#if defined(IMAGEMAGICK_7)
typedef GVL_STRUCT_TYPE(AdaptiveBlurImage) GVL_STRUCT_TYPE(adaptive_channel_method);
#else
typedef GVL_STRUCT_TYPE(AdaptiveBlurImageChannel) GVL_STRUCT_TYPE(adaptive_channel_method);
#endif

/**
 * Call Adaptive(Blur|Sharpen)ImageChannel.
 *
 * No Ruby usage (internal function)
 *
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @param fp pointer to the function to call
 * @return a new image
 */
static VALUE
adaptive_channel_method(int argc, VALUE *argv, VALUE self, gvl_function_t fp)
{
    Image *image, *new_image;
    double radius = 0.0;
    double sigma = 1.0;
    ExceptionInfo *exception;
    ChannelType channels;

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    switch (argc)
    {
        case 2:
            sigma = NUM2DBL(argv[1]);
        case 1:
            radius = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            raise_ChannelType_error(argv[argc-1]);
            break;
    }

    exception = AcquireExceptionInfo();

#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(adaptive_channel_method) args = { image, radius, sigma, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(fp, &args);
    CHANGE_RESULT_CHANNEL_MASK(new_image);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(adaptive_channel_method) args = { image, channels, radius, sigma, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(fp, &args);
#endif

    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Adaptively blurs the image by blurring more intensely near image edges and less intensely far
 * from edges. The {Magick::Image#adaptive_blur} method blurs the image with a Gaussian operator of
 * the given radius and standard deviation (sigma). For reasonable results, radius should be larger
 * than sigma. Use a radius of 0 and adaptive_blur selects a suitable radius for you.
 *
 * @overload adaptive_blur(radius = 0.0, sigma = 1.0)
 *   @param radius [Numeric] The radius of the Gaussian in pixels, not counting the center pixel.
 *   @param sigma [Numeric] The standard deviation of the Laplacian, in pixels.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_adaptive_blur(int argc, VALUE *argv, VALUE self)
{
    return adaptive_method(argc, argv, self, GVL_FUNC(AdaptiveBlurImage));
}


/**
 * The same as {Magick::Image#adaptive_blur} except only the specified channels are blurred.
 *
 * @overload adaptive_blur_channel(radius = 0.0, sigma = 1.0, channel = Magick::AllChannels)
 *   @param radius [Numeric] The radius of the Gaussian in pixels, not counting the center pixel.
 *   @param sigma [Numeric] The standard deviation of the Laplacian, in pixels.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload adaptive_blur_channel(radius = 0.0, sigma = 1.0, *channels)
 *   @param radius [Numeric] The radius of the Gaussian in pixels, not counting the center pixel.
 *   @param sigma [Numeric] The standard deviation of the Laplacian, in pixels.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_adaptive_blur_channel(int argc, VALUE *argv, VALUE self)
{
#if defined(IMAGEMAGICK_7)
    return adaptive_channel_method(argc, argv, self, GVL_FUNC(AdaptiveBlurImage));
#else
    return adaptive_channel_method(argc, argv, self, GVL_FUNC(AdaptiveBlurImageChannel));
#endif
}


/**
 * Resizes the image with data dependent triangulation.
 *
 * @overload adaptive_resize(scale_val)
 *   @param scale_val [Numeric] You can use this argument instead of specifying the desired width and
 *     height. The percentage size change. For example, 1.25 makes the new image 125% of the size of
 *     the receiver.
 *
 * @overload adaptive_resize(cols, rows)
 *   @param cols [Numeric] The desired column size
 *   @param rows [Numeric] The desired row size.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_adaptive_resize(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    unsigned long rows, columns;
    double scale_val, drows, dcols;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 2:
            rows = NUM2ULONG(argv[1]);
            columns = NUM2ULONG(argv[0]);
            break;
        case 1:
            scale_val = NUM2DBL(argv[0]);
            if (scale_val < 0.0)
            {
                rb_raise(rb_eArgError, "invalid scale_val value (%g given)", scale_val);
            }
            drows = scale_val * image->rows + 0.5;
            dcols = scale_val * image->columns + 0.5;
            if (drows > (double)ULONG_MAX || dcols > (double)ULONG_MAX)
            {
                rb_raise(rb_eRangeError, "resized image too big");
            }
            rows = (unsigned long) drows;
            columns = (unsigned long) dcols;
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or 2)", argc);
            break;
    }

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(AdaptiveResizeImage) args = { image, columns, rows, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(AdaptiveResizeImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Adaptively sharpens the image by sharpening more intensely near image edges and less intensely
 * far from edges.
 *
 * The {Magick::Image#adaptive_sharpen} method sharpens the image with a Gaussian operator of the
 * given radius and standard deviation (sigma).
 *
 * For reasonable results, radius should be larger than sigma.
 * Use a radius of 0 and adaptive_sharpen selects a suitable radius for you.
 *
 * @overload adaptive_sharpen(radius = 0.0, sigma = 1.0)
 *   @param radius [Numeric] The radius of the Gaussian in pixels, not counting the center pixel.
 *   @param sigma [Numeric] The standard deviation of the Laplacian, in pixels.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_adaptive_sharpen(int argc, VALUE *argv, VALUE self)
{
    return adaptive_method(argc, argv, self, GVL_FUNC(AdaptiveSharpenImage));
}


/**
 * The same as {Magick::Image#adaptive_sharpen} except only the specified channels are sharpened.
 *
 * @overload adaptive_sharpen_channel(radius = 0.0, sigma = 1.0, channel = Magick::AllChannels)
 *   @param radius [Numeric] The radius of the Gaussian in pixels, not counting the center pixel.
 *   @param sigma [Numeric] The standard deviation of the Laplacian, in pixels.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload adaptive_sharpen_channel(radius = 0.0, sigma = 1.0, *channels)
 *   @param radius [Numeric] The radius of the Gaussian in pixels, not counting the center pixel.
 *   @param sigma [Numeric] The standard deviation of the Laplacian, in pixels.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_adaptive_sharpen_channel(int argc, VALUE *argv, VALUE self)
{
#if defined(IMAGEMAGICK_7)
    return adaptive_channel_method(argc, argv, self, GVL_FUNC(AdaptiveSharpenImage));
#else
    return adaptive_channel_method(argc, argv, self, GVL_FUNC(AdaptiveSharpenImageChannel));
#endif
}


/**
 * Selects an individual threshold for each pixel based on the range of intensity values in its
 * local neighborhood. This allows for thresholding of an image whose global intensity histogram
 * doesn't contain distinctive peaks.
 *
 * @overload adaptive_threshold(width = 3, height = 3, bias = 0)
 *   @param width [Numeric] the width of the local neighborhood.
 *   @param height [Numeric] the height of the local neighborhood.
 *   @param bias [Numeric] the mean offset
 *   @return [Magick::Image] a new image
 */
VALUE
Image_adaptive_threshold(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    unsigned long width = 3, height = 3;
    double bias = 0;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 3:
            bias = NUM2DBL(argv[2]);
        case 2:
            height = NUM2ULONG(argv[1]);
        case 1:
            width  = NUM2ULONG(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 3)", argc);
    }

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(AdaptiveThresholdImage) args = { image, width, height, bias, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(AdaptiveThresholdImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Associates a mask with an image that will be used as the destination image in a
 * {Magick::Image#composite} operation.
 *
 * The areas of the destination image that are masked by white pixels will be modified by the
 * {Magick::Image#composite} method, while areas masked by black pixels are unchanged.
 *
 * @param mask [Magick::Image, Magick::ImageList] the composite mask
 * @see Image#mask
 * @see Image#delete_compose_mask
 */
VALUE
Image_add_compose_mask(VALUE self, VALUE mask)
{
    Image *image, *mask_image = NULL;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
    Image *clip_mask = NULL;
#endif

    image = rm_check_frozen(self);
    mask_image = rm_check_destroyed(rm_cur_image(mask));
    if (image->columns != mask_image->columns || image->rows != mask_image->rows)
    {
        rb_raise(rb_eArgError, "mask must be the same size as image");
    }

#if defined(IMAGEMAGICK_7)
    clip_mask = rm_clone_image(mask_image);

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(NegateImage) args_NegateImage = { clip_mask, MagickFalse, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(NegateImage), &args_NegateImage);
    rm_check_exception(exception, clip_mask, DestroyOnError);
    GVL_STRUCT_TYPE(SetImageMask) args_SetImageMask = { image, CompositePixelMask, clip_mask, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageMask), &args_SetImageMask);
    DestroyImage(clip_mask);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    // Delete any previously-existing mask image.
    // Store a clone of the new mask image.
    GVL_STRUCT_TYPE(SetImageMask) args_SetImageMask = { image, mask_image };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageMask), &args_SetImageMask);
    GVL_STRUCT_TYPE(NegateImage) args_NegateImage = { image->mask, MagickFalse };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(NegateImage), &args_NegateImage);

    // Since both Set and GetImageMask clone the mask image I don't see any
    // way to negate the mask without referencing it directly. Sigh.
#endif

    return self;
}


/**
 * Adds random noise to the image.
 *
 * @param noise [Magick::NoiseType] the noise
 * @return [Magick::Image] a new image
 */
VALUE
Image_add_noise(VALUE self, VALUE noise)
{
    Image *image, *new_image;
    NoiseType noise_type;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    VALUE_TO_ENUM(noise, noise_type, NoiseType);

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(AddNoiseImage) args = { image, noise_type, 1.0, exception };
#else
    GVL_STRUCT_TYPE(AddNoiseImage) args = { image, noise_type, exception };
#endif
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(AddNoiseImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}

/**
 * Adds random noise to the specified channel or channels in the image.
 *
 * @overload add_noise_channel(noise_type, channel = Magick::AllChannels)
 *   @param noise [Magick::NoiseType] the noise
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload add_noise_channel(noise_type, *channels)
 *   @param noise [Magick::NoiseType] the noise
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_add_noise_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    NoiseType noise_type;
    ExceptionInfo *exception;
    ChannelType channels;

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    // There must be 1 remaining argument.
    if (argc == 0)
    {
        rb_raise(rb_eArgError, "missing noise type argument");
    }
    else if (argc > 1)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    VALUE_TO_ENUM(argv[0], noise_type, NoiseType);
    channels = (ChannelType)(channels & ~OpacityChannel);

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(AddNoiseImage) args = { image, noise_type, 1.0, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(AddNoiseImage), &args);
    END_CHANNEL_MASK(new_image);
#else
    GVL_STRUCT_TYPE(AddNoiseImageChannel) args = { image, channels, noise_type, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(AddNoiseImageChannel), &args);
#endif
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Adds an ICC (a.k.a. ICM), IPTC, or generic profile. If the file contains more than one profile
 * all the profiles are added.
 *
 * @param name [String] The filename of a file containing the profile.
 * @return [Magick::Image] self
 */
VALUE
Image_add_profile(VALUE self, VALUE name)
{
    // ImageMagick code based on the code for the "-profile" option in mogrify.c
    Image *image, *profile_image;
    ImageInfo *info;
    ExceptionInfo *exception;
    char *profile_name;
    char *profile_filename = NULL;
    const StringInfo *profile;

    image = rm_check_frozen(self);

    // ProfileImage issues a warning if something goes wrong.
    profile_filename = StringValueCStr(name);

    info = CloneImageInfo(NULL);
    if (!info)
    {
        rb_raise(rb_eNoMemError, "not enough memory to continue");
    }
    profile = GetImageProfile(image, "iptc");
    if (profile)
    {
        info->profile = (void *)CloneStringInfo(profile);
    }
    strlcpy(info->filename, profile_filename, sizeof(info->filename));

    exception = AcquireExceptionInfo();
    profile_image = ReadImage(info, exception);
    DestroyImageInfo(info);
    rm_check_exception(exception, profile_image, DestroyOnError);
    rm_ensure_result(profile_image);

    ResetImageProfileIterator(profile_image);
    profile_name = GetNextImageProfile(profile_image);
    while (profile_name)
    {
        profile = GetImageProfile(profile_image, profile_name);
        if (profile)
        {
#if defined(IMAGEMAGICK_7)
            GVL_STRUCT_TYPE(ProfileImage) args = { image, profile_name, GetStringInfoDatum(profile), GetStringInfoLength(profile), exception };
            CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ProfileImage), &args);
            if (rm_should_raise_exception(exception, RetainExceptionRetention))
#else
            GVL_STRUCT_TYPE(ProfileImage) args = { image, profile_name, GetStringInfoDatum(profile), GetStringInfoLength(profile), MagickFalse };
            CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ProfileImage), &args);
            if (rm_should_raise_exception(&image->exception, RetainExceptionRetention))
#endif
            {
                break;
            }
        }
        profile_name = GetNextImageProfile(profile_image);
    }

    DestroyImage(profile_image);
#if defined(IMAGEMAGICK_7)
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    DestroyExceptionInfo(exception);
    rm_check_image_exception(image, RetainOnError);
#endif

    return self;
}



/**
 * Get/Set alpha channel.
 *
 * @overload alpha()
 *   Returns true if the alpha channel will be used, false otherwise.
 *   This calling is same as {Magick::Image#alpha?}.
 *   @return [Boolean] true or false
 *   @see Image#alpha?
 *
 * @overload alpha(value)
 *   Activates, deactivates, resets, or sets the alpha channel.
 *   @param value [Magick::AlphaChannelOption] An AlphaChannelOption value
 *   @return [Magick::AlphaChannelOption] the given value
 *
 * - Replaces {Magick::Image#matte=}, {Magick::Image#alpha=}
 * - Originally there was an alpha attribute getter and setter. These are replaced with alpha? and
 *   alpha(type). We still define (but don't document) alpha=. For backward compatibility, if this
 *   method is called without an argument, make it act like the old alpha getter and return true if
 *   the matte channel is active, false otherwise.
 *
 */
VALUE
Image_alpha(int argc, VALUE *argv, VALUE self)
{
    Image *image;
    AlphaChannelOption alpha;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif


    // For backward compatibility, make alpha() act like alpha?
    if (argc == 0)
    {
        return Image_alpha_q(self);
    }
    else if (argc > 1)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc);
    }


    image = rm_check_frozen(self);
    VALUE_TO_ENUM(argv[0], alpha, AlphaChannelOption);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(SetImageAlphaChannel) args = { image, alpha, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageAlphaChannel), &args);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(SetImageAlphaChannel) args = { image, alpha };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageAlphaChannel), &args);
    rm_check_image_exception(image, RetainOnError);
#endif

    return argv[0];
}



/**
 * Determine whether the image's alpha channel is activated.
 *
 * @return [Boolean] true if the image's alpha channel is activated
 */
VALUE
Image_alpha_q(VALUE self)
{
    Image *image = rm_check_destroyed(self);
#if defined(IMAGEMAGICK_7)
    return image->alpha_trait == BlendPixelTrait ? Qtrue : Qfalse;
#else
    return GetImageAlphaChannel(image) ? Qtrue : Qfalse;
#endif
}


/**
 * Transform an image as dictated by the affine matrix argument.
 *
 * @param affine [Magick::AffineMatrix] the affine matrix
 * @return [Magick::Image] a new image
 */
VALUE
Image_affine_transform(VALUE self, VALUE affine)
{
    Image *image, *new_image;
    ExceptionInfo *exception;
    AffineMatrix matrix;

    image = rm_check_destroyed(self);

    // Convert Magick::AffineMatrix to AffineMatrix structure.
    Export_AffineMatrix(&matrix, affine);

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(AffineTransformImage) args = { image, &matrix, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(AffineTransformImage), &args);
    new_image = reinterpret_cast<decltype(new_image)>(ret);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}

/**
 * Returns the value of the image property identified by key. An image may have any number of
 * properties.
 *
 * Each property is identified by a string (or symbol) key.
 * The property value is a string. ImageMagick predefines some properties, including "Label",
 * "Comment", "Signature", and in some cases "EXIF".
 *
 * @param key_arg [String, Symbol] the key to get
 * @return [String, nil] property value or nil if key doesn't exist
 * @see Image#[]=
 * @see Image#properties
 */
VALUE
 Image_aref(VALUE self, VALUE key_arg)
{
    Image *image;
    const char *key;
    const char *attr;

    image = rm_check_destroyed(self);

    switch (TYPE(key_arg))
    {
        case T_NIL:
            return Qnil;

        case T_SYMBOL:
            key = rb_id2name((ID)SYM2ID(key_arg));
            break;

        default:
            key = StringValueCStr(key_arg);
            if (*key == '\0')
            {
                return Qnil;
            }
            break;
    }


    if (rm_strcasecmp(key, "EXIF:*") == 0)
    {
        return rm_exif_by_entry(image);
    }
    else if (rm_strcasecmp(key, "EXIF:!") == 0)
    {
        return rm_exif_by_number(image);
    }

    attr = rm_get_property(image, key);
    return attr ? rb_str_new2(attr) : Qnil;
}

/**
 * Sets the value of an image property. An image may have any number of properties.
 *
 * - Specify attr=nil to remove the key from the list.
 * - SetImageProperty normally APPENDS the new value to any existing value. Since this usage is
 *   tremendously counter-intuitive, this function always deletes the existing value before setting
 *   the new value.
 * - There's no use checking the return value since SetImageProperty returns "False" for many
 *   reasons, some legitimate.
 *
 * @param key_arg [String, Symbol] the key to set
 * @param attr_arg [String] the value to which to set it
 * @return [Magick::Image] self
 */
VALUE
Image_aset(VALUE self, VALUE key_arg, VALUE attr_arg)
{
    Image *image;
    const char *key;
    char *attr;
    unsigned int okay;

    image = rm_check_frozen(self);

    attr = attr_arg == Qnil ? NULL : StringValueCStr(attr_arg);

    switch (TYPE(key_arg))
    {
        case T_NIL:
            return self;

        case T_SYMBOL:
            key = rb_id2name((ID)SYM2ID(key_arg));
            break;

        default:
            key = StringValueCStr(key_arg);
            if (*key == '\0')
            {
                return self;
            }
            break;
    }


    // Delete existing value. SetImageProperty returns False if
    // the attribute doesn't exist - we don't care.
    rm_set_property(image, key, NULL);
    // Set new value
    if (attr)
    {
        okay = rm_set_property(image, key, attr);
        if (!okay)
        {
            rb_warning("SetImageProperty failed (probably out of memory)");
        }
    }
    return self;
}


// aliases for common use of structure types; TransposeImage, TransverseImage
typedef GVL_STRUCT_TYPE(TransposeImage) GVL_STRUCT_TYPE(crisscross);

/**
 * Handle #transverse, #transform methods.
 *
 * No Ruby usage (internal function)
 *
 * @param bang whether the bang (!) version of the method was called
 * @param self this object
 * @param fp the transverse/transform method to call
 * @return self if bang, otherwise a new image
 */
static VALUE
crisscross(int bang, VALUE self, gvl_function_t fp)
{
    Image *image, *new_image;
    ExceptionInfo *exception;

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);
    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(crisscross) args = { image, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(fp, &args);
    new_image = reinterpret_cast<decltype(new_image)>(ret);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    if (bang)
    {
        rm_ensure_result(new_image);
        UPDATE_DATA_PTR(self, new_image);
        rm_image_destroy(image);
        return self;
    }

    return rm_image_new(new_image);

}


// aliases for common use of structure types; AutoGammaImage, AutoLevelImage, AutoGammaImageChannel, AutoLevelImageChannel
#if defined(IMAGEMAGICK_7)
typedef GVL_STRUCT_TYPE(AutoGammaImage) GVL_STRUCT_TYPE(auto_channel);
#else
typedef GVL_STRUCT_TYPE(AutoGammaImageChannel) GVL_STRUCT_TYPE(auto_channel);
#endif

/**
 * Handle #auto_gamma_channel, #auto_level_channel methods.
 *
 * No Ruby usage (internal function)
 *
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @param fp the channel method to call
 * @return a new image
 */
static VALUE
auto_channel(int argc, VALUE *argv, VALUE self, gvl_function_t fp)
{
    Image *image, *new_image;
    ChannelType channels;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    if (argc > 0)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(new_image, channels);
    GVL_STRUCT_TYPE(auto_channel) args = { new_image, exception };
    CALL_FUNC_WITHOUT_GVL(fp, &args);
    END_CHANNEL_MASK(new_image);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(auto_channel) args = { new_image, channels };
    CALL_FUNC_WITHOUT_GVL(fp, &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * "Automagically" adjust the gamma level of an image.
 *
 * @overload auto_gamma_channel(channel = Magick::AllChannels)
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload auto_gamma_channel(*channels)
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_auto_gamma_channel(int argc, VALUE *argv, VALUE self)
{
#if defined(IMAGEMAGICK_7)
    return auto_channel(argc, argv, self, GVL_FUNC(AutoGammaImage));
#else
    return auto_channel(argc, argv, self, GVL_FUNC(AutoGammaImageChannel));
#endif
}


/**
 * "Automagically" adjust the color levels of an image.
 *
 * @overload auto_level_channel(channel = Magick::AllChannels)
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload auto_level_channel(*channels)
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_auto_level_channel(int argc, VALUE *argv, VALUE self)
{
#if defined(IMAGEMAGICK_7)
    return auto_channel(argc, argv, self, GVL_FUNC(AutoLevelImage));
#else
    return auto_channel(argc, argv, self, GVL_FUNC(AutoLevelImageChannel));
#endif
}


/**
 * Implement mogrify's -auto_orient option automatically orient image based on
 * EXIF orientation value.
 *
 * No Ruby usage (internal function)
 *
 * @param bang whether the bang (!) version of the method was called
 * @param self this object
 * @return self if bang, otherwise a new image
 * @see mogrify.c (in ImageMagick 6.2.8)
 */
static VALUE
auto_orient(int bang, VALUE self)
{
    Image *image;
    VALUE new_image;
    VALUE degrees[1];

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);

    switch (image->orientation)
    {
        case TopRightOrientation:
            new_image = flipflop(bang, self, GVL_FUNC(FlopImage));
            break;

        case BottomRightOrientation:
            degrees[0] = rb_float_new(180.0);
            new_image = rotate(bang, 1, degrees, self);
            break;

        case BottomLeftOrientation:
            new_image = flipflop(bang, self, GVL_FUNC(FlipImage));
            break;

        case LeftTopOrientation:
            new_image = crisscross(bang, self, GVL_FUNC(TransposeImage));
            break;

        case RightTopOrientation:
            degrees[0] = rb_float_new(90.0);
            new_image = rotate(bang, 1, degrees, self);
            break;

        case RightBottomOrientation:
            new_image = crisscross(bang, self, GVL_FUNC(TransverseImage));
            break;

        case LeftBottomOrientation:
            degrees[0] = rb_float_new(270.0);
            new_image = rotate(bang, 1, degrees, self);
            break;

        default:                // Return IMMEDIATELY
            return bang ? Qnil : Image_copy(self);
            break;
    }


    TypedData_Get_Struct(new_image, Image, &rm_image_data_type, image);
    image->orientation = TopLeftOrientation;

    RB_GC_GUARD(new_image);

    return new_image;
}


/**
 * Rotates or flips the image based on the image's EXIF orientation tag.
 *
 * Note that only some models of modern digital cameras can tag an image with the orientation.
 * If the image does not have an orientation tag, or the image is already properly oriented, then
 * {Magick::Image#auto_orient} returns an exact copy of the image.
 *
 * @return [Magick::Image] a new image
 * @see Image#auto_orient!
 */
VALUE
Image_auto_orient(VALUE self)
{
    rm_check_destroyed(self);
    return auto_orient(False, self);
}


/**
 * Rotates or flips the image based on the image's EXIF orientation tag.
 * Note that only some models of modern digital cameras can tag an image with the orientation.
 * If the image does not have an orientation tag, or the image is already properly oriented, then
 * {Magick::Image#auto_orient!} returns nil.
 *
 * @return [Magick::Image, nil] nil if the image is already properly oriented, otherwise self
 * @see Image#auto_orient
*/
VALUE
Image_auto_orient_bang(VALUE self)
{
    rm_check_frozen(self);
    return auto_orient(True, self);
}


/**
 * Return the name of the background color as a String.
 *
 * @return [String] the background color
 */
VALUE
Image_background_color(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return rm_pixelcolor_to_color_name(image, &image->background_color);
}


/**
 * Set the the background color to the specified color spec.
 *
 * @param color [Magick::Pixel, String] the color
 * @return [Magick::Pixel, String] the given color
 */
VALUE
Image_background_color_eq(VALUE self, VALUE color)
{
    Image *image = rm_check_frozen(self);
    Color_to_PixelColor(&image->background_color, color);
    return color;
}


/**
 * Return the number of rows (before transformations).
 *
 * @return [Integer] the number of rows
 */
VALUE
Image_base_columns(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return INT2FIX(image->magick_columns);
}

/**
 * Return the image filename (before transformations).
 *
 * @return [String] the base image filename (or the current filename if there is no base)
 */
VALUE
Image_base_filename(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    if (*image->magick_filename)
    {
        return rb_str_new2(image->magick_filename);
    }
    else
    {
        return rb_str_new2(image->filename);
    }
}

/**
 * Return the number of rows (before transformations).
 *
 * @return [Integer] the number of rows
 */
VALUE
Image_base_rows(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return INT2FIX(image->magick_rows);
}


/**
 * Get image bias (used when convolving an image).
 *
 * @return [Float] the image bias
 */
VALUE
Image_bias(VALUE self)
{
    Image *image;
    double bias = 0.0;

    image = rm_check_destroyed(self);
#if defined(IMAGEMAGICK_7)
    {
        const char *artifact = GetImageArtifact(image, "convolve:bias");
        if (artifact != (const char *) NULL)
        {
            char *q;

            bias = InterpretLocaleValue(artifact, &q);
            if (*q == '%')
            {
                bias *= ((double) QuantumRange + 1.0) / 100.0;
            }
        }
    }
#else
    bias = image->bias;
#endif
    return rb_float_new(bias);
}


/**
 * Set image bias (used when convolving an image).
 *
 * @param pct [Numeric, String] Either a number between 0.0 and 1.0 or a string in the form "NN%"
 * @return [Numeric, String] the given value
 */
VALUE
Image_bias_eq(VALUE self, VALUE pct)
{
    Image *image;
    double bias;

    image = rm_check_frozen(self);
    bias = rm_percentage(pct, 1.0) * QuantumRange;

#if defined(IMAGEMAGICK_7)
    {
        char artifact[21];

        snprintf(artifact, sizeof(artifact), "%.20g", bias);
        SetImageArtifact(image, "convolve:bias", artifact);
    }
#else
    image->bias = bias;
#endif

    return pct;
}

/**
 * Changes the value of individual pixels based on the intensity of each pixel channel. The result
 * is a high-contrast image.
 *
 * @overload bilevel_channel(threshold, channel = Magick::AllChannels)
 *   @param threshold [Numeric] The threshold value, a number between 0 and QuantumRange.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload bilevel_channel(threshold, *channels)
 *   @param threshold [Numeric] The threshold value, a number between 0 and QuantumRange.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_bilevel_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ChannelType channels;
    double threshold;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    if (argc > 1)
    {
        raise_ChannelType_error(argv[argc-1]);
    }
    if (argc == 0)
    {
        rb_raise(rb_eArgError, "no threshold specified");
    }

    threshold = NUM2DBL(argv[0]);
    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(new_image, channels);
    GVL_STRUCT_TYPE(BilevelImage) args = { new_image, threshold, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(BilevelImage), &args);
    END_CHANNEL_MASK(new_image);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(BilevelImageChannel) args = { new_image, channels, threshold };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(BilevelImageChannel), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Return current black point compensation attribute.
 *
 * @return [Boolean] true or false
 */
VALUE
Image_black_point_compensation(VALUE self)
{
    Image *image;
    const char *attr;
    VALUE value;

    image = rm_check_destroyed(self);

    attr = rm_get_property(image, BlackPointCompensationKey);
    if (attr && rm_strcasecmp(attr, "true") == 0)
    {
        value = Qtrue;
    }
    else
    {
        value = Qfalse;
    }

    RB_GC_GUARD(value);

    return value;
}


/**
 * Set black point compensation attribute.
 *
 * @param arg [Boolean] true or false
 * @return [Boolean] the given value
 */
VALUE
Image_black_point_compensation_eq(VALUE self, VALUE arg)
{
    Image *image;
    const char *value;

    image = rm_check_frozen(self);
    rm_set_property(image, BlackPointCompensationKey, NULL);
    value = RTEST(arg) ? "true" : "false";
    rm_set_property(image, BlackPointCompensationKey, value);

    return arg;
}


/**
 * Forces all pixels below the threshold into black while leaving all pixels above the threshold
 * unchanged.
 *
 * @overload black_threshold(red)
 *   @param red [Numeric] the number for red channel
 *
 * @overload black_threshold(red, green)
 *   @param red [Numeric] the number for red channel
 *   @param green [Numeric] the number for green channel
 *
 * @overload black_threshold(red, green, blue)
 *   @param red [Numeric] the number for red channel
 *   @param green [Numeric] the number for green channel
 *   @param blue [Numeric] the number for blue channel
 *
 * @overload black_threshold(red, green, blue, alpha:)
 *   @param red [Numeric] the number for red channel
 *   @param green [Numeric] the number for green channel
 *   @param blue [Numeric] the number for blue channel
 *   @param alpha [Numeric] the number for alpha channel
 *
 * @return [Numeric] a new image
 * @see Image#white_threshold
 */
VALUE
Image_black_threshold(int argc, VALUE *argv, VALUE self)
{
    return threshold_image(argc, argv, self, GVL_FUNC(BlackThresholdImage));
}


/**
 * Compute offsets using the gravity to determine what the offsets are relative
 * to.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - No return value: modifies x_offset and y_offset directly.
 *
 * @param grav the gravity
 * @param image the destination image
 * @param mark the source image
 * @param x_offset pointer to x offset
 * @param y_offset pointer to y offset
 */
static void
get_relative_offsets(VALUE grav, Image *image, Image *mark, long *x_offset, long *y_offset)
{
    GravityType gravity;

    VALUE_TO_ENUM(grav, gravity, GravityType);

    switch (gravity)
    {
        case NorthEastGravity:
        case EastGravity:
        case SouthEastGravity:
            *x_offset = (long)(image->columns) - (long)(mark->columns) - *x_offset;
            break;
        case NorthGravity:
        case SouthGravity:
        case CenterGravity:
            *x_offset += (long)(image->columns/2) - (long)(mark->columns/2);
            break;
        default:
            break;
    }
    switch (gravity)
    {
        case SouthWestGravity:
        case SouthGravity:
        case SouthEastGravity:
            *y_offset = (long)(image->rows) - (long)(mark->rows) - *y_offset;
            break;
        case EastGravity:
        case WestGravity:
        case CenterGravity:
            *y_offset += (long)(image->rows/2) - (long)(mark->rows/2);
            break;
        case NorthEastGravity:
        case NorthGravity:
        default:
            break;
    }

}


/**
 * Compute watermark offsets from gravity type.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - No return value: modifies x_offset and y_offset directly.
 *
 * @param grav the gravity
 * @param image the destination image
 * @param mark the source image
 * @param x_offset pointer to x offset
 * @param y_offset pointer to y offset
 */
static void
get_offsets_from_gravity(GravityType gravity, Image *image, Image *mark,
                         long *x_offset, long *y_offset)
{

    switch (gravity)
    {
        case ForgetGravity:
        case NorthWestGravity:
            *x_offset = 0;
            *y_offset = 0;
            break;
        case NorthGravity:
            *x_offset = ((long)(image->columns) - (long)(mark->columns)) / 2;
            *y_offset = 0;
            break;
        case NorthEastGravity:
            *x_offset = (long)(image->columns) - (long)(mark->columns);
            *y_offset = 0;
            break;
        case WestGravity:
            *x_offset = 0;
            *y_offset = ((long)(image->rows) - (long)(mark->rows)) / 2;
            break;
        case CenterGravity:
        default:
            *x_offset = ((long)(image->columns) - (long)(mark->columns)) / 2;
            *y_offset = ((long)(image->rows) - (long)(mark->rows)) / 2;
            break;
        case EastGravity:
            *x_offset = (long)(image->columns) - (long)(mark->columns);
            *y_offset = ((long)(image->rows) - (long)(mark->rows)) / 2;
            break;
        case SouthWestGravity:
            *x_offset = 0;
            *y_offset = (long)(image->rows) - (long)(mark->rows);
            break;
        case SouthGravity:
            *x_offset = ((long)(image->columns) - (long)(mark->columns)) / 2;
            *y_offset = (long)(image->rows) - (long)(mark->rows);
            break;
        case SouthEastGravity:
            *x_offset = (long)(image->columns) - (long)(mark->columns);
            *y_offset = (long)(image->rows) - (long)(mark->rows);
            break;
    }
}


/**
 * Called from rb_protect, returns the number if obj is really a numeric value.
 *
 * No Ruby usage (internal function)
 *
 * @param obj the value
 * @return numeric value of obj
 * @todo Make sure that we are really returning the obj here
 */
static VALUE
check_for_long_value(VALUE obj)
{
    return LONG2NUM(NUM2LONG(obj));
}


/**
 * Compute x- and y-offset of source image for a compositing method.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - No return value: modifies x_offset and y_offset directly.
 *
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param dest the destination image
 * @param src the source image
 * @param x_offset pointer to x offset
 * @param y_offset pointer to y offset
 */
static void
get_composite_offsets(int argc, VALUE *argv, Image *dest, Image *src,
                      long *x_offset, long *y_offset)
{
    GravityType gravity;
    int exc = 0;

    if (CLASS_OF(argv[0]) == Class_GravityType)
    {
        VALUE_TO_ENUM(argv[0], gravity, GravityType);

        switch (argc)
        {
            // Gravity + offset(s). Offsets are relative to the image edges
            // as specified by the gravity.
            case 3:
                *y_offset = NUM2LONG(argv[2]);
            case 2:
                *x_offset = NUM2LONG(argv[1]);
                get_relative_offsets(argv[0], dest, src, x_offset, y_offset);
                break;
            case 1:
                // No offsets specified. Compute offset based on the gravity alone.
                get_offsets_from_gravity(gravity, dest, src, x_offset, y_offset);
                break;
        }
    }
    // Gravity not specified at all. Offsets are measured from the
    // NorthWest corner. The arguments must be numbers.
    else
    {
        rb_protect(check_for_long_value, argv[0], &exc);
        if (exc)
        {
            rb_raise(rb_eTypeError, "expected GravityType, got %s",
                     rb_class2name(CLASS_OF(argv[0])));
        }
        *x_offset = NUM2LONG(argv[0]);
        if (argc > 1)
        {
            *y_offset = NUM2LONG(argv[1]);
        }
    }

}


/**
 * Convert 2 doubles to a blend or dissolve geometry string.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - the geometry buffer needs to be at least 16 characters long.
 *   - For safety's sake this function asserts that it is at least 20 characters
 *     long.
 *   - The percentages must be in the range -1000 < n < 1000. This is far in
 *     excess of what xMagick will allow.
 *
 * @param geometry the geometry
 * @param geometry_l length of geometry
 * @param src_percent source percentage
 * @param dst_percent destination percentage
 */
static void
blend_geometry(char *geometry, size_t geometry_l, double src_percent, double dst_percent)
{
    size_t sz = 0;
    int fw, prec;

    if (fabs(src_percent) >= 1000.0 || fabs(dst_percent) >= 1000.0)
    {
        if (fabs(src_percent) < 1000.0)
        {
            src_percent = dst_percent;
        }
        rb_raise(rb_eArgError, "%g is out of range +/-999.99", src_percent);
    }

    assert(geometry_l >= 20);
    memset(geometry, 0xdf, geometry_l);

    fw = 4;
    prec = 0;
    if (src_percent != floor(src_percent))
    {
        prec = 2;
        fw += 3;
    }

    sz = (size_t)snprintf(geometry, geometry_l, "%*.*f", -fw, prec, src_percent);
    assert(sz < geometry_l);

    sz = strcspn(geometry, " ");

    // if dst_percent was nil don't add to the geometry
    if (dst_percent != -1.0)
    {
        fw = 4;
        prec = 0;
        if (dst_percent != floor(dst_percent))
        {
            prec = 2;
            fw += 3;
        }


        sz += (size_t)snprintf(geometry+sz, geometry_l-sz, "x%*.*f", -fw, prec, dst_percent);
        assert(sz < geometry_l);
        sz = strcspn(geometry, " ");
    }

    if (sz < geometry_l)
    {
        memset(geometry+sz, 0x00, geometry_l-sz);
    }

}


/**
 * Create a composite of an image and an overlay (for blending, dissolving, etc.).
 *
 * No Ruby usage (internal function)
 *
 * @param image the original image
 * @param overlay the overlay
 * @param image_pct image percentage
 * @param overlay_pct overlay percentage
 * @param x_off the x offset
 * @param y_off the y offset
 * @param op the composite operator to use
 * @return a new image
 */
static VALUE
special_composite(Image *image, Image *overlay, double image_pct, double overlay_pct,
                  long x_off, long y_off, CompositeOperator op)
{
    Image *new_image;
    char geometry[20];
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    blend_geometry(geometry, sizeof(geometry), image_pct, overlay_pct);
    CloneString(&overlay->geometry, geometry);
    SetImageArtifact(overlay, "compose:args", geometry);

    new_image = rm_clone_image(image);
    SetImageArtifact(new_image, "compose:args", geometry); // 6.9 appears to get this info from canvas (dest) image


#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(CompositeImage) args = { new_image, overlay, op, MagickTrue, x_off, y_off, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompositeImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(CompositeImage) args = { new_image, op, overlay, x_off, y_off };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompositeImage), &args);

    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Adds the overlay image to the target image according to src_percent and dst_percent.
 *
 * - The default value for dst_percent is 100%-src_percent
 *
 * @overload blend(overlay, src_percent, dst_percent, gravity = Magick::NorthWestGravity, x_offset = 0, y_offset = 0)
 *   @param overlay [Magick::Image, Magick::ImageList] The source image for the composite operation.
 *     Either an imagelist or an image. If an imagelist, uses the current image.
 *   @param src_percent [Numeric, String] Either a non-negative number a string in the form "NN%".
 *     If src_percentage is a number it is interpreted as a percentage.
 *     Both 0.25 and "25%" mean 25%. This argument is required.
 *   @param dst_percent [Numeric, String] Either a non-negative number a string in the form "NN%".
 *     If src_percentage is a number it is interpreted as a percentage.
 *     Both 0.25 and "25%" mean 25%. This argument may omitted if no other arguments follow it.
 *     In this case the default is 100%-src_percentage.
 *   @param gravity [Magick::GravityType] the gravity for offset. the offsets are measured from the NorthWest corner by default.
 *   @param x_offset [Numeric] The offset that measured from the left-hand side of the target image.
 *   @param y_offset [Numeric] The offset that measured from the top of the target image.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_blend(int argc, VALUE *argv, VALUE self)
{
    VALUE ovly;
    Image *image, *overlay;
    double src_percent, dst_percent;
    long x_offset = 0L, y_offset = 0L;

    image = rm_check_destroyed(self);

    if (argc < 1)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 to 6)", argc);
    }

    ovly = rm_cur_image(argv[0]);
    overlay = rm_check_destroyed(ovly);

    if (argc > 3)
    {
        get_composite_offsets(argc-3, &argv[3], image, overlay, &x_offset, &y_offset);
        // There must be 3 arguments left
        argc = 3;
    }

    switch (argc)
    {
        case 3:
            dst_percent = rm_percentage(argv[2], 1.0) * 100.0;
            src_percent = rm_percentage(argv[1], 1.0) * 100.0;
            break;
        case 2:
            src_percent = rm_percentage(argv[1], 1.0) * 100.0;
            dst_percent = FMAX(100.0 - src_percent, 0);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 to 6)", argc);
            break;
    }

    RB_GC_GUARD(ovly);

    return special_composite(image, overlay, src_percent, dst_percent,
                             x_offset, y_offset, BlendCompositeOp);

}



/**
 * Simulate a scene at nighttime in the moonlight.
 *
 * @overload blue_shift(factor = 1.5)
 *   @param factor [Numeric] Larger values increase the effect.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_blue_shift(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double factor = 1.5;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 1:
            factor = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 or 1)", argc);
            break;
    }


    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(BlueShiftImage) args = { image, factor, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(BlueShiftImage), &args);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Blurs the specified channel.
 * Convolves the image with a Gaussian operator of the given radius and standard deviation (sigma).
 *
 * @overload blur_channel(radius = 0.0, sigma = 1.0, channel = Magick::AllChannels)
 *   @param radius [Numeric] the radius value
 *   @param sigma [Numeric] the sigma value
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload blur_channel(radius = 0.0, sigma = 1.0, *channels)
 *   @param radius [Numeric] the radius value
 *   @param sigma [Numeric] the sigma value
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_blur_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ExceptionInfo *exception;
    ChannelType channels;
    double radius = 0.0, sigma = 1.0;

    image = rm_check_destroyed(self);

    channels = extract_channels(&argc, argv);

    // There can be 0, 1, or 2 remaining arguments.
    switch (argc)
    {
        case 2:
            sigma = NUM2DBL(argv[1]);
        case 1:
            radius = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            raise_ChannelType_error(argv[argc-1]);
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(BlurImage) args = { image, radius, sigma, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(BlurImage), &args);
    CHANGE_RESULT_CHANNEL_MASK(new_image);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(BlurImageChannel) args = { image, channels, radius, sigma, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(BlurImageChannel), &args);
#endif
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Blur the image.
 *
 * @overload blur_image(radius = 0.0, sigma = 1.0)
 *   @param radius [Numeric] the radius value
 *   @param sigma [Numeric] the sigma value
 *   @return [Magick::Image] a new image
 */
VALUE
Image_blur_image(int argc, VALUE *argv, VALUE self)
{
    return effect_image(self, argc, argv, GVL_FUNC(BlurImage));
}


/**
 * Surrounds the image with a border of the specified width, height, and named
 * color.
 *
 * No Ruby usage (internal function)
 *
 * @param bang whether the bang (!) version of the method was called
 * @param self this object
 * @param width the width of the border
 * @param height the height of the border
 * @param color the color of the border
 * @return self if bang, otherwise a new image
 * @see Image_border
 * @see Image_border_bang
 */
static VALUE
border(int bang, VALUE self, VALUE width, VALUE height, VALUE color)
{
    Image *image, *new_image;
    PixelColor old_border;
    ExceptionInfo *exception;
    RectangleInfo rect;

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);

    memset(&rect, 0, sizeof(rect));
    rect.width = NUM2UINT(width);
    rect.height = NUM2UINT(height);

    // Save current border color - we'll want to restore it afterwards.
    old_border = image->border_color;
    Color_to_PixelColor(&image->border_color, color);

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(BorderImage) args = { image, &rect, image->compose, exception };
#else
    GVL_STRUCT_TYPE(BorderImage) args = { image, &rect, exception };
#endif
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(BorderImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    if (bang)
    {
        rm_ensure_result(new_image);
        new_image->border_color = old_border;
        UPDATE_DATA_PTR(self, new_image);
        rm_image_destroy(image);
        return self;
    }

    image->border_color = old_border;
    return rm_image_new(new_image);
}

/**
 * Surrounds the image with a border of the specified width, height, and named color.
 * In-place form of {Image#border}.
 *
 * @param width [Numeric] the width of the border
 * @param height [Numeric] the height of the border
 * @param color [Magick::Pixel, String] the color of the border
 */
VALUE
Image_border_bang(VALUE self, VALUE width, VALUE height, VALUE color)
{
    rm_check_frozen(self);
    return border(True, self, width, height, color);
}


/**
 * Surrounds the image with a border of the specified width, height, and named color.
 *
 * @param width [Numeric] the width of the border
 * @param height [Numeric] the height of the border
 * @param color [Magick::Pixel, String] the color of the border
 * @return [Magick::Image] a new image
 */
VALUE
Image_border(VALUE self, VALUE width, VALUE height, VALUE color)
{
    rm_check_destroyed(self);
    return border(False, self, width, height, color);
}


/**
 * Return the name of the border color as a String.
 *
 * @return [String] the name of the border color
 */
VALUE
Image_border_color(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return rm_pixelcolor_to_color_name(image, &image->border_color);
}


/**
 * Set the the border color.
 *
 * @param [Magick::Pixel, String] color the color
 * @return [Magick::Pixel, String] the given color
 */
VALUE
Image_border_color_eq(VALUE self, VALUE color)
{
    Image *image = rm_check_frozen(self);
    Color_to_PixelColor(&image->border_color, color);
    return color;
}


/**
 * Returns the bounding box of an image canvas.
 *
 * @return [Magick::Rectangle] the bounding box
 */
VALUE
Image_bounding_box(VALUE self)
{
    Image *image;
    RectangleInfo box;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    exception = AcquireExceptionInfo();
    box = GetImageBoundingBox(image, exception);
    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    return Import_RectangleInfo(&box);
}


/**
 * Reads an image from an X window.
 * Unless you identify a window to capture via the optional arguments block, when capture is invoked
 * the cursor will turn into a cross. Click the cursor on the window to be captured.
 *
 * @overload capture(silent = false, frame = false, descend = false, screen = false, borders = false)
 *   @param silent [Boolean] If true, suppress the beeps that signal the start and finish of the
 *     capture process.
 *   @param frame [Boolean] If true, include the window frame.
 *   @param descend [Boolean] If true, obtain image by descending window hierarchy.
 *   @param screen [Boolean] If true, specifies that the GetImage request used to obtain the image
 *     should be done on the root window, rather than directly on the specified window. In this way,
 *     you can obtain pieces of other windows that overlap the specified window, and more
 *     importantly, you can capture menus or other popups that are independent windows but appear
 *     over the specified window.
 *   @param borders [Boolean] If true, include the border in the image.
 *
 * @overload capture(silent = false, frame = false, descend = false, screen = false, borders = false)
 *   This yields {Magick::Image::Info} to block with its object's scope.
 *   @param silent [Boolean] If true, suppress the beeps that signal the start and finish of the
 *     capture process.
 *   @param frame [Boolean] If true, include the window frame.
 *   @param descend [Boolean] If true, obtain image by descending window hierarchy.
 *   @param screen [Boolean] If true, specifies that the GetImage request used to obtain the image
 *     should be done on the root window, rather than directly on the specified window. In this way,
 *     you can obtain pieces of other windows that overlap the specified window, and more
 *     importantly, you can capture menus or other popups that are independent windows but appear
 *     over the specified window.
 *   @param borders [Boolean] If true, include the border in the image.
 *   @yield [info]
 *   @yieldparam info [Magick::Image::Info]
 *
 * @return [Magick::Image] a new image
 * @example
 *   img = Image.capture { |options|
 *     options.filename = "root"
 *   }
 */
VALUE
Image_capture(int argc, VALUE *argv, VALUE self ATTRIBUTE_UNUSED)
{
    Image *new_image;
    ImageInfo *image_info;
    VALUE info_obj;
    XImportInfo ximage_info;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    XGetImportInfo(&ximage_info);
    switch (argc)
    {
        case 5:
            ximage_info.borders = (MagickBooleanType)RTEST(argv[4]);
        case 4:
            ximage_info.screen  = (MagickBooleanType)RTEST(argv[3]);
        case 3:
            ximage_info.descend = (MagickBooleanType)RTEST(argv[2]);
        case 2:
            ximage_info.frame   = (MagickBooleanType)RTEST(argv[1]);
        case 1:
            ximage_info.silent  = (MagickBooleanType)RTEST(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 5)", argc);
            break;
    }

    // Get optional parms.
    // Set info->filename = "root", window ID number or window name,
    //  or nothing to do an interactive capture
    // Set info->server_name to the server name
    // Also info->colorspace, depth, dither, interlace, type
    info_obj = rm_info_new();
    TypedData_Get_Struct(info_obj, Info, &rm_info_data_type, image_info);

    // If an error occurs, IM will call our error handler and we raise an exception.
#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    new_image = XImportImage(image_info, &ximage_info, exception);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    new_image = XImportImage(image_info, &ximage_info);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    rm_ensure_result(new_image);

    rm_set_user_artifact(new_image, image_info);
    rm_sync_image_options(new_image, image_info);

    RB_GC_GUARD(info_obj);

    return rm_image_new(new_image);
}


/**
 * This method supports resizing a method by specifying constraints.
 * For example, you can specify that the image should be resized such that the aspect ratio should
 * be retained but the resulting image should be no larger than 640 pixels wide and 480 pixels tall.
 *
 * @param geom_arg [Magick::Geometry, String] the geometry
 * @yield [column, row, image]
 * @yieldparam column [Integer] The desired column size
 * @yieldparam row [Integer] The desired row size
 * @yieldparam image [Magick::Image] self
 * @see https://www.imagemagick.org/Magick++/Geometry.html
 * @example
 *   image.change_geometry!('320x240') { |cols, rows, img|
 *     img.resize!(cols, rows)
 *   }
 * @note {Magick::Image#change_geometry!} is an alias for {Magick::Image#change_geometry}.
 */
VALUE
Image_change_geometry(VALUE self, VALUE geom_arg)
{
    Image *image;
    RectangleInfo rect;
    VALUE geom_str;
    char *geometry;
    unsigned int flags;
    VALUE ary;

    image = rm_check_destroyed(self);
    geom_str = rb_String(geom_arg);
    geometry = StringValueCStr(geom_str);

    memset(&rect, 0, sizeof(rect));

    SetGeometry(image, &rect);
    flags = ParseMetaGeometry(geometry, &rect.x, &rect.y, &rect.width, &rect.height);
    if (flags == NoValue)
    {
        rb_raise(rb_eArgError, "invalid geometry string `%s'", geometry);
    }

    ary = rb_ary_new2(3);
    rb_ary_store(ary, 0, ULONG2NUM(rect.width));
    rb_ary_store(ary, 1, ULONG2NUM(rect.height));
    rb_ary_store(ary, 2, self);

    RB_GC_GUARD(geom_str);
    RB_GC_GUARD(ary);

    return rb_yield(ary);
}


/**
 * Return true if any pixel in the image has been altered since the image was constituted.
 *
 * @return [Boolean] true if altered, false otherwise
 */
VALUE
Image_changed_q(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    VALUE okay = IsTaintImage(image) ? Qtrue : Qfalse;
    return okay;
}


/**
 * Extract a channel from the image. A channel is a particular color component of each pixel in the
 * image.
 *
 * @param channel_arg [Magick::ChannelType] the type of the channel to extract
 * @return [Magick::Image] a new image
 */
VALUE
Image_channel(VALUE self, VALUE channel_arg)
{
    Image *image, *new_image;
    ChannelType channel;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

    VALUE_TO_ENUM(channel_arg, channel, ChannelType);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(SeparateImage) args = { image, channel, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SeparateImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    new_image = rm_clone_image(image);
    GVL_STRUCT_TYPE(SeparateImageChannel) args = { new_image, channel };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SeparateImageChannel), &args);

    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Returns the maximum depth for the specified channel or channels.
 *
 * @overload channel_depth(channel = Magick::AllChannels)
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload channel_depth(*channels)
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Integer] the channel depth
 */
VALUE
Image_channel_depth(int argc, VALUE *argv, VALUE self)
{
    Image *image;
    ChannelType channels;
    size_t channel_depth;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    // Ensure all arguments consumed.
    if (argc > 0)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    exception = AcquireExceptionInfo();

#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(GetImageDepth) args = { image, exception };
    channel_depth = (size_t)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetImageDepth), &args);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(GetImageChannelDepth) args = { image, channels, exception };
    channel_depth = (size_t)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetImageChannelDepth), &args);
#endif
    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    return ULONG2NUM(channel_depth);
}


/**
 * Returns the minimum and maximum intensity values for the specified channel or channels.
 *
 * @overload channel_extrema(channel = Magick::AllChannels)
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload channel_extrema(*channels)
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Array<Integer>] The first element in the array is the minimum value. The second element is the
 *   maximum value.
 */
VALUE
Image_channel_extrema(int argc, VALUE *argv, VALUE self)
{
    Image *image;
    ChannelType channels;
    ExceptionInfo *exception;
    size_t min, max;
    VALUE ary;

    image = rm_check_destroyed(self);

    channels = extract_channels(&argc, argv);

    // Ensure all arguments consumed.
    if (argc > 0)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(GetImageExtrema) args = { image, &min, &max, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetImageExtrema), &args);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(GetImageChannelExtrema) args = { image, channels, &min, &max, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetImageChannelExtrema), &args);
#endif
    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    ary = rb_ary_new2(2);
    rb_ary_store(ary, 0, ULONG2NUM(min));
    rb_ary_store(ary, 1, ULONG2NUM(max));

    RB_GC_GUARD(ary);

    return ary;
}


/**
 * Returns the mean and standard deviation values for the specified channel or channels.
 *
 * @overload channel_mean(channel = Magick::AllChannels)
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload channel_mean(*channels)
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Array<Float>] The first element in the array is the mean value. The second element is the
 *   standard deviation.
 */
VALUE
Image_channel_mean(int argc, VALUE *argv, VALUE self)
{
    Image *image;
    ChannelType channels;
    ExceptionInfo *exception;
    double mean, stddev;
    VALUE ary;

    image = rm_check_destroyed(self);

    channels = extract_channels(&argc, argv);

    // Ensure all arguments consumed.
    if (argc > 0)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(GetImageMean) args = { image, &mean, &stddev, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetImageMean), &args);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(GetImageChannelMean) args = { image, channels, &mean, &stddev, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetImageChannelMean), &args);
#endif
    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    ary = rb_ary_new2(2);
    rb_ary_store(ary, 0, rb_float_new(mean));
    rb_ary_store(ary, 1, rb_float_new(stddev));

    RB_GC_GUARD(ary);

    return ary;
}

/**
 * Return an array of the entropy for the channel.
 *
 * @overload channel_entropy(channel = Magick::AllChannels)
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload channel_entropy(*channels)
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Array<Float>] The first element in the array is the average entropy of the selected channels.
 */
#if defined(HAVE_GETIMAGECHANNELENTROPY) || defined(IMAGEMAGICK_7)
VALUE
Image_channel_entropy(int argc, VALUE *argv, VALUE self)
{
    Image *image;
    ChannelType channels;
    ExceptionInfo *exception;
    double entropy;
    VALUE ary;

    image = rm_check_destroyed(self);

    channels = extract_channels(&argc, argv);

    // Ensure all arguments consumed.
    if (argc > 0)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(GetImageEntropy) args = { image, &entropy, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetImageEntropy), &args);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(GetImageChannelEntropy) args = { image, channels, &entropy, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetImageChannelEntropy), &args);
#endif
    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    ary = rb_ary_new2(1);
    rb_ary_store(ary, 0, rb_float_new(entropy));

    RB_GC_GUARD(ary);

    return ary;
}
#else
VALUE
Image_channel_entropy(int argc ATTRIBUTE_UNUSED, VALUE *argv ATTRIBUTE_UNUSED, VALUE self ATTRIBUTE_UNUSED)
{
    rm_not_implemented();
}
#endif

/**
 * Return a new image that is a copy of the input image with the edges highlighted.
 *
 * @overload charcoal(radius = 0.0, sigma = 1.0)
 *   @param radius [Numeric] The radius of the pixel neighborhood.
 *   @param sigma [Numeric] The standard deviation of the Gaussian, in pixels.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_charcoal(int argc, VALUE *argv, VALUE self)
{
    return effect_image(self, argc, argv, GVL_FUNC(CharcoalImage));
}


/**
 * Raises {Magick::DestroyedImageError} if the image has been destroyed. Returns nil otherwise.
 *
 * @return [nil] nil
 * @raise [Magick::DestroyedImageError] raise if the image has been destroyed
 */
VALUE
Image_check_destroyed(VALUE self)
{
    rm_check_destroyed(self);
    return Qnil;
}


/**
 * Remove a region of an image and collapses the image to occupy the removed portion.
 *
 * @param x [Numeric] x position of start of region
 * @param y [Numeric] y position of start of region
 * @param width [Numeric] width of region
 * @param height [Numeric] height of region
 * @return [Magick::Image] a new image
 */
VALUE
Image_chop(VALUE self, VALUE x, VALUE y, VALUE width, VALUE height)
{
    rm_check_destroyed(self);
    return xform_image(False, self, x, y, width, height, GVL_FUNC(ChopImage));
}


/**
 * Return the red, green, blue, and white-point chromaticity values as a {Magick::Chromaticity}.
 *
 * @return [Magick::Chromaticity] the chromaticity values
 */
VALUE
Image_chromaticity(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return ChromaticityInfo_new(&image->chromaticity);
}


/**
 * Set the red, green, blue, and white-point chromaticity values from a {Magick::Chromaticity}.
 *
 * @param [Magick::Chromaticity] chroma the chromaticity
 * @return [Magick::Chromaticity] the given value
 */
VALUE
Image_chromaticity_eq(VALUE self, VALUE chroma)
{
    Image *image = rm_check_frozen(self);
    Export_ChromaticityInfo(&image->chromaticity, chroma);
    return chroma;
}


/**
 * Same as {Magick::Image#dup} except the frozen state of the original is propagated to the new
 * copy.
 *
 * @return [Magick::Image] a clone of this object
 */
VALUE
Image_clone(VALUE self)
{
    VALUE clone;

    clone = Image_dup(self);
    if (OBJ_FROZEN(self))
    {
        OBJ_FREEZE(clone);
    }

    RB_GC_GUARD(clone);

    return clone;
}


/**
 * Replace the channel values in the target image with a lookup of its replacement value in an LUT
 * gradient image.
 *
 * The LUT image should be either a single row or column image of replacement colors.
 * The lookup is controlled by the -interpolate setting, especially for an LUT which is not the full
 * length needed by the IM installed Quality (Q) level.  Good settings for this is the default
 * 'bilinear' or 'bicubic' interpolation setting for a smooth color gradient, or 'integer' for a
 * direct unsmoothed lookup of color values.
 *
 * This method is especially suited to replacing a grayscale image with specific color gradient from
 * the CLUT image.
 *
 * @overload clut_channel(clut_image, channel = Magick::AllChannels)
 *   @param clut_image [Magick::Image, Magick::ImageList] The LUT gradient image.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload clut_channel(clut_image, *channels)
 *   @param clut_image [Magick::Image, Magick::ImageList] The LUT gradient image.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] self
 */
VALUE
Image_clut_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *clut;
    ChannelType channels;
    MagickBooleanType okay;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_frozen(self);

    // check_destroyed before confirming the arguments
    if (argc >= 1)
    {
        clut = rm_check_destroyed(rm_cur_image(argv[0]));
        channels = extract_channels(&argc, argv);
        if (argc != 1)
        {
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or more)", argc);
        }
    }
    else
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or more)", argc);
    }

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(ClutImage) args = { image, clut, image->interpolate, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ClutImage), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    END_CHANNEL_MASK(image);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(ClutImageChannel) args = { image, channels, clut };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ClutImageChannel), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    rm_check_image_exception(image, RetainOnError);
    rm_check_image_exception(clut, RetainOnError);
#endif
    if (!okay)
    {
        rb_raise(rb_eRuntimeError, "ClutImageChannel failed.");
    }

    return self;
}


/**
 * Computes the number of times each unique color appears in the image.
 *
 * @return [Hash<Magick::Pixel, Integer>] Each key in the hash is a pixel representing a color that appears in the image.
 *   The value associated with the key is the number of times that color appears in the image.
 */
VALUE
Image_color_histogram(VALUE self)
{
    Image *image, *dc_copy = NULL;
    VALUE hash, pixel;
    size_t x, colors;
    ExceptionInfo *exception;
#if defined(IMAGEMAGICK_7)
    PixelInfo *histogram;
#else
    ColorPacket *histogram;
#endif

    image = rm_check_destroyed(self);

    exception = AcquireExceptionInfo();

    // If image not DirectClass make a DirectClass copy.
    if (image->storage_class != DirectClass)
    {
        dc_copy = rm_clone_image(image);
#if defined(IMAGEMAGICK_7)
        GVL_STRUCT_TYPE(SetImageStorageClass) args = { dc_copy, DirectClass, exception };
#else
        GVL_STRUCT_TYPE(SetImageStorageClass) args = { dc_copy, DirectClass };
#endif
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageStorageClass), &args);
        image = dc_copy;
    }

    GVL_STRUCT_TYPE(GetImageHistogram) args = { image, &colors, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetImageHistogram), &args);
    histogram = reinterpret_cast<decltype(histogram)>(ret);

    if (histogram == NULL)
    {
        if (dc_copy)
        {
            DestroyImage(dc_copy);
        }
        rb_raise(rb_eNoMemError, "not enough memory to continue");
    }
    if (rm_should_raise_exception(exception, DestroyExceptionRetention))
    {
        RelinquishMagickMemory(histogram);
        if (dc_copy)
        {
            DestroyImage(dc_copy);
        }

        rm_raise_exception(exception);
    }

    hash = rb_hash_new();
    for (x = 0; x < colors; x++)
    {
#if defined(IMAGEMAGICK_7)
        pixel = Pixel_from_PixelColor(&histogram[x]);
#else
        pixel = Pixel_from_PixelColor(&histogram[x].pixel);
#endif
        rb_hash_aset(hash, pixel, ULONG2NUM((unsigned long)histogram[x].count));
    }

    /*
        Christy evidently didn't agree with Bob's memory management.
    */
    RelinquishMagickMemory(histogram);

    if (dc_copy)
    {
        // Do not trace destruction
        DestroyImage(dc_copy);
    }

    RB_GC_GUARD(hash);
    RB_GC_GUARD(pixel);

    return hash;
}


/**
 * Store all the profiles in the profile in the target image. Called from
 * Image_color_profile_eq and Image_iptc_profile_eq.
 *
 * No Ruby usage (internal function)
 *
 * @param self this object
 * @param name profile name
 * @param profile an IPTC or ICC profile
 * @return self
 */
static VALUE
set_profile(VALUE self, const char *name, VALUE profile)
{
    Image *image, *profile_image;
    ImageInfo *info;
    const MagickInfo *m;
    ExceptionInfo *exception;
    char *profile_name;
    char *profile_blob;
    size_t profile_length;
    const StringInfo *profile_data;

    image = rm_check_frozen(self);

    profile_blob = rm_str2cstr(profile, &profile_length);

    exception = AcquireExceptionInfo();
    m = GetMagickInfo(name, exception);
    CHECK_EXCEPTION();
    if (!m)
    {
        DestroyExceptionInfo(exception);
        rb_raise(rb_eArgError, "unknown name: %s", name);
    }

    info = CloneImageInfo(NULL);
    if (!info)
    {
        rb_raise(rb_eNoMemError, "not enough memory to continue");
    }

    strlcpy(info->magick, m->name, sizeof(info->magick));

    GVL_STRUCT_TYPE(BlobToImage) args = { info, profile_blob, profile_length, exception };
    profile_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(BlobToImage), &args);
    DestroyImageInfo(info);
    CHECK_EXCEPTION();

    ResetImageProfileIterator(profile_image);
    profile_name = GetNextImageProfile(profile_image);
    while (profile_name)
    {
        /* Hack for versions of ImageMagick where the meta coder would change the iptc profile into an 8bim profile */
        if (rm_strcasecmp("8bim", profile_name) == 0 && rm_strcasecmp("iptc", name) == 0)
        {
#if defined(IMAGEMAGICK_7)
            GVL_STRUCT_TYPE(ProfileImage) args = { image, name, profile_blob, profile_length, exception };
            CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ProfileImage), &args);
            if (rm_should_raise_exception(exception, RetainExceptionRetention))
#else
            GVL_STRUCT_TYPE(ProfileImage) args = { image, name, profile_blob, profile_length, MagickFalse };
            CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ProfileImage), &args);
            if (rm_should_raise_exception(&image->exception, RetainExceptionRetention))
#endif
            {
                break;
            }
        }
        else if (rm_strcasecmp(profile_name, name) == 0)
        {
            profile_data = GetImageProfile(profile_image, profile_name);
            if (profile_data)
            {
#if defined(IMAGEMAGICK_7)
                GVL_STRUCT_TYPE(ProfileImage) args = { image, name, GetStringInfoDatum(profile_data), GetStringInfoLength(profile_data), exception };
                CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ProfileImage), &args);
                if (rm_should_raise_exception(exception, RetainExceptionRetention))
#else
                GVL_STRUCT_TYPE(ProfileImage) args = { image, name, GetStringInfoDatum(profile_data), GetStringInfoLength(profile_data), MagickFalse };
                CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ProfileImage), &args);
                if (rm_should_raise_exception(&image->exception, RetainExceptionRetention))
#endif
                {
                    break;
                }
            }
        }
        profile_name = GetNextImageProfile(profile_image);
    }

    DestroyImage(profile_image);

#if defined(IMAGEMAGICK_7)
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    DestroyExceptionInfo(exception);
    rm_check_image_exception(image, RetainOnError);
#endif

    return self;
}


/**
 * Return the ICC color profile as a String.
 *
 * - If there is no profile, returns ""
 * - This method has no real use but is retained for compatibility with earlier releases of RMagick,
 *   where it had no real use either.
 *
 * @return [String, nil] the ICC color profile
 */
VALUE
Image_color_profile(VALUE self)
{
    Image *image;
    const StringInfo *profile;

    image = rm_check_destroyed(self);
    profile = GetImageProfile(image, "icc");
    if (!profile)
    {
        return Qnil;
    }

    return rb_str_new((char *)profile->datum, (long)profile->length);

}


/**
 * Set the ICC color profile.
 *
 * - Pass nil to remove any existing profile.
 * - Removes any existing profile before adding the new one.
 *
 * @param profile [String, nil] the profile to set
 * @return [String, nil] the given profile
 */
VALUE
Image_color_profile_eq(VALUE self, VALUE profile)
{
    Image_delete_profile(self, rb_str_new2("ICC"));
    if (profile != Qnil)
    {
        set_profile(self, "ICC", profile);
    }
    return profile;
}


/**
 * Change the color value of any pixel that matches target_color and is an immediate neighbor.
 *
 * @param target_color [Magick::Pixel, String] the target color
 * @param fill_color [Magick::Pixel, String] the color to fill
 * @param xv [Numeric] the x position
 * @param yv [Numeric] the y position
 * @param method [Magick::PaintMethod] the method to call
 * @return [Magick::Image] a new image
 * @see Image#opaque
 */
VALUE
Image_color_flood_fill(VALUE self, VALUE target_color, VALUE fill_color,
                       VALUE xv, VALUE yv, VALUE method)
{
    Image *image, *new_image;
    PixelColor target;
    DrawInfo *draw_info;
    PixelColor fill;
    long x, y;
    int fill_method;
    MagickPixel target_mpp;
    MagickBooleanType invert;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

    // The target and fill args can be either a color name or
    // a Magick::Pixel.
    Color_to_PixelColor(&target, target_color);
    Color_to_PixelColor(&fill, fill_color);

    x = NUM2LONG(xv);
    y = NUM2LONG(yv);
    if ((unsigned long)x > image->columns || (unsigned long)y > image->rows)
    {
        rb_raise(rb_eArgError, "target out of range. %lux%lu given, image is %" RMIuSIZE "x%" RMIuSIZE "",
                 x, y, image->columns, image->rows);
    }

    VALUE_TO_ENUM(method, fill_method, PaintMethod);
    if (!(fill_method == FloodfillMethod || fill_method == FillToBorderMethod))
    {
        rb_raise(rb_eArgError, "paint method must be FloodfillMethod or "
                 "FillToBorderMethod (%d given)", fill_method);
    }

    draw_info = CloneDrawInfo(NULL, NULL);
    if (!draw_info)
    {
        rb_raise(rb_eNoMemError, "not enough memory to continue");
    }
    draw_info->fill = fill;

    new_image = rm_clone_image(image);

    rm_init_magickpixel(new_image, &target_mpp);
    if (fill_method == FillToBorderMethod)
    {
        invert = MagickTrue;
        target_mpp.red   = (MagickRealType) image->border_color.red;
        target_mpp.green = (MagickRealType) image->border_color.green;
        target_mpp.blue  = (MagickRealType) image->border_color.blue;
    }
    else
    {
        invert = MagickFalse;
        target_mpp.red   = (MagickRealType) target.red;
        target_mpp.green = (MagickRealType) target.green;
        target_mpp.blue  = (MagickRealType) target.blue;
    }

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(FloodfillPaintImage) args = { new_image, draw_info, &target_mpp, x, y, invert, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(FloodfillPaintImage), &args);
    DestroyDrawInfo(draw_info);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(FloodfillPaintImage) args = { new_image, DefaultChannels, draw_info, &target_mpp, x, y, invert };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(FloodfillPaintImage), &args);

    DestroyDrawInfo(draw_info);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Blend the fill color specified by "target" with each pixel in the image. Specify the percentage
 * blend for each r, g, b component.
 *
 * @overload colorize(red, green, blue, target)
 *   @param red [Numeric] The percentage of the fill color red
 *   @param green [Numeric] The percentage of the fill color green
 *   @param blue [Numeric] The percentage of the fill color blue
 *   @param target [Magick::Pixel, String] the color name
 *
 * @overload colorize(red, green, blue, matte, target)
 *   @param red [Numeric] The percentage of the fill color red
 *   @param green [Numeric] The percentage of the fill color green
 *   @param blue [Numeric] The percentage of the fill color blue
 *   @param matte [Numeric] The percentage of the fill color transparency
 *   @param target [Magick::Pixel, String] the color name
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_colorize(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double red, green, blue, matte;
    char opacity[50];
    PixelColor target;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    if (argc == 4)
    {
        red   = floor(100*NUM2DBL(argv[0])+0.5);
        green = floor(100*NUM2DBL(argv[1])+0.5);
        blue  = floor(100*NUM2DBL(argv[2])+0.5);
        Color_to_PixelColor(&target, argv[3]);
        snprintf(opacity, sizeof(opacity), "%f/%f/%f", red, green, blue);
    }
    else if (argc == 5)
    {
        red   = floor(100*NUM2DBL(argv[0])+0.5);
        green = floor(100*NUM2DBL(argv[1])+0.5);
        blue  = floor(100*NUM2DBL(argv[2])+0.5);
        matte = floor(100*NUM2DBL(argv[3])+0.5);
        Color_to_PixelColor(&target, argv[4]);
        snprintf(opacity, sizeof(opacity), "%f/%f/%f/%f", red, green, blue, matte);
    }
    else
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 4 or 5)", argc);
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(ColorizeImage) args = { image, opacity, &target, exception };
#else
    GVL_STRUCT_TYPE(ColorizeImage) args = { image, opacity, target, exception };
#endif
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ColorizeImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Return the color in the colormap at the specified index. If a new color is specified, replaces
 * the color at the index with the new color.
 *
 * @overload colormap(index)
 *   @param index [Numeric] A number between 0 and the number of colors in the color map. If the
 *     value is out of range, colormap raises an IndexError.  You can get the number of colors in
 *     the color map from the colors attribute.
 *
 * @overload colormap(index, new_color)
 *   @param index [Numeric] A number between 0 and the number of colors in the color map. If the
 *     value is out of range, colormap raises an IndexError.  You can get the number of colors in
 *     the color map from the colors attribute.
 *   @param new_color [Magick::Pixel, String] the color name
 *
 * @return [String] the name of the color at the specified location in the color map
 */
VALUE
Image_colormap(int argc, VALUE *argv, VALUE self)
{
    Image *image;
    unsigned long idx;
    PixelColor color, new_color;

    image = rm_check_destroyed(self);

    // We can handle either 1 or 2 arguments. Nothing else.
    if (argc == 0 || argc > 2)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or 2)", argc);
    }

    idx = NUM2ULONG(argv[0]);
    if (idx > QuantumRange)
    {
        rb_raise(rb_eIndexError, "index out of range");
    }

    // If this is a simple "get" operation, ensure the image has a colormap.
    if (argc == 1)
    {
        if (!image->colormap)
        {
            rb_raise(rb_eIndexError, "image does not contain a colormap");
        }
        // Validate the index

        if (idx > image->colors-1)
        {
            rb_raise(rb_eIndexError, "index out of range");
        }
        return rm_pixelcolor_to_color_name(image, &image->colormap[idx]);
    }

    // This is a "set" operation. Things are different.

    rb_check_frozen(self);

    // Replace with new color? The arg can be either a color name or
    // a Magick::Pixel.
    Color_to_PixelColor(&new_color, argv[1]);

    // Handle no colormap or current colormap too small.
    if (!image->colormap || idx > image->colors-1)
    {
        PixelColor black;
        unsigned long i;

        memset(&black, 0, sizeof(black));

        if (!image->colormap)
        {
            image->colormap = (PixelColor *)magick_safe_malloc((idx+1), sizeof(PixelColor));
            image->colors = 0;
        }
        else
        {
            image->colormap = (PixelColor *)magick_safe_realloc(image->colormap, (idx+1), sizeof(PixelColor));
        }

        for (i = image->colors; i < idx; i++)
        {
            image->colormap[i] = black;
        }
        image->colors = idx+1;
    }

    // Save the current color so we can return it. Set the new color.
    color = image->colormap[idx];
    image->colormap[idx] = new_color;

    return rm_pixelcolor_to_color_name(image, &color);
}

/**
 * Get the number of colors in the colormap.
 *
 * @return [Integer] the number of colors
 */
VALUE
Image_colors(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, colors, ulong, &rm_image_data_type);
}

/**
 * Return the Image pixel interpretation. If the colorspace is RGB the pixels are red, green,
 * blue. If matte is true, then red, green, blue, and index. If it is CMYK, the pixels are cyan,
 * yellow, magenta, black. Otherwise the colorspace is ignored.
 *
 * @return [Magick::ColorspaceType] the colorspace
 */
VALUE
Image_colorspace(VALUE self)
{
    Image *image;

    image = rm_check_destroyed(self);
    return ColorspaceType_find(image->colorspace);
}


/**
 * Set the image's colorspace.
 *
 * @param colorspace [Magick::ColorspaceType] the colorspace
 * @return [Magick::ColorspaceType] the given colorspace
 */
VALUE
Image_colorspace_eq(VALUE self, VALUE colorspace)
{
    Image *image;
    ColorspaceType new_cs;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_frozen(self);
    VALUE_TO_ENUM(colorspace, new_cs, ColorspaceType);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(TransformImageColorspace) args = { image, new_cs, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(TransformImageColorspace), &args);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(TransformImageColorspace) args = { image, new_cs };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(TransformImageColorspace), &args);
    rm_check_image_exception(image, RetainOnError);
#endif

    return colorspace;
}


/**
 * Get image columns.
 *
 * @return [Integer] the columns
 */
VALUE
Image_columns(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, columns, int, &rm_image_data_type);
}


/**
 * Compare one or more channels in two images and returns the specified distortion metric and a
 * comparison image.
 *
 * @overload compare_channel(image, metric, channel = Magick::AllChannels)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param metric [Magick::MetricType] The desired distortion metric.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload compare_channel(image, metric, channel = Magick::AllChannels)
 *   When a block is given, compare_channel yields with a block argument you can optionally use to
 *   set attributes.
 *   - options.highlight_color = color
 *     - Emphasize pixel differences with this color. The default is partially transparent red.
 *   - options.lowlight_color = color
 *     - Demphasize pixel differences with this color. The default is partially transparent white.
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param metric [Magick::MetricType] The desired distortion metric.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *   @yield [opt_args]
 *   @yieldparam opt_args [Magick::OptionalMethodArguments]
 *
 * @overload compare_channel(image, metric, *channels)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param metric [Magick::MetricType] The desired distortion metric.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @overload compare_channel(image, metric, *channels)
 *   When a block is given, compare_channel yields with a block argument you can optionally use to
 *   set attributes.
 *   - options.highlight_color = color
 *     - Emphasize pixel differences with this color. The default is partially transparent red.
 *   - options.lowlight_color = color
 *     - Demphasize pixel differences with this color. The default is partially transparent white.
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param metric [Magick::MetricType] The desired distortion metric.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *   @yield [opt_args]
 *   @yieldparam opt_args [Magick::OptionalMethodArguments]
 *
 * @return [Array] The first element is a difference image, the second is a the value of the
 *   computed distortion represented as a Float.
 */
VALUE
Image_compare_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *r_image, *difference_image;
    double distortion;
    VALUE ary, ref;
    MetricType metric_type;
    ChannelType channels;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    channels = extract_channels(&argc, argv);

    if (argc > 2)
    {
        raise_ChannelType_error(argv[argc-1]);
    }
    if (argc != 2)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 or more)", argc);
    }

    rm_get_optional_arguments(self);

    ref = rm_cur_image(argv[0]);
    r_image = rm_check_destroyed(ref);

    VALUE_TO_ENUM(argv[1], metric_type, MetricType);

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(CompareImages) args = { image, r_image, metric_type, &distortion, exception };
    difference_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompareImages), &args);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(CompareImageChannels) args = { image, r_image, channels, metric_type, &distortion, exception };
    difference_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompareImageChannels), &args);
#endif
    rm_check_exception(exception, difference_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    ary = rb_ary_new2(2);
    rb_ary_store(ary, 0, rm_image_new(difference_image));
    rb_ary_store(ary, 1, rb_float_new(distortion));

    RB_GC_GUARD(ary);
    RB_GC_GUARD(ref);

    return ary;
}


/**
 * Return the composite operator attribute.
 *
 * @return [Magick::CompositeOperator] the composite operator
 */
VALUE
Image_compose(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return CompositeOperator_find(image->compose);
}


/**
 * Set the composite operator attribute.
 *
 * @param compose_arg [Magick::CompositeOperator] the composite operator
 * @return [Magick::CompositeOperator] the given value
 */
VALUE
Image_compose_eq(VALUE self, VALUE compose_arg)
{
    Image *image = rm_check_frozen(self);
    VALUE_TO_ENUM(compose_arg, image->compose, CompositeOperator);
    return compose_arg;
}

/**
 * Call CompositeImage.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - The other image can be either an Image or an Image.
 *   - The use of the GravityType to position the composited image is based on
 *     Magick++.
 *   - The `gravity' argument has the same effect as the -gravity option does in
 *     the `composite' utility.
 *
 * @param bang whether the bang (!) version of the method was called
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @param channels
 * @return self if bang, otherwise new composited image
 * @see Image_composite
 * @see Image_composite_bang
 */
static VALUE
composite(int bang, int argc, VALUE *argv, VALUE self, ChannelType channels)
{
    Image *image, *new_image;
    Image *comp_image;
    CompositeOperator composite_op = UndefinedCompositeOp;
    GravityType gravity;
    VALUE comp;
    signed long x_offset = 0;
    signed long y_offset = 0;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

    if (bang)
    {
        rb_check_frozen(self);
    }
    if (argc < 3 || argc > 5)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 3, 4, or 5)", argc);
    }


    comp = rm_cur_image(argv[0]);
    comp_image = rm_check_destroyed(comp);
    RB_GC_GUARD(comp);

    switch (argc)
    {
        case 3:                 // argv[1] is gravity, argv[2] is composite_op
            VALUE_TO_ENUM(argv[1], gravity, GravityType);
            VALUE_TO_ENUM(argv[2], composite_op, CompositeOperator);

            // convert gravity to x, y offsets
            switch (gravity)
            {
                case ForgetGravity:
                case NorthWestGravity:
                    x_offset = 0;
                    y_offset = 0;
                    break;
                case NorthGravity:
                    x_offset = ((long)(image->columns) - (long)(comp_image->columns)) / 2;
                    y_offset = 0;
                    break;
                case NorthEastGravity:
                    x_offset = (long)(image->columns) - (long)(comp_image->columns);
                    y_offset = 0;
                    break;
                case WestGravity:
                    x_offset = 0;
                    y_offset = ((long)(image->rows) - (long)(comp_image->rows)) / 2;
                    break;
                case CenterGravity:
                default:
                    x_offset = ((long)(image->columns) - (long)(comp_image->columns)) / 2;
                    y_offset = ((long)(image->rows) - (long)(comp_image->rows)) / 2;
                    break;
                case EastGravity:
                    x_offset = (long)(image->columns) - (long)(comp_image->columns);
                    y_offset = ((long)(image->rows) - (long)(comp_image->rows)) / 2;
                    break;
                case SouthWestGravity:
                    x_offset = 0;
                    y_offset = (long)(image->rows) - (long)(comp_image->rows);
                    break;
                case SouthGravity:
                    x_offset = ((long)(image->columns) - (long)(comp_image->columns)) / 2;
                    y_offset = (long)(image->rows) - (long)(comp_image->rows);
                    break;
                case SouthEastGravity:
                    x_offset = (long)(image->columns) - (long)(comp_image->columns);
                    y_offset = (long)(image->rows) - (long)(comp_image->rows);
                    break;
            }
            break;

        case 4:                 // argv[1], argv[2] is x_off, y_off,
            // argv[3] is composite_op
            x_offset = NUM2LONG(argv[1]);
            y_offset = NUM2LONG(argv[2]);
            VALUE_TO_ENUM(argv[3], composite_op, CompositeOperator);
            break;

        case 5:
            VALUE_TO_ENUM(argv[1], gravity, GravityType);
            x_offset = NUM2LONG(argv[2]);
            y_offset = NUM2LONG(argv[3]);
            VALUE_TO_ENUM(argv[4], composite_op, CompositeOperator);

            switch (gravity)
            {
                case NorthEastGravity:
                case EastGravity:
                case SouthEastGravity:
                    x_offset = ((long)(image->columns) - (long)(comp_image->columns)) - x_offset;
                    break;
                case NorthGravity:
                case SouthGravity:
                case CenterGravity:
                    x_offset += (long)(image->columns/2) - (long)(comp_image->columns/2);
                    break;
                default:
                    break;
            }
            switch (gravity)
            {
                case SouthWestGravity:
                case SouthGravity:
                case SouthEastGravity:
                    y_offset = ((long)(image->rows) - (long)(comp_image->rows)) - y_offset;
                    break;
                case EastGravity:
                case WestGravity:
                case CenterGravity:
                    y_offset += (long)(image->rows/2) - (long)(comp_image->rows/2);
                    break;
                case NorthEastGravity:
                case NorthGravity:
                default:
                    break;
            }
            break;

    }

    if (bang)
    {
#if defined(IMAGEMAGICK_7)
        exception = AcquireExceptionInfo();
        BEGIN_CHANNEL_MASK(image, channels);
        GVL_STRUCT_TYPE(CompositeImage) args = { image, comp_image, composite_op, MagickTrue, x_offset, y_offset, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompositeImage), &args);
        END_CHANNEL_MASK(image);
        CHECK_EXCEPTION();
        DestroyExceptionInfo(exception);
#else
        GVL_STRUCT_TYPE(CompositeImageChannel) args = { image, channels, composite_op, comp_image, x_offset, y_offset };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompositeImageChannel), &args);
        rm_check_image_exception(image, RetainOnError);
#endif

        return self;
    }
    else
    {
        new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
        exception = AcquireExceptionInfo();
        BEGIN_CHANNEL_MASK(new_image, channels);
        GVL_STRUCT_TYPE(CompositeImage) args = { new_image, comp_image, composite_op, MagickTrue, x_offset, y_offset, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompositeImage), &args);
        END_CHANNEL_MASK(new_image);
        rm_check_exception(exception, new_image, DestroyOnError);
        DestroyExceptionInfo(exception);
#else
        GVL_STRUCT_TYPE(CompositeImageChannel) args = { new_image, channels, composite_op, comp_image, x_offset, y_offset };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompositeImageChannel), &args);
        rm_check_image_exception(new_image, DestroyOnError);
#endif

        return rm_image_new(new_image);
    }
}


/**
 * Composites src onto dest using the specified composite operator.
 * In-place form of {Magick::Image#composite}.
 *
 * @overload composite!(image, x_off, y_off, composite_op)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param x_off [Numeric] the x-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param y_off [Numeric] the y-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *
 * @overload composite!(image, gravity, composite_op)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param gravity [Magick::GravityType] A GravityType value that specifies the location of img on
 *     image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *
 * @overload composite!(image, gravity, x_off, y_off, composite_op)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param gravity [Magick::GravityType] A GravityType value that specifies the location of img on
 *     image.
 *   @param x_off [Numeric] the x-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param y_off [Numeric] the y-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator.
 *
 * @return [Magick::Image] a new image
 * @see Image#composite
 */
VALUE
Image_composite_bang(int argc, VALUE *argv, VALUE self)
{
    return composite(True, argc, argv, self, DefaultChannels);
}


/**
 * Composites src onto dest using the specified composite operator.
 *
 * @overload composite(image, x_off, y_off, composite_op)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param x_off [Numeric] the x-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param y_off [Numeric] the y-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *
 * @overload composite(image, gravity, composite_op)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param gravity [Magick::GravityType] A GravityType value that specifies the location of img on
 *     image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *
 * @overload composite(image, gravity, x_off, y_off, composite_op)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param gravity [Magick::GravityType] A GravityType value that specifies the location of img on
 *     image.
 *   @param x_off [Numeric] the x-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param y_off [Numeric] the y-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator.
 *
 * @return [Magick::Image] a new image
 * @see Image#composite!
 */
VALUE
Image_composite(int argc, VALUE *argv, VALUE self)
{
    return composite(False, argc, argv, self, DefaultChannels);
}


/**
 * Composite the source over the destination image as dictated by the affine transform.
 *
 * @param source [Magick::Image, Magick::ImageList] the source image
 * @param affine_matrix [Magick::AffineMatrix] affine transform matrix
 * @return [Magick::Image] a new image
 */
VALUE
Image_composite_affine(VALUE self, VALUE source, VALUE affine_matrix)
{
    Image *image, *composite_image, *new_image;
    AffineMatrix affine;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    composite_image = rm_check_destroyed(rm_cur_image(source));

    Export_AffineMatrix(&affine, affine_matrix);
    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(DrawAffineImage) args = { new_image, composite_image, &affine, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(DrawAffineImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(DrawAffineImage) args = { new_image, composite_image, &affine };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(DrawAffineImage), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Call CompositeImageChannel.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - Default channel is AllChannels
 *
 * @param bang whether the bang (!) version of the method was called
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @return self if bang, otherwise a new image
 * @see Image_composite_channel
 * @see Image_composite_channel_bang
 */
static VALUE
composite_channel(int bang, int argc, VALUE *argv, VALUE self)
{
    ChannelType channels;

    // Check destroyed before validating the arguments
    rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    // There must be 3, 4, or 5 remaining arguments.
    if (argc < 3)
    {
        rb_raise(rb_eArgError, "composite operator not specified");
    }
    else if (argc > 5)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    return composite(bang, argc, argv, self, channels);
}


/**
 * Composite the source over the destination image channel as dictated by the affine transform.
 *
 * @overload composite_channel(image, x_off, y_off, composite_op, channel = Magick::AllChannels)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param x_off [Numeric] the x-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param y_off [Numeric] the y-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload composite_channel(image, x_off, y_off, composite_op, *channels)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param x_off [Numeric] the x-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param y_off [Numeric] the y-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @overload composite_channel(image, gravity, composite_op, channel = Magick::AllChannels)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param gravity [Magick::GravityType] A GravityType value that specifies the location of img on
 *     image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload composite_channel(image, gravity, composite_op, *channels)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param gravity [Magick::GravityType] A GravityType value that specifies the location of img on
 *     image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @overload composite_channel(image, gravity, x_off, y_off, composite_op, channel = Magick::AllChannels)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param gravity [Magick::GravityType] A GravityType value that specifies the location of img on
 *     image.
 *   @param x_off [Numeric] the x-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param y_off [Numeric] the y-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload composite_channel(image, gravity, x_off, y_off, composite_op, *channels)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param gravity [Magick::GravityType] A GravityType value that specifies the location of img on
 *     image.
 *   @param x_off [Numeric] the x-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param y_off [Numeric] the y-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 * @see Image#composite
 */
VALUE
Image_composite_channel(int argc, VALUE *argv, VALUE self)
{
    return composite_channel(False, argc, argv, self);
}


/**
 * Composite the source over the destination image channel as dictated by the affine transform.
 * In-place form of {Image#composite_channel}.
 *
 * @overload composite_channel!(image, x_off, y_off, composite_op, channel = Magick::AllChannels)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param x_off [Numeric] the x-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param y_off [Numeric] the y-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload composite_channel!(image, x_off, y_off, composite_op, *channels)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param x_off [Numeric] the x-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param y_off [Numeric] the y-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @overload composite_channel!(image, gravity, composite_op, channel = Magick::AllChannels)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param gravity [Magick::GravityType] A GravityType value that specifies the location of img on
 *     image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload composite_channel!(image, gravity, composite_op, *channels)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param gravity [Magick::GravityType] A GravityType value that specifies the location of img on
 *     image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @overload composite_channel!(image, gravity, x_off, y_off, composite_op, channel = Magick::AllChannels)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param gravity [Magick::GravityType] A GravityType value that specifies the location of img on
 *     image.
 *   @param x_off [Numeric] the x-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param y_off [Numeric] the y-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload composite_channel!(image, gravity, x_off, y_off, composite_op, *channels)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param gravity [Magick::GravityType] A GravityType value that specifies the location of img on
 *     image.
 *   @param x_off [Numeric] the x-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param y_off [Numeric] the y-offset of the composited image, measured from the upper-left
 *     corner of the image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 * @see Image#composite_channel
 * @see Image#composite!
 */
VALUE
Image_composite_channel_bang(int argc, VALUE *argv, VALUE self)
{
    return composite_channel(True, argc, argv, self);
}


/**
 * Merge the source and destination images according to the formula
 *   a*Sc*Dc + b*Sc + c*Dc + d
 * where Sc is the source pixel and Dc is the destination pixel.
 *
 * @overload composite_mathematics(image, a, b, c, d, gravity)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param a [Numeric] See the description.
 *   @param b [Numeric] See the description.
 *   @param c [Numeric] See the description.
 *   @param d [Numeric] See the description.
 *   @param gravity [Magick::GravityType] the gravity type
 *
 * @overload composite_mathematics(image, a, b, c, d, x_off, y_off)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param a [Numeric] See the description.
 *   @param b [Numeric] See the description.
 *   @param c [Numeric] See the description.
 *   @param d [Numeric] See the description.
 *   @param x_off [Numeric] The x-offset of the composited image, measured relative to the gravity
 *     argument.
 *   @param y_off [Numeric] The y-offset of the composited image, measured relative to the gravity
 *     argument.
 *
 * @overload composite_mathematics(image, a, b, c, d, gravity, x_off, y_off)
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param a [Numeric] See the description.
 *   @param b [Numeric] See the description.
 *   @param c [Numeric] See the description.
 *   @param d [Numeric] See the description.
 *   @param gravity [Magick::GravityType] the gravity type
 *   @param x_off [Numeric] The x-offset of the composited image, measured relative to the gravity
 *     argument.
 *   @param y_off [Numeric] The y-offset of the composited image, measured relative to the gravity
 *     argument.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_composite_mathematics(int argc, VALUE *argv, VALUE self)
{
    Image *composite_image;
    VALUE args[5];
    signed long x_off = 0L;
    signed long y_off = 0L;
    GravityType gravity = NorthWestGravity;
    char compose_args[200];

    rm_check_destroyed(self);

    switch (argc)
    {
        case 8:
            VALUE_TO_ENUM(argv[5], gravity, GravityType);
            x_off = NUM2LONG(argv[6]);
            y_off = NUM2LONG(argv[7]);
            break;
        case 7:
            x_off = NUM2LONG(argv[5]);
            y_off = NUM2LONG(argv[6]);
            break;
        case 6:
            VALUE_TO_ENUM(argv[5], gravity, GravityType);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (got %d, expected 6 to 8)", argc);
            break;
    }

    composite_image = rm_check_destroyed(rm_cur_image(argv[0]));

    snprintf(compose_args, sizeof(compose_args), "%-.16g,%-.16g,%-.16g,%-.16g", NUM2DBL(argv[1]), NUM2DBL(argv[2]), NUM2DBL(argv[3]), NUM2DBL(argv[4]));
    SetImageArtifact(composite_image, "compose:args", compose_args);

    // Call composite(False, gravity, x_off, y_off, MathematicsCompositeOp, DefaultChannels)
    args[0] = argv[0];
    args[1] = GravityType_find(gravity);
    args[2] = LONG2FIX(x_off);
    args[3] = LONG2FIX(y_off);
    args[4] = CompositeOperator_find(MathematicsCompositeOp);

    return composite(False, 5, args, self, DefaultChannels);
}


/**
 * Emulate the -tile option to the composite command.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - Default composite_op is Magick::OverCompositeOp
 *   - Default channel is AllChannels
 *
 * @param bang whether the bang (!) version of the method was called
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @return self if bang, otherwise a new image
 * @see Image_composite_tiled
 * @see Image_composite_tiled_bang
 * @see wand/composite.c in ImageMagick (6.2.4)
 */
static VALUE
composite_tiled(int bang, int argc, VALUE *argv, VALUE self)
{
    Image *image;
    Image *comp_image;
    CompositeOperator composite_op = OverCompositeOp;
    long x, y;
    unsigned long columns;
    ChannelType channels;
    MagickStatusType status;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    // Ensure image and composite_image aren't destroyed.
    if (bang)
    {
        image = rm_check_frozen(self);
    }
    else
    {
        image = rm_check_destroyed(self);
    }

    channels = extract_channels(&argc, argv);

    switch (argc)
    {
        case 2:
            VALUE_TO_ENUM(argv[1], composite_op, CompositeOperator);
        case 1:
            break;
        case 0:
            rb_raise(rb_eArgError, "wrong number of arguments (0 for 1 or more)");
            break;
        default:
            raise_ChannelType_error(argv[argc-1]);
            break;
    }

    comp_image = rm_check_destroyed(rm_cur_image(argv[0]));

    if (!bang)
    {
        image = rm_clone_image(image);
    }

    SetImageArtifact(comp_image, "modify-outside-overlay", "false");

    status = MagickTrue;
    columns = comp_image->columns;

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
#endif

    // Tile
    for (y = 0; y < (long) image->rows; y += comp_image->rows)
    {
        for (x = 0; status == MagickTrue && x < (long) image->columns; x += columns)
        {
#if defined(IMAGEMAGICK_7)
            BEGIN_CHANNEL_MASK(image, channels);
            GVL_STRUCT_TYPE(CompositeImage) args = { image, comp_image, composite_op, MagickTrue, x, y, exception };
            void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompositeImage), &args);
            status = reinterpret_cast<MagickStatusType &>(ret);
            END_CHANNEL_MASK(image);
            rm_check_exception(exception, image, bang ? RetainOnError: DestroyOnError);
#else
            GVL_STRUCT_TYPE(CompositeImageChannel) args = { image, channels, composite_op, comp_image, x, y };
            void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompositeImageChannel), &args);
            status = reinterpret_cast<MagickStatusType &>(ret);
            rm_check_image_exception(image, bang ? RetainOnError: DestroyOnError);
#endif
        }
    }

#if defined(IMAGEMAGICK_7)
    DestroyExceptionInfo(exception);
#endif

    return bang ? self : rm_image_new(image);
}


/**
 * Composites multiple copies of the source image across and down the image,
 * producing the same results as ImageMagick's composite command with the -tile option.
 *
 * @overload composite_tiled(src, composite_op = Magick::OverCompositeOp, channel = Magick::AllChannels)
 *   @param src [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload composite_tiled(src, composite_op = Magick::OverCompositeOp, *channels)
 *   @param src [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 * @see Image#composite_tiled!
 */
VALUE
Image_composite_tiled(int argc, VALUE *argv, VALUE self)
{
    return composite_tiled(False, argc, argv, self);
}


/**
 * Composites multiple copies of the source image across and down the image, producing the same
 * results as ImageMagick's composite command with the -tile option.
 * In-place form of {Magick::Image#composite_tiled}.
 *
 * @overload composite_tiled!(src, composite_op = Magick::OverCompositeOp, channel = Magick::AllChannels)
 *   @param src [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload composite_tiled!(src, composite_op = Magick::OverCompositeOp, *channels)
 *   @param src [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param composite_op [Magick::CompositeOperator] the composite operator
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 * @see Image#composite_tiled
 */
VALUE
Image_composite_tiled_bang(int argc, VALUE *argv, VALUE self)
{
    return composite_tiled(True, argc, argv, self);
}


/**
 * Get the compression attribute.
 *
 * @return [Magick::CompressionType] the compression
 */
VALUE
Image_compression(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return CompressionType_find(image->compression);
}

/**
 * Set the compression attribute.
 *
 * @param compression [Magick::CompressionType] the compression
 * @return [Magick::CompressionType] the given compression
 */
VALUE
Image_compression_eq(VALUE self, VALUE compression)
{
    Image *image = rm_check_frozen(self);
    VALUE_TO_ENUM(compression, image->compression, CompressionType);
    return compression;
}

/**
 * Removes duplicate or unused entries in the colormap.
 * Only PseudoClass images have a colormap.
 * If the image is DirectClass then compress_colormap! converts it to PseudoClass.
 *
 * @return [Magick::Image] self
 */
VALUE
Image_compress_colormap_bang(VALUE self)
{
    Image *image;
    MagickBooleanType okay;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_frozen(self);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(CompressImageColormap) args = { image, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompressImageColormap), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(CompressImageColormap) args = { image };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompressImageColormap), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    rm_check_image_exception(image, RetainOnError);
#endif
    if (!okay)
    {
        rb_warning("CompressImageColormap failed (probably DirectClass image)");
    }

    return self;
}

/**
 * Creates an Image from the supplied pixel data. The pixel data must be in scanline order,
 * top-to-bottom. The pixel data is an array of either all Fixed or all Float elements. If Fixed,
 * the elements must be in the range [0..QuantumRange]. If Float, the elements must be normalized
 * [0..1]. The "map" argument reflects the expected ordering of the pixel array. It can be any
 * combination or order of R = red, G = green, B = blue, A = alpha, C = cyan, Y = yellow, M =
 * magenta, K = black, or I = intensity (for grayscale).
 *
 * The pixel array must have width X height X strlen(map) elements.
 *
 * @param width_arg [Numeric] The number of columns in the image
 * @param height_arg [Numeric] The number of rows in the image
 * @param map_arg [String] A string describing the expected ordering of the pixel array.
 *   It can be any combination or order of R = red, G = green, B = blue, A = alpha, C = cyan, Y =
 *   yellow, M = magenta, K = black, or I = intensity (for grayscale).
 * @param pixels_arg [Array<Magick::Pixel>] The pixel data in the array must be stored in scanline order,
 *   left-to-right and top-to-bottom. The elements in the array must be either all Integers or all
 *   Floats. If the elements are Integers, the Integers must be in the range [0..QuantumRange]. If
 *   the elements are Floats, they must be in the range [0..1].
 * @return [Magick::Image] a new image
 */
VALUE
Image_constitute(VALUE klass ATTRIBUTE_UNUSED, VALUE width_arg, VALUE height_arg,
                 VALUE map_arg, VALUE pixels_arg)
{
    Image *new_image;
    VALUE pixel, pixel0;
    long x, npixels;
    size_t width, height, map_l;
    char *map;
    volatile union
    {
        double *f;
        Quantum *i;
        void *v;
    } pixels;
    VALUE pixel_class;
    StorageType stg_type;
    ExceptionInfo *exception;

    // rb_Array converts objects that are not Arrays to Arrays if possible,
    // and raises TypeError if it can't.
    pixels_arg = rb_Array(pixels_arg);

    if (NUM2LONG(width_arg) <= 0 || NUM2LONG(height_arg) <= 0)
    {
        rb_raise(rb_eArgError, "width and height must be greater than zero");
    }

    width = NUM2LONG(width_arg);
    height = NUM2LONG(height_arg);
    map = rm_str2cstr(map_arg, &map_l);

    npixels = width * height * map_l;
    if (RARRAY_LEN(pixels_arg) != npixels)
    {
        rb_raise(rb_eArgError, "wrong number of array elements (%ld for %ld)",
                 RARRAY_LEN(pixels_arg), npixels);
    }

    // Inspect the first element in the pixels array to determine the expected
    // type of all the elements. Allocate the pixel buffer.
    pixel0 = rb_ary_entry(pixels_arg, 0);
    if (rb_obj_is_kind_of(pixel0, rb_cFloat) == Qtrue)
    {
        pixels.f = ALLOC_N(double, npixels);
        stg_type = DoublePixel;
        pixel_class = rb_cFloat;
    }
    else if (rb_obj_is_kind_of(pixel0, rb_cInteger) == Qtrue)
    {
        pixels.i = ALLOC_N(Quantum, npixels);
        stg_type = QuantumPixel;
        pixel_class = rb_cInteger;
    }
    else
    {
        rb_raise(rb_eTypeError, "element 0 in pixel array is %s, must be numeric",
                 rb_class2name(CLASS_OF(pixel0)));
    }



    // Convert the array elements to the appropriate C type, store in pixel
    // buffer.
    for (x = 0; x < npixels; x++)
    {
        pixel = rb_ary_entry(pixels_arg, x);
        if (rb_obj_is_kind_of(pixel, pixel_class) != Qtrue)
        {
            xfree(pixels.v);
            rb_raise(rb_eTypeError, "element %ld in pixel array is %s, expected %s",
                     x, rb_class2name(CLASS_OF(pixel)), rb_class2name(CLASS_OF(pixel0)));
        }
        if (pixel_class == rb_cFloat)
        {
            pixels.f[x] = (float) NUM2DBL(pixel);
            if (pixels.f[x] < 0.0 || pixels.f[x] > 1.0)
            {
                xfree(pixels.v);
                rb_raise(rb_eArgError, "element %ld is out of range [0..1]: %f", x, pixels.f[x]);
            }
        }
        else
        {
            pixels.i[x] = NUM2QUANTUM(pixel);
        }
    }

    // This is based on ConstituteImage in IM 5.5.7
    new_image = rm_acquire_image((ImageInfo *) NULL);
    if (!new_image)
    {
        xfree(pixels.v);
        rb_raise(rb_eNoMemError, "not enough memory to continue.");
    }

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(SetImageExtent) args_SetImageExtent = { new_image, width, height, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageExtent), &args_SetImageExtent);
#else
    GVL_STRUCT_TYPE(SetImageExtent) args_SetImageExtent = { new_image, width, height };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageExtent), &args_SetImageExtent);
    exception = &new_image->exception;
#endif

    if (rm_should_raise_exception(exception, RetainExceptionRetention))
    {
        xfree(pixels.v);
#if defined(IMAGEMAGICK_7)
        DestroyImage(new_image);
        rm_raise_exception(exception);
#else
        rm_check_image_exception(new_image, DestroyOnError);
#endif
    }

#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(SetImageBackgroundColor) args_SetImageBackgroundColor = { new_image, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageBackgroundColor), &args_SetImageBackgroundColor);
#else
    GVL_STRUCT_TYPE(SetImageBackgroundColor) args_SetImageBackgroundColor = { new_image };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageBackgroundColor), &args_SetImageBackgroundColor);
    exception = &new_image->exception;
#endif

    if (rm_should_raise_exception(exception, RetainExceptionRetention))
    {
        xfree(pixels.v);
#if defined(IMAGEMAGICK_7)
        DestroyImage(new_image);
        rm_raise_exception(exception);
#else
        rm_check_image_exception(new_image, DestroyOnError);
#endif
    }

#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(ImportImagePixels) args_ImportImagePixels = { new_image, 0, 0, width, height, map, stg_type, (const void *)pixels.v, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ImportImagePixels), &args_ImportImagePixels);
    xfree(pixels.v);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(ImportImagePixels) args_ImportImagePixels = { new_image, 0, 0, width, height, map, stg_type, (const void *)pixels.v };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ImportImagePixels), &args_ImportImagePixels);
    xfree(pixels.v);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    RB_GC_GUARD(pixel);
    RB_GC_GUARD(pixel0);
    RB_GC_GUARD(pixel_class);

    return rm_image_new(new_image);
}

/**
 * Enhance the intensity differences between the lighter and darker elements of the image.
 *
 * @overload contrast(sharpen = false)
 *   @param sharpen [Boolean] If sharpen is true, the contrast is increased, otherwise it is
 *     reduced.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_contrast(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    MagickBooleanType sharpen = MagickFalse;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    if (argc > 1)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 or 1)", argc);
    }
    else if (argc == 1)
    {
        sharpen = (MagickBooleanType)RTEST(argv[0]);
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(ContrastImage) args = { new_image, sharpen, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ContrastImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(ContrastImage) args = { new_image, sharpen };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ContrastImage), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Convert percentages to #pixels. If the white-point (2nd) argument is not
 * supplied set it to #pixels - black-point.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - No return value: modifies black_point and white_point directly.
 *
 * @param image the image
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param black_point pointer to the black point
 * @param white_point pointer to the white point
 */
static void
get_black_white_point(Image *image, int argc, VALUE *argv, double *black_point, double *white_point)
{
    double pixels;

    pixels = (double) (image->columns * image->rows);

    switch (argc)
    {
        case 2:
            if (rm_check_num2dbl(argv[0]))
            {
                *black_point = NUM2DBL(argv[0]);
            }
            else
            {
                *black_point = pixels * rm_str_to_pct(argv[0], true);
            }
            if (rm_check_num2dbl(argv[1]))
            {
                *white_point = NUM2DBL(argv[1]);
            }
            else
            {
                *white_point = pixels * rm_str_to_pct(argv[1], true);
            }
            break;

        case 1:
            if (rm_check_num2dbl(argv[0]))
            {
                *black_point = NUM2DBL(argv[0]);
            }
            else
            {
                *black_point = pixels * rm_str_to_pct(argv[0], true);
            }
            *white_point = pixels - *black_point;
            break;

        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or 2)", argc);
            break;
    }

    return;
}


/**
 * This method is a simple image enhancement technique that attempts to improve the contrast in an
 * image by `stretching' the range of intensity values it contains to span a desired range of
 * values.  It differs from the more sophisticated histogram equalization in that it can only apply
 * a linear scaling function to the image pixel values.
 *
 * @overload contrast_stretch_channel(black_point, white_point = pixels - black_point, channel = Magick::AllChannels)
 *   @param black_point [Numeric, String] black out at most this many pixels. Specify an absolute
 *     number of pixels as a numeric value, or a percentage as a string in the form 'NN%'.
 *   @param white_point [Numeric, String] burn at most this many pixels. Specify an absolute number
 *     of pixels as a numeric value, or a percentage as a string in the form 'NN%'. This argument
 *     is optional. If not specified the default is `(columns * rows) - black_point`.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload contrast_stretch_channel(black_point, white_point = pixels - black_point, *channels)
 *   @param black_point [Numeric, String] black out at most this many pixels. Specify an absolute
 *     number of pixels as a numeric value, or a percentage as a string in the form 'NN%'.
 *   @param white_point [Numeric, String] burn at most this many pixels. Specify an absolute number of
 *     pixels as a numeric value, or a percentage as a string in the form 'NN%'. This argument is
 *     optional. If not specified the default is all pixels - black_point pixels.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_contrast_stretch_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ChannelType channels;
    double black_point, white_point;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);
    if (argc > 2)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    get_black_white_point(image, argc, argv, &black_point, &white_point);

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(new_image, channels);
    GVL_STRUCT_TYPE(ContrastStretchImage) args = { new_image, black_point, white_point, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ContrastStretchImage), &args);
    END_CHANNEL_MASK(new_image);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(ContrastStretchImageChannel) args = { new_image, channels, black_point, white_point };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ContrastStretchImageChannel), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}

/**
 * Apply a user supplied kernel to the image according to the given mophology method.
 *
 * @param method_v [Magick::MorphologyMethod] the morphology method
 * @param iterations [Numeric] apply the operation this many times (or no change).
 *   A value of -1 means loop until no change found.
 *   How this is applied may depend on the morphology method.
 *   Typically this is a value of 1.
 * @param kernel_v [Magick::KernelInfo] morphology kernel to apply
 * @return [Magick::Image] a new image
 */

VALUE
Image_morphology(VALUE self, VALUE method_v, VALUE iterations, VALUE kernel_v)
{
    static VALUE default_channels_const = 0;

    if(!default_channels_const)
    {
        default_channels_const = rb_const_get(Module_Magick, rb_intern("DefaultChannels"));
    }

    return Image_morphology_channel(self, default_channels_const, method_v, iterations, kernel_v);
}

/**
 * Apply a user supplied kernel to the image channel according to the given mophology method.
 *
 * @param channel_v [Magick::ChannelType] a channel type
 * @param method_v [Magick::MorphologyMethod] the morphology method
 * @param iterations_v [Numeric] apply the operation this many times (or no change).
 *   A value of -1 means loop until no change found.
 *   How this is applied may depend on the morphology method.
 *   Typically this is a value of 1.
 * @param kernel_v [Magick::KernelInfo] morphology kernel to apply
 * @return [Magick::Image] a new image
 */

VALUE
Image_morphology_channel(VALUE self, VALUE channel_v, VALUE method_v, VALUE iterations_v, VALUE kernel_v)
{
    Image *image, *new_image;
    ExceptionInfo *exception;
    MorphologyMethod method;
    ChannelType channel;
    KernelInfo *kernel;
    ssize_t iterations = NUM2LONG(iterations_v);;

    image = rm_check_destroyed(self);

    VALUE_TO_ENUM(method_v, method, MorphologyMethod);
    VALUE_TO_ENUM(channel_v, channel, ChannelType);

    if (TYPE(kernel_v) == T_STRING)
    {
        kernel_v = rb_class_new_instance(1, &kernel_v, Class_KernelInfo);
    }

    if (!rb_obj_is_kind_of(kernel_v, Class_KernelInfo))
    {
        rb_raise(rb_eArgError, "expected String or Magick::KernelInfo");
    }

    TypedData_Get_Struct(kernel_v, KernelInfo, &rm_kernel_info_data_type, kernel);

    exception = AcquireExceptionInfo();

#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channel);
    GVL_STRUCT_TYPE(MorphologyImage) args = { image, method, iterations, kernel, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(MorphologyImage), &args);
    CHANGE_RESULT_CHANNEL_MASK(new_image);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(MorphologyImageChannel) args = { image, channel, method, iterations, kernel, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(MorphologyImageChannel), &args);
#endif
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}

#if defined(IMAGEMAGICK_7)
// TODO: Move this to KernelInfo class as a constructor?
KernelInfo*
convolve_create_kernel_info(unsigned int order, VALUE kernel_arg)
{
    unsigned int x;
    KernelInfo *kernel;
    ExceptionInfo *exception;

    exception = AcquireExceptionInfo();
    kernel = AcquireKernelInfo((const char *) NULL, exception);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
    if (!kernel)
    {
        rb_raise(rb_eNoMemError, "not enough memory to initialize KernelInfo");
    }

    kernel->width = order;
    kernel->height = order;
    kernel->x = (ssize_t)(order - 1) / 2;
    kernel->y = (ssize_t)(order - 1) / 2;
    kernel->values = (MagickRealType *) AcquireAlignedMemory(order, order*sizeof(*kernel->values));
    if (!kernel->values)
    {
        DestroyKernelInfo(kernel);
        rb_raise(rb_eNoMemError, "not enough memory to initialize KernelInfo values");
    }

    for (x = 0; x < order*order; x++)
    {
        VALUE element = rb_ary_entry(kernel_arg, (long)x);
        if (rm_check_num2dbl(element))
        {
            kernel->values[x] = NUM2DBL(element);
        }
        else
        {
            DestroyKernelInfo(kernel);
            rb_raise(rb_eTypeError, "type mismatch: %s given", rb_class2name(CLASS_OF(element)));
        }
    }

    return kernel;
}
#endif

/**
 * Apply a custom convolution kernel to the image.
 *
 * @param order_arg [Numeric] the number of rows and columns in the kernel
 * @param kernel_arg [Array<Float>] An `order*order` matrix of {Float} values.
 * @return [Magick::Image] a new image
 */
VALUE
Image_convolve(VALUE self, VALUE order_arg, VALUE kernel_arg)
{
    Image *image, *new_image;
    size_t order;
    ExceptionInfo *exception;
#if defined(IMAGEMAGICK_7)
    KernelInfo *kernel;
#else
    double *kernel;
    unsigned int x;
#endif

    image = rm_check_destroyed(self);

    if (NUM2INT(order_arg) <= 0)
    {
        rb_raise(rb_eArgError, "order must be non-zero and positive");
    }

    order = NUM2INT(order_arg);
    kernel_arg = rb_Array(kernel_arg);
    rm_check_ary_len(kernel_arg, (long)(order*order));

#if defined(IMAGEMAGICK_7)
    kernel = convolve_create_kernel_info(order, kernel_arg);
#else
    // Convert the kernel array argument to an array of doubles

    kernel = (double *)ALLOC_N(double, order*order);
    for (x = 0; x < (unsigned)(order * order); x++)
    {
        VALUE element = rb_ary_entry(kernel_arg, (long)x);
        if (rm_check_num2dbl(element))
        {
            kernel[x] = NUM2DBL(element);
        }
        else
        {
            xfree((void *)kernel);
            rb_raise(rb_eTypeError, "type mismatch: %s given", rb_class2name(CLASS_OF(element)));
        }
    }
#endif

    exception = AcquireExceptionInfo();

#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(ConvolveImage) args = { image, kernel, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ConvolveImage), &args);
    DestroyKernelInfo(kernel);
#else
    GVL_STRUCT_TYPE(ConvolveImage) args = { image, order, kernel, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ConvolveImage), &args);
    xfree((void *)kernel);
#endif

    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Applies a custom convolution kernel to the specified channel or channels in the image.
 *
 * @overload convolve_channel(order, kernel, channel = Magick::AllChannels)
 *   @param order_arg [Numeric] the number of rows and columns in the kernel
 *   @param kernel_arg [Array<Float>] An `order*order` matrix of {Float} values.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload convolve_channel(order, kernel, *channels)
 *   @param order_arg [Numeric] the number of rows and columns in the kernel
 *   @param kernel_arg [Array<Float>] An `order*order` matrix of {Float} values.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_convolve_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    VALUE ary;
    size_t order;
    ChannelType channels;
    ExceptionInfo *exception;
#if defined(IMAGEMAGICK_7)
    KernelInfo *kernel;
#else
    double *kernel;
    unsigned int x;
#endif

    image = rm_check_destroyed(self);

    channels = extract_channels(&argc, argv);

    // There are 2 required arguments.
    if (argc > 2)
    {
        raise_ChannelType_error(argv[argc-1]);
    }
    if (argc != 2)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 or more)", argc);
    }

    if (NUM2INT(argv[0]) <= 0)
    {
        rb_raise(rb_eArgError, "order must be non-zero and positive");
    }

    order = NUM2INT(argv[0]);
    ary = rb_Array(argv[1]);
    rm_check_ary_len(ary, (long)(order*order));

#if defined(IMAGEMAGICK_7)
    kernel = convolve_create_kernel_info(order, ary);
#else
    kernel = ALLOC_N(double, (long)(order*order));

    // Convert the kernel array argument to an array of doubles
    for (x = 0; x < (unsigned)(order * order); x++)
    {
        VALUE element = rb_ary_entry(ary, (long)x);
        if (rm_check_num2dbl(element))
        {
            kernel[x] = NUM2DBL(element);
        }
        else
        {
            xfree((void *)kernel);
            rb_raise(rb_eTypeError, "type mismatch: %s given", rb_class2name(CLASS_OF(element)));
        }
    }
#endif

    exception = AcquireExceptionInfo();

#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(ConvolveImage) args = { image, kernel, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ConvolveImage), &args);
    CHANGE_RESULT_CHANNEL_MASK(new_image);
    END_CHANNEL_MASK(image);
    DestroyKernelInfo(kernel);
#else
    GVL_STRUCT_TYPE(ConvolveImageChannel) args = { image, channels, order, kernel, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ConvolveImageChannel), &args);
    xfree((void *)kernel);
#endif

    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    RB_GC_GUARD(ary);

    return rm_image_new(new_image);
}



/**
 * Alias for {Magick::Image#dup}.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_copy(VALUE self)
{
    return rb_funcall(self, rm_ID_dup, 0);
}

/**
 * Initialize copy, clone, dup.
 *
 * @param orig [Magick::Image] the source image
 * @return [Magick::Image] self
 * @see Image#copy
 * @see Image#clone
 * @see Image#dup
 */
VALUE
Image_init_copy(VALUE copy, VALUE orig)
{
    Image *image, *new_image;

    image = rm_check_destroyed(orig);
    new_image = rm_clone_image(image);
    UPDATE_DATA_PTR(copy, new_image);

    return copy;
}


/**
 * Extract a region of the image defined by width, height, x, y.
 *
 * @overload crop(x, y, width, height, reset = false)
 *   @param x [Numeric] x position of start of region
 *   @param y [Numeric] y position of start of region
 *   @param width [Numeric] width of region
 *   @param height [Numeric] height of region
 *   @param reset [Boolean] true if reset the cropped image page canvas and position
 *
 * @overload crop(gravity, width, height, reset = false)
 *   @param gravity [Magick::GravityType] the gravity type
 *   @param width [Numeric] width of region
 *   @param height [Numeric] height of region
 *   @param reset [Boolean] true if reset the cropped image page canvas and position

 * @overload crop(gravity, x, y, width, height, reset = false)
 *   @param gravity [Magick::GravityType] the gravity type
 *   @param x [Numeric] x position of start of region
 *   @param y [Numeric] y position of start of region
 *   @param width [Numeric] width of region
 *   @param height [Numeric] height of region
 *   @param reset [Boolean] true if reset the cropped image page canvas and position
 *
 * @return [Magick::Image] a new image
 * @see Image#crop!
 */
VALUE
Image_crop(int argc, VALUE *argv, VALUE self)
{
    rm_check_destroyed(self);
    return cropper(False, argc, argv, self);
}


/**
 * Extract a region of the image defined by width, height, x, y.
 * In-place form of {Image#crop}.
 *
 * @overload crop!(x, y, width, height, reset = false)
 *   @param x [Numeric] x position of start of region
 *   @param y [Numeric] y position of start of region
 *   @param width [Numeric] width of region
 *   @param height [Numeric] height of region
 *   @param reset [Boolean] true if reset the cropped image page canvas and position
 *
 * @overload crop!(gravity, width, height, reset = false)
 *   @param gravity [Magick::GravityType] the gravity type
 *   @param width [Numeric] width of region
 *   @param height [Numeric] height of region
 *   @param reset [Boolean] true if reset the cropped image page canvas and position

 * @overload crop!(gravity, x, y, width, height, reset = false)
 *   @param gravity [Magick::GravityType] the gravity type
 *   @param x [Numeric] x position of start of region
 *   @param y [Numeric] y position of start of region
 *   @param width [Numeric] width of region
 *   @param height [Numeric] height of region
 *   @param reset [Boolean] true if reset the cropped image page canvas and position
 *
 * @return [Magick::Image] a new image
 * @see Image#crop!
 */
VALUE
Image_crop_bang(int argc, VALUE *argv, VALUE self)
{
    rm_check_frozen(self);
    return cropper(True, argc, argv, self);
}


/**
 * Displaces the colormap by a given number of positions.
 * If you cycle the colormap a number of times you can produce a psychedelic effect.
 *
 * The returned image is always a PseudoClass image, regardless of the type of the original image.
 *
 * @param amount [Numeric] amount to cycle the colormap
 * @return [Magick::Image] a new image
 */
VALUE
Image_cycle_colormap(VALUE self, VALUE amount)
{
    Image *image, *new_image;
    int amt;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    amt = NUM2INT(amount);

    image = rm_check_destroyed(self);
    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(CycleColormapImage) args = { new_image, amt, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CycleColormapImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(CycleColormapImage) args = { new_image, amt };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CycleColormapImage), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Get the vertical and horizontal resolution in pixels of the image.
 * The default is "72x72".
 *
 * @return [String] a string of geometry in the form "XresxYres"
 * @see https://www.imagemagick.org/Magick++/Geometry.html
 */
VALUE
Image_density(VALUE self)
{
    Image *image;
    char density[128];

    image = rm_check_destroyed(self);

#if defined(IMAGEMAGICK_7)
    snprintf(density, sizeof(density), "%gx%g", image->resolution.x, image->resolution.y);
#else
    snprintf(density, sizeof(density), "%gx%g", image->x_resolution, image->y_resolution);
#endif
    return rb_str_new2(density);
}


/**
 * Set the vertical and horizontal resolution in pixels of the image.
 *
 * - The density is a string of the form "XresxYres" or simply "Xres".
 * - If the y resolution is not specified, set it equal to the x resolution.
 * - This is equivalent to PerlMagick's handling of density.
 * - The density can also be a Geometry object. The width attribute is used for the x
 *   resolution. The height attribute is used for the y resolution.  If the height attribute is
 *   missing, the width attribute is used for both.
 *
 * @param density_arg [Magick::Geometry, String] The density String or Geometry
 * @return [Magick::Geometry, String] the given value
 * @see https://www.imagemagick.org/Magick++/Geometry.html
 */
VALUE
Image_density_eq(VALUE self, VALUE density_arg)
{
    Image *image;
    char *density;
    VALUE x_val, y_val;
    int count;
    double x_res, y_res;

    image = rm_check_frozen(self);

    // Get the Class ID for the Geometry class.
    if (!Class_Geometry)
    {
        Class_Geometry = rb_const_get(Module_Magick, rm_ID_Geometry);
    }

    // Geometry object. Width and height attributes are always positive.
    if (CLASS_OF(density_arg) == Class_Geometry)
    {
        x_val = rb_funcall(density_arg, rm_ID_width, 0);
        x_res = NUM2DBL(x_val);
        y_val = rb_funcall(density_arg, rm_ID_height, 0);
        y_res = NUM2DBL(y_val);
        if (x_res == 0.0)
        {
            rb_raise(rb_eArgError, "invalid x resolution: %f", x_res);
        }
#if defined(IMAGEMAGICK_7)
        image->resolution.y = y_res != 0.0 ? y_res : x_res;
        image->resolution.x = x_res;
#else
        image->y_resolution = y_res != 0.0 ? y_res : x_res;
        image->x_resolution = x_res;
#endif
    }

    // Convert the argument to a string
    else
    {
        density = StringValueCStr(density_arg);
        if (!IsGeometry(density))
        {
            rb_raise(rb_eArgError, "invalid density geometry %s", density);
        }

#if defined(IMAGEMAGICK_7)
        count = sscanf(density, "%lfx%lf", &image->resolution.x, &image->resolution.y);
#else
        count = sscanf(density, "%lfx%lf", &image->x_resolution, &image->y_resolution);
#endif
        if (count < 2)
        {
#if defined(IMAGEMAGICK_7)
            image->resolution.y = image->resolution.x;
#else
            image->y_resolution = image->x_resolution;
#endif
        }

    }

    RB_GC_GUARD(x_val);
    RB_GC_GUARD(y_val);

    return density_arg;
}


/**
 * Decipher an enciphered image.
 *
 * @param passphrase [String] The passphrase used to encipher the image.
 * @return [Magick::Image] a new deciphered image
 */
VALUE
Image_decipher(VALUE self, VALUE passphrase)
{
    Image *image, *new_image;
    char *pf;
    ExceptionInfo *exception;
    MagickBooleanType okay;

    image = rm_check_destroyed(self);
    pf = StringValueCStr(passphrase);      // ensure passphrase is a string
    exception = AcquireExceptionInfo();

    new_image = rm_clone_image(image);

    GVL_STRUCT_TYPE(DecipherImage) args = { new_image, pf, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(DecipherImage), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    rm_check_exception(exception, new_image, DestroyOnError);
    if (!okay)
    {
        DestroyImage(new_image);
        rb_raise(rb_eRuntimeError, "DecipherImage failed for unknown reason.");
    }

    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Associates makes a copy of the given string arguments and
 * inserts it into the artifact tree.
 *
 * - Normally a script should never call this method. Any calls to
 *   SetImageArtifact will be part of the methods in which they're needed, or
 *   be called via the OptionalMethodArguments class.
 * - If value is nil, the artifact will be removed
 *
 * @param artifact [String] the artifact to set
 * @param value [String, nil] the value to which to set the artifact
 * @return [String, nil] the given `value`
 */
VALUE
Image_define(VALUE self, VALUE artifact, VALUE value)
{
    Image *image;
    char *key, *val;
    MagickBooleanType status;

    image = rm_check_frozen(self);
    artifact = rb_String(artifact);
    key = StringValueCStr(artifact);

    if (value == Qnil)
    {
        DeleteImageArtifact(image, key);
    }
    else
    {
        value = rb_String(value);
        val = StringValueCStr(value);
        status = SetImageArtifact(image, key, val);
        if (!status)
        {
            rb_raise(rb_eNoMemError, "not enough memory to continue");
        }
    }

    return value;
}


/**
 * Get the Number of ticks which must expire before displaying the next image in an animated
 * sequence. The default number of ticks is 0. By default there are 100 ticks per second but this
 * number can be changed via the ticks_per_second attribute.
 *
 * @return [Integer] The current delay value.
 */
VALUE
Image_delay(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, delay, ulong, &rm_image_data_type);
}

/**
 * Set the Number of ticks which must expire before displaying the next image in an animated
 * sequence.
 *
 * @param val [Numeric] the delay value
 * @return [Numeric] the given value
 */
VALUE
Image_delay_eq(VALUE self, VALUE val)
{
    IMPLEMENT_TYPED_ATTR_WRITER(Image, delay, ulong, &rm_image_data_type);
}


/**
 * Delete the image composite mask.
 *
 * @return [Magick::Image] self
 * @see Image#add_compose_mask
 */
VALUE
Image_delete_compose_mask(VALUE self)
{
    Image *image;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_frozen(self);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(SetImageMask) args = { image, CompositePixelMask, NULL, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageMask), &args);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(SetImageMask) args = { image, NULL };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageMask), &args);
    rm_check_image_exception(image, RetainOnError);
#endif

    return self;
}


/**
 * Deletes the specified profile.
 *
 * @param name [String] The profile name, "IPTC" or "ICC" for example.
 *   Specify "*" to delete all the profiles in the image.
 * @return [Magick::Image] self
 * @see Image#add_profile
 */
VALUE
Image_delete_profile(VALUE self, VALUE name)
{
    Image *image = rm_check_frozen(self);

#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(ProfileImage) args = { image, StringValueCStr(name), NULL, 0, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ProfileImage), &args);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(ProfileImage) args = { image, StringValueCStr(name), NULL, 0, MagickTrue };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ProfileImage), &args);
#endif
    return self;
}


/**
 * Return the image depth (8, 16 or 32).
 *
 * - If all pixels have lower-order bytes equal to higher-order bytes, the depth will be reported as
 *   8 even if the depth field in the Image structure says 16.
 *
 * @return [Integer] the depth
 */
VALUE
Image_depth(VALUE self)
{
    Image *image;
    size_t depth = 0;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(GetImageDepth) args = { image, exception };
    depth = (size_t)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetImageDepth), &args);
    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    return INT2FIX(depth);
}


/**
 * Straightens an image. A threshold of 40% works for most images.
 *
 * @overload deskew(threshold = 0.40, auto_crop_width = nil)
 *   @param threshold [Numeric, String] A percentage of QuantumRange. Either a Float between 0 and 1.0,
 *     inclusive, or a string in the form "NN%" where NN is between 0 and 100.
 *   @param auto_crop_width [Numeric] Specify a value for this argument to cause the deskewed image to
 *     be auto-cropped. The argument is the pixel width of the image background (e.g. 40).
 *   @return [Magick::Image] a new image
 */
VALUE
Image_deskew(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double threshold = 40.0 * QuantumRange / 100.0;
    unsigned long width;
    char auto_crop_width[20];
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 2:
            width = NUM2ULONG(argv[1]);
            memset(auto_crop_width, 0, sizeof(auto_crop_width));
            snprintf(auto_crop_width, sizeof(auto_crop_width), "%lu", width);
            SetImageArtifact(image, "deskew:auto-crop", auto_crop_width);
        case 1:
            threshold = rm_percentage(argv[0], 1.0) * QuantumRange;
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 2)", argc);
            break;
    }

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(DeskewImage) args = { image, threshold, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(DeskewImage), &args);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Reduce the speckle noise in an image while preserving the edges of the original image.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_despeckle(VALUE self)
{
    Image *image, *new_image;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(DespeckleImage) args = { image, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(DespeckleImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Free all the memory associated with an image.
 *
 * @return [Magick::Image] self
 */
VALUE
Image_destroy_bang(VALUE self)
{
    Image *image;

    rb_check_frozen(self);
    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);
    rm_image_destroy(image);
    DATA_PTR(self) = NULL;
    return self;
}


/**
 * Return true if the image has been destroyed, false otherwise.
 *
 * @return [Boolean] true if destroyed, false otherwise
 */
VALUE
Image_destroyed_q(VALUE self)
{
    Image *image;

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);
    return image ? Qfalse : Qtrue;
}


/**
 * Compares two images and computes statistics about their difference.
 *
 * @param other [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an imagelist,
 *   uses the current image.
 * @return [Array<Float>] An array of three {Float} values:
 *   - mean error per pixel
 *     - The mean error for any single pixel in the image.
 *   - normalized mean error
 *     - The normalized mean quantization error for any single pixel in the image. This distance measure
 *       is normalized to a range between 0 and 1. It is independent of the range of red, green, and
 *       blue values in the image.
 *   - normalized maximum error
 *     - The normalized maximum quantization error for any single pixel in the image. This distance
 *       measure is normalized to a range between 0 and 1. It is independent of the range of red,
 *       green, and blue values in your image.
 */
VALUE
Image_difference(VALUE self, VALUE other)
{
    Image *image;
    Image *image2;
    VALUE mean, nmean, nmax;
#if defined(IMAGEMAGICK_7)
    double distortion;
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    other = rm_cur_image(other);
    image2 = rm_check_destroyed(other);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(GetImageDistortion) args = { image, image2, MeanErrorPerPixelErrorMetric, &distortion, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetImageDistortion), &args);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(IsImagesEqual) args = { image, image2 };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(IsImagesEqual), &args);
    rm_check_image_exception(image, RetainOnError);
#endif

    mean  = rb_float_new(image->error.mean_error_per_pixel);
    nmean = rb_float_new(image->error.normalized_mean_error);
    nmax  = rb_float_new(image->error.normalized_maximum_error);

    RB_GC_GUARD(mean);
    RB_GC_GUARD(nmean);
    RB_GC_GUARD(nmax);

    return rb_ary_new3(3, mean, nmean, nmax);
}


/**
 * Get image directory.
 *
 * @return [String, nil] the directory
 */
VALUE
Image_directory(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, directory, str, &rm_image_data_type);
}


/**
 * Uses displacement_map to move color from img to the output image.
 * This method corresponds to the -displace option of ImageMagick's composite command.
 *
 * @overload displace(displacement_map, x_amp, y_amp = x_amp, gravity = Magick::NorthWestGravity, x_offset = 0, y_offset = 0)
 *   @param displacement_map [Magick::Image, Magick::ImageList] The source image for the composite
 *     operation. Either an imagelist or an image. If an imagelist, uses the current image.
 *   @param x_amp [Numeric] The maximum displacement on the x-axis.
 *   @param y_amp [Numeric] The maximum displacement on the y-axis.
 *   @param gravity [Magick::GravityType] the gravity for offset. the offsets are measured from the
 *   NorthWest corner by default.
 *   @param x_offset [Numeric] The offset that measured from the left-hand side of the target image.
 *   @param y_offset [Numeric] The offset that measured from the top of the target image.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_displace(int argc, VALUE *argv, VALUE self)
{
    Image *image, *displacement_map;
    VALUE dmap;
    double x_amplitude = 0.0, y_amplitude = 0.0;
    long x_offset = 0L, y_offset = 0L;

    image = rm_check_destroyed(self);

    if (argc < 2)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 to 6)", argc);
    }

    dmap = rm_cur_image(argv[0]);
    displacement_map = rm_check_destroyed(dmap);

    if (argc > 3)
    {
        get_composite_offsets(argc-3, &argv[3], image, displacement_map, &x_offset, &y_offset);
        // There must be 3 arguments left
        argc = 3;
    }

    switch (argc)
    {
        case 3:
            y_amplitude = NUM2DBL(argv[2]);
            x_amplitude = NUM2DBL(argv[1]);
            break;
        case 2:
            x_amplitude = NUM2DBL(argv[1]);
            y_amplitude = x_amplitude;
            break;
    }

    RB_GC_GUARD(dmap);

    return special_composite(image, displacement_map, x_amplitude, y_amplitude,
                             x_offset, y_offset, DisplaceCompositeOp);
}


/**
 * Extract pixel data from the image and returns it as an array of pixels. The "x", "y", "width" and
 * "height" parameters specify the rectangle to be extracted. The "map" parameter reflects the
 * expected ordering of the pixel array. It can be any combination or order of R = red, G = green,
 * B = blue, A = alpha, C = cyan, Y = yellow, M = magenta, K = black, or I = intensity (for
 * grayscale). If the "float" parameter is specified and true, the pixel data is returned as
 * floating-point numbers in the range [0..1]. By default the pixel data is returned as integers in
 * the range [0..QuantumRange].
 *
 * @overload dispatch(x, y, columns, rows, map, float = false)
 *   @param x [Numeric] The offset of the rectangle from the upper-left corner of the image.
 *   @param y [Numeric] The offset of the rectangle from the upper-left corner of the image.
 *   @param columns [Numeric] The width of the rectangle.
 *   @param rows [Numeric] The height of the rectangle.
 *   @param map [String]
 *   @param float [Boolean]
 *   @return [Array<Numeric>] an Array of pixel data
 */
VALUE
Image_dispatch(int argc, VALUE *argv, VALUE self)
{
    Image *image;
    long x, y;
    unsigned long columns, rows, n, npixels;
    VALUE pixels_ary;
    StorageType stg_type = QuantumPixel;
    char *map;
    size_t mapL;
    MagickBooleanType okay;
    ExceptionInfo *exception;
    volatile union
    {
        Quantum *i;
        double *f;
        void *v;
    } pixels;

    rm_check_destroyed(self);

    if (argc < 5 || argc > 6)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 5 or 6)", argc);
    }

    x       = NUM2LONG(argv[0]);
    y       = NUM2LONG(argv[1]);
    columns = NUM2ULONG(argv[2]);
    rows    = NUM2ULONG(argv[3]);
    map     = rm_str2cstr(argv[4], &mapL);
    if (argc == 6)
    {
        stg_type = RTEST(argv[5]) ? DoublePixel : QuantumPixel;
    }

    // Compute the size of the pixel array and allocate the memory.
    npixels = columns * rows * mapL;
    pixels.v = stg_type == QuantumPixel ? (void *) ALLOC_N(Quantum, npixels)
               : (void *) ALLOC_N(double, npixels);

    // Create the Ruby array for the pixels. Return this even if ExportImagePixels fails.
    pixels_ary = rb_ary_new();

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(ExportImagePixels) args = { image, x, y, columns, rows, map, stg_type, (void *)pixels.v, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ExportImagePixels), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));

    if (!okay)
    {
        goto exit;
    }

    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    // Convert the pixel data to the appropriate Ruby type
    if (stg_type == QuantumPixel)
    {
        for (n = 0; n < npixels; n++)
        {
            rb_ary_push(pixels_ary, QUANTUM2NUM(pixels.i[n]));
        }
    }
    else
    {
        for (n = 0; n < npixels; n++)
        {
            rb_ary_push(pixels_ary, rb_float_new(pixels.f[n]));
        }
    }

    exit:
    xfree((void *)pixels.v);

    RB_GC_GUARD(pixels_ary);

    return pixels_ary;
}


/**
 * Display the image to an X window screen.
 *
 * @yield [info]
 * @yieldparam info [Magick::Image::Info]
 * @return [Magick::Image] self
 */
VALUE
Image_display(VALUE self)
{
    Image *image;
    Info *info;
    VALUE info_obj;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

    if (image->rows == 0 || image->columns == 0)
    {
        rb_raise(rb_eArgError, "invalid image geometry (%" RMIuSIZE "x%" RMIuSIZE ")", image->rows, image->columns);
    }

    info_obj = rm_info_new();
    TypedData_Get_Struct(info_obj, Info, &rm_info_data_type, info);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    DisplayImages(info, image, exception);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    DisplayImages(info, image);
    rm_check_image_exception(image, RetainOnError);
#endif

    RB_GC_GUARD(info_obj);

    return self;
}


/**
 * Return the dispose attribute as a DisposeType enum.
 *
 * @return [Magick::DisposeType] the dispose
 */
VALUE
Image_dispose(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return DisposeType_find(image->dispose);
}


/**
 * Set the dispose attribute.
 *
 * @param dispose [Magick::DisposeType] the dispose
 * @return [Magick::DisposeType] the given dispose
 */
VALUE
Image_dispose_eq(VALUE self, VALUE dispose)
{
    Image *image = rm_check_frozen(self);
    VALUE_TO_ENUM(dispose, image->dispose, DisposeType);
    return dispose;
}


/**
 * Composites the overlay image into the target image.
 * The opacity of img is multiplied by dst_percentage and opacity of overlay is multiplied by
 * src_percentage.
 *
 * This method corresponds to the -dissolve option of ImageMagick's composite command.
 *
 * @overload dissolve(overlay, src_percent, dst_percent = -1.0, gravity = Magick::NorthWestGravity, x_offset = 0, y_offset = 0)
 *   @param overlay [Magick::Image, Magick::ImageList] The source image for the composite operation.
 *     Either an imagelist or an image. If an imagelist, uses the current image.
 *   @param src_percent [Numeric, String] Either a non-negative number a string in the form "NN%".
 *     If src_percentage is a number it is interpreted as a percentage.
 *     Both 0.25 and "25%" mean 25%. This argument is required.
 *   @param dst_percent [Numeric, String] Either a non-negative number a string in the form "NN%".
 *     If src_percentage is a number it is interpreted as a percentage.
 *     Both 0.25 and "25%" mean 25%. This argument may omitted if no other arguments follow it.
 *     In this case the default is 100%-src_percentage.
 *   @param gravity [Magick::GravityType] the gravity for offset. the offsets are measured from the
 *     NorthWest corner by default.
 *   @param x_offset [Numeric] The offset that measured from the left-hand side of the target image.
 *   @param y_offset [Numeric] The offset that measured from the top of the target image.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_dissolve(int argc, VALUE *argv, VALUE self)
{
    Image *image, *overlay;
    double src_percent, dst_percent = -1.0;
    long x_offset = 0L, y_offset = 0L;
    VALUE composite_image, ovly;

    image = rm_check_destroyed(self);

    if (argc < 1)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 to 6)", argc);
    }

    ovly = rm_cur_image(argv[0]);
    overlay = rm_check_destroyed(ovly);

    if (argc > 3)
    {
        get_composite_offsets(argc-3, &argv[3], image, overlay, &x_offset, &y_offset);
        // There must be 3 arguments left
        argc = 3;
    }

    switch (argc)
    {
        case 3:
            dst_percent = rm_percentage(argv[2], 1.0) * 100.0;
        case 2:
            src_percent = rm_percentage(argv[1], 1.0) * 100.0;
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 to 6)", argc);
            break;
    }

    composite_image =  special_composite(image, overlay, src_percent, dst_percent,
                                         x_offset, y_offset, DissolveCompositeOp);

    RB_GC_GUARD(composite_image);
    RB_GC_GUARD(ovly);

    return composite_image;
}


/**
 * Distort an image using the specified distortion type and its required arguments.
 * This method is equivalent to ImageMagick's -distort option.
 *
 * @overload distort(type, points, bestfit = false)
 *   @param type [Magick::DistortMethod] a DistortMethod value
 *   @param points [Array<Numeric>] an Array of Numeric values. The size of the array depends on the
 *     distortion type.
 *   @param bestfit [Boolean] If bestfit is enabled, and the distortion allows it, the destination
 *     image is adjusted to ensure the whole source image will just fit within the final destination
 *     image, which will be sized and offset accordingly.  Also in many cases the virtual offset of
 *     the source image will be taken into account in the mapping.
 *
 * @overload distort(type, points, bestfit = false)
 *   When a block is given, distort yields with a block argument you can optionally use to set attributes.
 *   - options.define("distort:viewport", "WxH+X+Y")
 *     - Specify the size and offset of the generated viewport image of the distorted image space. W and
 *       H are the width and height, and X and Y are the offset.
 *   - options.define("distort:scale", N)
 *     - N is an integer factor. Scale the output image (viewport or otherwise) by that factor without
 *       changing the viewed contents of the distorted image. This can be used either for
 *       'super-sampling' the image for a higher quality result, or for panning and zooming around
 *       the image (with appropriate viewport changes, or post-distort cropping and resizing).
 *   - options.verbose(true)
 *     - Attempt to output the internal coefficients, and the -fx equivalent to the distortion, for
         expert study, and debugging purposes. This many not be available for all distorts.
 *   @param type [Magick::DistortMethod] a DistortMethod value
 *   @param points [Array<Numeric>] an Array of Numeric values. The size of the array depends on the distortion type.
 *   @param bestfit [Boolean] If bestfit is enabled, and the distortion allows it, the destination
 *     image is adjusted to ensure the whole source image will just fit within the final destination
 *     image, which will be sized and offset accordingly.  Also in many cases the virtual offset of
 *     the source image will be taken into account in the mapping.
 *   @yield [opt_args]
 *   @yieldparam opt_args [Magick::OptionalMethodArguments]
 *
 * @return [Magick::Image] a new image
 * @example
 *   img.distort(Magick::ScaleRotateTranslateDistortion, [0]) do |options|
 *     options.define "distort:viewport", "44x44+15+0"
 *     options.define "distort:scale", 2
 *   end
 */
VALUE
Image_distort(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    VALUE pts;
    unsigned long n, npoints;
    DistortMethod distortion_method;
    double *points;
    MagickBooleanType bestfit = MagickFalse;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    rm_get_optional_arguments(self);

    switch (argc)
    {
        case 3:
            bestfit = (MagickBooleanType)RTEST(argv[2]);
        case 2:
            // Ensure pts is an array
            pts = rb_Array(argv[1]);
            VALUE_TO_ENUM(argv[0], distortion_method, DistortMethod);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (expected 2 or 3, got %d)", argc);
            break;
    }

    npoints = RARRAY_LEN(pts);
    points = ALLOC_N(double, npoints);

    for (n = 0; n < npoints; n++)
    {
        VALUE element = rb_ary_entry(pts, n);
        if (rm_check_num2dbl(element))
        {
            points[n] = NUM2DBL(element);
        }
        else
        {
            xfree(points);
            rb_raise(rb_eTypeError, "type mismatch: %s given", rb_class2name(CLASS_OF(element)));
        }
    }

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(DistortImage) args = { image, distortion_method, npoints, points, bestfit, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(DistortImage), &args);
    xfree(points);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    RB_GC_GUARD(pts);

    return rm_image_new(new_image);
}


/**
 * Compares one or more image channels of an image to a reconstructed image and returns the
 * specified distortion metric.
 *
 * @overload distortion_channel(reconstructed_image, metric, channel = Magick::AllChannels)
 *   @param reconstructed_image [Magick::Image, Magick::ImageList] Either an imagelist or an
 *     image. If an imagelist, uses the current image.
 *   @param metric [Magick::MetricType] The desired distortion metric.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload distortion_channel(reconstructed_image, metric, *channels)
 *   @param reconstructed_image [Magick::Image, Magick::ImageList] Either an imagelist or an
 *     image. If an imagelist, uses the current image.
 *   @param metric [Magick::MetricType] The desired distortion metric.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Float] the image channel distortion
 */
VALUE
Image_distortion_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *reconstruct;
    ChannelType channels;
    ExceptionInfo *exception;
    MetricType metric;
    VALUE rec;
    double distortion;
#if defined(IMAGEMAGICK_7)
    Image *difference_image;
#endif

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);
    if (argc > 2)
    {
        raise_ChannelType_error(argv[argc-1]);
    }
    if (argc < 2)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 or more)", argc);
    }

    rec = rm_cur_image(argv[0]);
    reconstruct = rm_check_destroyed(rec);
    VALUE_TO_ENUM(argv[1], metric, MetricType);
    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(CompareImages) args = { image, reconstruct, metric, &distortion, exception };
    difference_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompareImages), &args);
    END_CHANNEL_MASK(image);
    DestroyImage(difference_image);
#else
    GVL_STRUCT_TYPE(GetImageChannelDistortion) args = { image, reconstruct, channels, metric, &distortion, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetImageChannelDistortion), &args);
#endif

    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    RB_GC_GUARD(rec);

    return rb_float_new(distortion);
}


/**
 * Implement marshalling.
 *
 * @param depth [Object] unused
 * @return [String] a string representing the dumped image
 */
VALUE
Image__dump(VALUE self, VALUE depth ATTRIBUTE_UNUSED)
{
    Image *image;
    ImageInfo *info;
    void *blob;
    size_t length;
    DumpedImage mi;
    VALUE str;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    info = CloneImageInfo(NULL);
    if (!info)
    {
        rb_raise(rb_eNoMemError, "not enough memory to continue");
    }
    strlcpy(info->magick, image->magick, sizeof(info->magick));

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(ImageToBlob) args = { info, image, &length, exception };
    blob = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ImageToBlob), &args);

    // Free ImageInfo first - error handling may raise an exception
    DestroyImageInfo(info);

    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    if (!blob)
    {
        rb_raise(rb_eNoMemError, "not enough memory to continue");
    }

    // Create a header for the blob: ID and version
    // numbers, followed by the length of the magick
    // string stored as a byte, followed by the
    // magick string itself.
    mi.id = DUMPED_IMAGE_ID;
    mi.mj = DUMPED_IMAGE_MAJOR_VERS;
    mi.mi = DUMPED_IMAGE_MINOR_VERS;
    strlcpy(mi.magick, image->magick, sizeof(mi.magick));
    mi.len = (unsigned char) min((size_t)UCHAR_MAX, rm_strnlen_s(mi.magick, sizeof(mi.magick)));

    // Concatenate the blob onto the header & return the result
    str = rb_str_new((char *)&mi, (long)(mi.len+offsetof(DumpedImage, magick)));
    str = rb_str_buf_cat(str, (char *)blob, (long)length);
    magick_free((void*)blob);

    RB_GC_GUARD(str);

    return str;
}


/**
 * Duplicates a image.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_dup(VALUE self)
{
    VALUE dup;

    rm_check_destroyed(self);
    dup = TypedData_Wrap_Struct(CLASS_OF(self), &rm_image_data_type, NULL);
    RB_GC_GUARD(dup);

    return rb_funcall(dup, rm_ID_initialize_copy, 1, self);
}


/**
 * Calls block once for each profile in the image, passing the profile name and value as parameters.
 *
 * @yield [name, val]
 * @yieldparam name [String] the profile name
 * @yieldparam val [String] the profile value
 * @return [Object] the last value returned by the block
 */
VALUE
Image_each_profile(VALUE self)
{
    Image *image;
    VALUE ary;
    VALUE val = Qnil;
    char *name;
    const StringInfo *profile;

    image = rm_check_destroyed(self);
    ResetImageProfileIterator(image);

    ary = rb_ary_new2(2);

    name = GetNextImageProfile(image);
    while (name)
    {
        rb_ary_store(ary, 0, rb_str_new2(name));

        profile = GetImageProfile(image, name);
        if (!profile)
        {
            rb_ary_store(ary, 1, Qnil);
        }
        else
        {
            rb_ary_store(ary, 1, rb_str_new((char *)profile->datum, (long)profile->length));
        }
        val = rb_yield(ary);
        name = GetNextImageProfile(image);
    }

    RB_GC_GUARD(ary);
    RB_GC_GUARD(val);

    return val;
}


/**
 * Find edges in an image. "radius" defines the radius of the convolution filter.
 *
 * @overload edge(radius = 0.0)
 *   @param radius [Numeric] The radius of the convolution filter.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_edge(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double radius = 0.0;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 1:
            radius = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 or 1)", argc);
            break;
    }

    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(EdgeImage) args = { image, radius, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(EdgeImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


// aliases for common use of structure types; BlurImage, CharcoalImage, EmbossImage, GaussianBlurImage, SharpenImage
typedef GVL_STRUCT_TYPE(BlurImage) GVL_STRUCT_TYPE(effect_image);

/**
 * Call one of the effects methods.
 *
 * No Ruby usage (internal function)
 *
 * @param self this object
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param effector the effector to call
 * @return a new image
 */
static VALUE
effect_image(VALUE self, int argc, VALUE *argv, gvl_function_t fp)
{
    Image *image, *new_image;
    ExceptionInfo *exception;
    double radius = 0.0, sigma = 1.0;

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 2:
            sigma = NUM2DBL(argv[1]);
        case 1:
            radius = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 2)", argc);
            break;
    }

    if (sigma == 0.0)
    {
        rb_raise(rb_eArgError, "sigma must be != 0.0");
    }

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(effect_image) args = { image, radius, sigma, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(fp, &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Adds a 3-dimensional effect.
 *
 * @overload emboss(radius = 0.0, sigma = 1.0)
 *   @param radius [Numeric] The radius of the Gaussian operator.
 *   @param sigma [Numeric] The sigma (standard deviation) of the Gaussian operator.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_emboss(int argc, VALUE *argv, VALUE self)
{
    return effect_image(self, argc, argv, GVL_FUNC(EmbossImage));
}


/**
 * Encipher an image.
 *
 * @param passphrase [String] the passphrase with which to encipher
 * @return [Magick::Image] a new image
 * @example
 *   enciphered_img = img.encipher("magic word")
 */
VALUE
Image_encipher(VALUE self, VALUE passphrase)
{
    Image *image, *new_image;
    char *pf;
    ExceptionInfo *exception;
    MagickBooleanType okay;

    image = rm_check_destroyed(self);
    pf = StringValueCStr(passphrase);      // ensure passphrase is a string
    exception = AcquireExceptionInfo();

    new_image = rm_clone_image(image);

    GVL_STRUCT_TYPE(EncipherImage) args = { new_image, pf, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(EncipherImage), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    rm_check_exception(exception, new_image, DestroyOnError);
    if (!okay)
    {
        DestroyImage(new_image);
        rb_raise(rb_eRuntimeError, "EncipherImage failed for unknown reason.");
    }

    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}



/**
 * Return endian option for images that support it.
 *
 * @return [Magick::EndianType] the endian option
 */
VALUE
Image_endian(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return EndianType_find(image->endian);
}


/**
 * Set endian option for images that support it.
 *
 * @param type [Magick::EndianType] the endian type
 * @return [Magick::EndianType] the given type
 */
VALUE
Image_endian_eq(VALUE self, VALUE type)
{
    Image *image = rm_check_frozen(self);
    VALUE_TO_ENUM(type, image->endian, EndianType);
    return type;
}

/**
 * Apply a digital filter that improves the quality of a noisy image.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_enhance(VALUE self)
{
    Image *image, *new_image;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(EnhanceImage) args = { image, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(EnhanceImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Apply a histogram equalization to the image.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_equalize(VALUE self)
{
    Image *image, *new_image;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(EqualizeImage) args = { new_image, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(EqualizeImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(EqualizeImage) args = { new_image };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(EqualizeImage), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Applies a histogram equalization to the image. Only the specified channels are equalized.
 *
 * @overload equalize_channel(channel = Magick::AllChannels)
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload equalize_channel(*channels)
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_equalize_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif
    ChannelType channels;

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);
    if (argc > 0)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(new_image, channels);
    GVL_STRUCT_TYPE(EqualizeImage) args = { new_image, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(EqualizeImage), &args);
    END_CHANNEL_MASK(new_image);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(EqualizeImageChannel) args = { new_image, channels };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(EqualizeImageChannel), &args);

    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Reset the image to the background color.
 *
 * @return [Magick::Image] self
 */
VALUE
Image_erase_bang(VALUE self)
{
    Image *image;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_frozen(self);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(SetImageBackgroundColor) args = { image, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageBackgroundColor), &args);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(SetImageBackgroundColor) args = { image };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageBackgroundColor), &args);
    rm_check_image_exception(image, RetainOnError);
#endif

    return self;
}


/**
 * Lightweight crop.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - christy says "does not respect the virtual page offset (-page) and does
 *     not update the page offset and its more efficient than cropping."
 *
 * @param bang whether the bang (!) version of the method was called
 * @param self this object
 * @param x the x position for the start of the rectangle
 * @param y the y position for the start of the rectangle
 * @param width the width of the rectancle
 * @param height the height of the rectangle
 * @return self if bang, otherwise a new image
 * @see Image_excerpt
 * @see Image_excerpt_bang
 * @see Image_crop
 * @see Image_crop_bang
 */
static VALUE
excerpt(int bang, VALUE self, VALUE x, VALUE y, VALUE width, VALUE height)
{
    Image *image, *new_image;
    RectangleInfo rect;
    ExceptionInfo *exception;

    memset(&rect, '\0', sizeof(rect));
    rect.x = NUM2LONG(x);
    rect.y = NUM2LONG(y);
    rect.width = NUM2ULONG(width);
    rect.height = NUM2ULONG(height);

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(ExcerptImage) args = { image, &rect, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ExcerptImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    if (bang)
    {
        rm_ensure_result(new_image);
        UPDATE_DATA_PTR(self, new_image);
        rm_image_destroy(image);
        return self;
    }

    return rm_image_new(new_image);
}


/**
 * This method is very similar to crop.
 * It extracts the rectangle specified by its arguments from the image and returns it as a new
 * image. However, excerpt does not respect the virtual page offset and does not update the page
 * offset and is more efficient than cropping.
 *
 * @param x [Numeric] the x position for the start of the rectangle
 * @param y [Numeric] the y position for the start of the rectangle
 * @param width [Numeric] the width of the rectancle
 * @param height [Numeric] the height of the rectangle
 * @return [Magick::Image] a new image
 * @see Image#excerpt!
 * @see Image#crop
 * @see Image#crop!
 */
VALUE
Image_excerpt(VALUE self, VALUE x, VALUE y, VALUE width, VALUE height)
{
    rm_check_destroyed(self);
    return excerpt(False, self, x, y, width, height);
}


/**
 * In-place form of {Magick::Image#excerpt}.
 *
 * This method is very similar to crop.
 * It extracts the rectangle specified by its arguments from the image and returns it as a new
 * image.  However, excerpt does not respect the virtual page offset and does not update the page
 * offset and is more efficient than cropping.
 *
 * @param x [Numeric] the x position for the start of the rectangle
 * @param y [Numeric] the y position for the start of the rectangle
 * @param width [Numeric] the width of the rectancle
 * @param height [Numeric] the height of the rectangle
 * @return [Magick::Image] self
 * @see Image#excerpt
 * @see Image#crop
 * @see Image#crop!
 */
VALUE
Image_excerpt_bang(VALUE self, VALUE x, VALUE y, VALUE width, VALUE height)
{
    rm_check_frozen(self);
    return excerpt(True, self, x, y, width, height);
}


/**
 * Extracts the pixel data from the specified rectangle and returns it as an array of Integer
 * values. The array returned by {Magick::Image#export_pixels} is suitable for use as an argument
 * to {Magick::Image#import_pixels}.
 *
 * @overload export_pixels(x = 0, y = 0, cols = self.columns, rows = self.rows, map = "RGB")
 *   @param x [Numeric] The offset of the rectangle from the upper-left corner of the image.
 *   @param y [Numeric] The offset of the rectangle from the upper-left corner of the image.
 *   @param cols [Numeric] The width of the rectangle.
 *   @param rows [Numeric] The height of the rectangle.

 *   @param map [String] A string that describes which pixel channel data is desired and the order
 *     in which it should be stored. It can be any combination or order of R = red, G = green, B =
 *     blue, A = alpha, C = cyan, Y = yellow, M = magenta, K = black, I = intensity (for grayscale),
 *     or P = pad.
 *   @return [Array<Numeric>] array of pixels
 */
VALUE
Image_export_pixels(int argc, VALUE *argv, VALUE self)
{
    Image *image;
    long x_off = 0L, y_off = 0L;
    unsigned long cols, rows;
    long n, npixels;
    MagickBooleanType okay;
    const char *map = "RGB";
    Quantum *pixels;
    VALUE ary;
    ExceptionInfo *exception;


    image = rm_check_destroyed(self);
    cols = image->columns;
    rows = image->rows;

    switch (argc)
    {
        case 5:
            map   = StringValueCStr(argv[4]);
        case 4:
            rows  = NUM2ULONG(argv[3]);
        case 3:
            cols  = NUM2ULONG(argv[2]);
        case 2:
            y_off = NUM2LONG(argv[1]);
        case 1:
            x_off = NUM2LONG(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 5)", argc);
            break;
    }

    if (   x_off < 0 || (unsigned long)x_off > image->columns
           || y_off < 0 || (unsigned long)y_off > image->rows
           || cols == 0 || rows == 0)
    {
        rb_raise(rb_eArgError, "invalid extract geometry");
    }


    npixels = (long)(cols * rows * strlen(map));
    pixels = ALLOC_N(Quantum, npixels);
    if (!pixels)    // app recovered from exception
    {
        return rb_ary_new2(0L);
    }

    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(ExportImagePixels) args = { image, x_off, y_off, cols, rows, map, QuantumPixel, (void *)pixels, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ExportImagePixels), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    if (!okay)
    {
        xfree((void *)pixels);
        CHECK_EXCEPTION();

        // Should never get here...
        rm_magick_error("ExportImagePixels failed with no explanation.");
    }

    DestroyExceptionInfo(exception);

    ary = rb_ary_new2(npixels);
    for (n = 0; n < npixels; n++)
    {
        rb_ary_push(ary, QUANTUM2NUM(pixels[n]));
    }

    xfree((void *)pixels);

    RB_GC_GUARD(ary);

    return ary;
}


/**
 * If width or height is greater than the target image's width or height, extends the width and
 * height of the target image to the specified values.  The new pixels are set to the background
 * color. If width or height is less than the target image's width or height, crops the target
 * image.
 *
 * @overload extent(width, height, x = 0, y = 0)
 *   @param width [Numeric] The width of the new image
 *   @param height [Numeric] The height of the new image
 *   @param x [Numeric] The upper-left corner of the new image is positioned
 *   @param y [Numeric] The upper-left corner of the new image is positioned
 *   @return [Magick::Image] a new image
 */
VALUE
Image_extent(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    RectangleInfo geometry;
    long height, width;
    ExceptionInfo *exception;

    rm_check_destroyed(self);

    if (argc < 2 || argc > 4)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (expected 2 to 4, got %d)", argc);
    }

    geometry.y = geometry.x = 0L;
    switch (argc)
    {
        case 4:
            geometry.y = NUM2LONG(argv[3]);
        case 3:
            geometry.x = NUM2LONG(argv[2]);
        default:
            geometry.height = height = NUM2LONG(argv[1]);
            geometry.width = width = NUM2LONG(argv[0]);
            break;
    }

    // Use the signed versions of these two values to test for < 0
    if (height <= 0L || width <= 0L)
    {
        if (geometry.x == 0 && geometry.y == 0)
        {
            rb_raise(rb_eArgError, "invalid extent geometry %ldx%ld", width, height);
        }
        else
        {
            rb_raise(rb_eArgError, "invalid extent geometry %ldx%ld+%" RMIdSIZE "+%" RMIdSIZE "",
                     width, height, geometry.x, geometry.y);
        }
    }


    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);
    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(ExtentImage) args = { image, &geometry, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ExtentImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Extracts the pixel data from the specified rectangle and returns it as a string.
 *
 * @overload export_pixels_to_str(x = 0, y = 0, cols = self.columns, rows = self.rows, map = "RGB", type = Magick::CharPixel)
 *   @param x [Numeric] The offset of the rectangle from the upper-left corner of the image.
 *   @param y [Numeric] The offset of the rectangle from the upper-left corner of the image.
 *   @param cols [Numeric] The width of the rectangle.
 *   @param rows [Numeric] The height of the rectangle.
 *   @param map [String] A string that describes which pixel channel data is desired and the order
 *     in which it should be stored. It can be any combination or order of R = red, G = green, B =
 *     blue, A = alpha, C = cyan, Y = yellow, M = magenta, K = black, I = intensity (for grayscale),
 *     or P = pad.
 *   @param type [Magick::StorageType] A StorageType value that specifies the C datatype to which
 *     the pixel data will be converted.
 *   @return [String] the pixel data
 */
VALUE
Image_export_pixels_to_str(int argc, VALUE *argv, VALUE self)
{
    Image *image;
    long x_off = 0L, y_off = 0L;
    unsigned long cols, rows;
    unsigned long npixels;
    size_t sz;
    MagickBooleanType okay;
    const char *map = "RGB";
    StorageType type = CharPixel;
    VALUE string;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    cols = image->columns;
    rows = image->rows;

    switch (argc)
    {
        case 6:
            VALUE_TO_ENUM(argv[5], type, StorageType);
        case 5:
            map   = StringValueCStr(argv[4]);
        case 4:
            rows  = NUM2ULONG(argv[3]);
        case 3:
            cols  = NUM2ULONG(argv[2]);
        case 2:
            y_off = NUM2LONG(argv[1]);
        case 1:
            x_off = NUM2LONG(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 6)", argc);
            break;
    }

    if (   x_off < 0 || (unsigned long)x_off > image->columns
           || y_off < 0 || (unsigned long)y_off > image->rows
           || cols == 0 || rows == 0)
    {
        rb_raise(rb_eArgError, "invalid extract geometry");
    }


    npixels = cols * rows * strlen(map);
    switch (type)
    {
        case CharPixel:
            sz = sizeof(unsigned char);
            break;
        case ShortPixel:
            sz = sizeof(unsigned short);
            break;
        case DoublePixel:
            sz = sizeof(double);
            break;
        case FloatPixel:
            sz = sizeof(float);
            break;
        case LongPixel:
            sz = sizeof(unsigned long);
            break;
        case QuantumPixel:
            sz = sizeof(Quantum);
            break;
        case UndefinedPixel:
        default:
            rb_raise(rb_eArgError, "undefined storage type");
            break;
    }

    // Allocate a string long enough to hold the exported pixel data.
    // Get a pointer to the buffer.
    string = rb_str_new2("");
    rb_str_resize(string, (long)(sz * npixels));

    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(ExportImagePixels) args = { image, x_off, y_off, cols, rows, map, type, (void *)RSTRING_PTR(string), exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ExportImagePixels), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    if (!okay)
    {
        // Let GC have the string buffer.
        rb_str_resize(string, 0);
        CHECK_EXCEPTION();

        // Should never get here...
        rm_magick_error("ExportImagePixels failed with no explanation.");
    }

    DestroyExceptionInfo(exception);

    RB_GC_GUARD(string);

    return string;
}


/**
 * The extract_info attribute reader.
 *
 * @return [Magick::Rectangle] the Rectangle object
 */
VALUE
Image_extract_info(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return Import_RectangleInfo(&image->extract_info);
}


/**
 * Set the extract_info attribute.
 *
 * @param rect [Magick::Rectangle] the Rectangle object
 * @return [Magick::Rectangle] the given value
 */
VALUE
Image_extract_info_eq(VALUE self, VALUE rect)
{
    Image *image = rm_check_frozen(self);
    Export_RectangleInfo(&image->extract_info, rect);
    return rect;
}


/**
 * Get image filename.
 *
 * @return [String] the filename
 */
VALUE
Image_filename(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, filename, str, &rm_image_data_type);
}


/**
 * Return the image file size.
 *
 * @return [Integer] the file size
 */
VALUE Image_filesize(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return INT2FIX(GetBlobSize(image));
}


/**
 * Get filter type.
 *
 * @return [Magick::FilterType] the filter
 */
VALUE
Image_filter(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return FilterType_find(image->filter);
}


/**
 * Set filter type.
 *
 * @param filter [Magick::FilterType] the filter
 * @return [Magick::FilterType] the given filter
 */
VALUE
Image_filter_eq(VALUE self, VALUE filter)
{
    Image *image = rm_check_frozen(self);
    VALUE_TO_ENUM(filter, image->filter, FilterType);
    return filter;
}


/**
 * This interesting method searches for a rectangle in the image that is similar to the target.
 * For the rectangle to be similar each pixel in the rectangle must match the corresponding pixel in
 * the target image within the range specified by the fuzz attributes of the image and the target
 * image.
 *
 * @overload find_similar_region(target, x = 0, y = 0)
 *   @param target [Magick::Image, Magick::ImageList] An image that forms the target of the
 *     search. This image can be any size. Either an imagelist or an image. If an imagelist, uses
 *     the current image.
 *   @param x [Numeric] The starting x-offsets for the search.
 *   @param y [Numeric] The starting y-offsets for the search.
 *   @return [Array<Numeric>, nil] If the search succeeds, the return value is an array with 2 elements.
 *     These elements are the x- and y-offsets of the matching rectangle.
 *     If the search fails the return value is nil.
 */
VALUE
Image_find_similar_region(int argc, VALUE *argv, VALUE self)
{
    Image *image, *target;
    VALUE region, targ;
    ssize_t x = 0L, y = 0L;
    ExceptionInfo *exception;
    MagickBooleanType okay;

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 3:
            y = NUM2LONG(argv[2]);
        case 2:
            x = NUM2LONG(argv[1]);
        case 1:
            targ = rm_cur_image(argv[0]);
            target = rm_check_destroyed(targ);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 to 3)", argc);
            break;
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(IsEquivalentImage) args = { image, target, &x, &y, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(IsEquivalentImage), &args);
#else
    GVL_STRUCT_TYPE(IsImageSimilar) args = { image, target, &x, &y, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(IsImageSimilar), &args);
#endif
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);

    if (!okay)
    {
        return Qnil;
    }

    region = rb_ary_new2(2);
    rb_ary_store(region, 0L, LONG2NUM(x));
    rb_ary_store(region, 1L, LONG2NUM(y));

    RB_GC_GUARD(region);
    RB_GC_GUARD(targ);

    return region;
}


// aliases for common use of structure types; FlopImage, FlipImage
typedef GVL_STRUCT_TYPE(FlipImage) GVL_STRUCT_TYPE(flipflop);

/**
 * Call a flipflopper (a function that either flips or flops the image).
 *
 * No Ruby usage (internal function)
 *
 * @param bang whether the bang (!) version of the method was called
 * @param self this object
 * @param flipflopper the flip/flop method to call
 * @return self if bang, otherwise a new image
 * @see Image_flip
 * @see Image_flip_bang
 * @see Image_flop
 * @see Image_flop_bang
 */
static VALUE
flipflop(int bang, VALUE self, gvl_function_t fp)
{
    Image *image, *new_image;
    ExceptionInfo *exception;

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);
    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(flipflop) args = { image, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(fp, &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    if (bang)
    {
        rm_ensure_result(new_image);
        UPDATE_DATA_PTR(self, new_image);
        rm_image_destroy(image);
        return self;
    }

    return rm_image_new(new_image);
}


/**
 * Create a vertical mirror image by reflecting the pixels around the central x-axis.
 *
 * @return [Magick::Image] a new image
 * @see Image#flip!
 * @see Image#flop
 * @see Image#flop!
 */
VALUE
Image_flip(VALUE self)
{
    rm_check_destroyed(self);
    return flipflop(False, self, GVL_FUNC(FlipImage));
}


/**
 * Create a vertical mirror image by reflecting the pixels around the central x-axis.
 * In-place form of {Image#flip}.
 *
 * @return [Magick::Image] self
 * @see Image#flip
 * @see Image#flop
 * @see Image#flop!
 */
VALUE
Image_flip_bang(VALUE self)
{
    rm_check_frozen(self);
    return flipflop(True, self, GVL_FUNC(FlipImage));
}


/**
 * Create a horizonal mirror image by reflecting the pixels around the central y-axis.
 *
 * @return [Magick::Image] a new image
 * @see Image#flop!
 * @see Image#flip
 * @see Image#flip!
 */
VALUE
Image_flop(VALUE self)
{
    rm_check_destroyed(self);
    return flipflop(False, self, GVL_FUNC(FlopImage));
}


/**
 * Create a horizonal mirror image by reflecting the pixels around the central y-axis.
 * In-place form of {Image#flop}.
 *
 * @return [Magick::Image] self
 * @see Image#flop
 * @see Image#flip
 * @see Image#flip!
 */
VALUE
Image_flop_bang(VALUE self)
{
    rm_check_frozen(self);
    return flipflop(True, self, GVL_FUNC(FlopImage));
}


/**
 * Return the image encoding format. For example, "GIF" or "PNG".
 *
 * @return [String, nil] the encoding format
 */
VALUE
Image_format(VALUE self)
{
    Image *image;
    const MagickInfo *magick_info;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    if (*image->magick)
    {
        // Deliberately ignore the exception info!
        exception = AcquireExceptionInfo();
        magick_info = GetMagickInfo(image->magick, exception);
        DestroyExceptionInfo(exception);
        return magick_info ? rb_str_new2(magick_info->name) : Qnil;
    }

    return Qnil;
}


/**
 * Set the image encoding format. For example, "GIF" or "PNG".
 *
 * @param magick [String] the encoding format
 * @return [String] the given value
 */
VALUE
Image_format_eq(VALUE self, VALUE magick)
{
    Image *image;
    const MagickInfo *m;
    char *mgk;
    ExceptionInfo *exception;

    image = rm_check_frozen(self);

    mgk = StringValueCStr(magick);

    exception = AcquireExceptionInfo();
    m = GetMagickInfo(mgk, exception);
    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    if (!m)
    {
        rb_raise(rb_eArgError, "unknown format: %s", mgk);
    }


    strlcpy(image->magick, m->name, sizeof(image->magick));
    return magick;
}


/**
 * Add a simulated three-dimensional border around the image.
 *
 * @overload frame(width = self.columns+25*2, height = self.rows+25*2, x = 25, y = 25, inner_bevel = 6, outer_bevel = 6, color = self.matte_color)
 *   @param width [Numeric] The width of the left and right sides.
 *   @param height [Numeric] The height of the top and bottom sides.
 *   @param x [Numeric] The offset of the image from the upper-left outside corner of the border.
 *   @param y [Numeric] The offset of the image from the upper-left outside corner of the border.
 *   @param inner_bevel [Numeric] The width of the inner shadows of the border.
 *   @param outer_bevel [Numeric] The width of the outer shadows of the border.
 *   @param color [Magick::Pixel, String] The border color.
 *   @return [Magick::Image] a new image.
 */
VALUE
Image_frame(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ExceptionInfo *exception;
    FrameInfo frame_info;

    image = rm_check_destroyed(self);

    frame_info.width = image->columns + 50;
    frame_info.height = image->rows + 50;
    frame_info.x = 25;
    frame_info.y = 25;
    frame_info.inner_bevel = 6;
    frame_info.outer_bevel = 6;

    switch (argc)
    {
        case 7:
            Color_to_PixelColor(&image->matte_color, argv[6]);
        case 6:
            frame_info.outer_bevel = NUM2LONG(argv[5]);
        case 5:
            frame_info.inner_bevel = NUM2LONG(argv[4]);
        case 4:
            frame_info.y = NUM2LONG(argv[3]);
        case 3:
            frame_info.x = NUM2LONG(argv[2]);
        case 2:
            frame_info.height = image->rows + 2*NUM2LONG(argv[1]);
        case 1:
            frame_info.width = image->columns + 2*NUM2LONG(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 7)", argc);
            break;
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(FrameImage) args = { image, &frame_info, image->compose, exception };
#else
    GVL_STRUCT_TYPE(FrameImage) args = { image, &frame_info, exception };
#endif
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(FrameImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Convert direct to memory image formats from string data.
 *
 * @overload from_blob(blob)
 *   @param blob [String] the blob data
 *
 * @overload from_blob(blob)
 *   This yields {Magick::Image::Info} to block with its object's scope.
 *   @param blob [String] the blob data
 *   @yield [info]
 *   @yieldparam info [Magick::Image::Info]
 *
 * @return [Array<Magick::Image>] an array of new images
 * @see Image#to_blob
 */
VALUE
Image_from_blob(VALUE klass ATTRIBUTE_UNUSED, VALUE blob_arg)
{
    Image *images;
    Info *info;
    VALUE info_obj;
    ExceptionInfo *exception;
    void *blob;
    size_t length;

    blob = (void *) rm_str2cstr(blob_arg, &length);

    // Get a new Info object - run the parm block if supplied
    info_obj = rm_info_new();
    TypedData_Get_Struct(info_obj, Info, &rm_info_data_type, info);

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(BlobToImage) args = { info,  blob, (size_t)length, exception };
    images = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(BlobToImage), &args);
    rm_check_exception(exception, images, DestroyOnError);

    DestroyExceptionInfo(exception);

    rm_ensure_result(images);
    rm_set_user_artifact(images, info);
    rm_sync_image_options(images, info);

    RB_GC_GUARD(info_obj);

    return array_from_images(images);
}


/**
 * Set the function on a channel.
 *
 * @overload function_channel(function, *args, channel = Magick::AllChannels)
 *   @param function [Magick::MagickFunction] the function
 *   @param *args [Numeric] One or more floating-point numbers.
 *     The number of parameters depends on the function. See the ImageMagick documentation for
 *     details.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload function_channel(function, *args, *channels)
 *   @param function [Magick::MagickFunction] the function
 *   @param *args [Numeric] One or more floating-point numbers.
 *     The number of parameters depends on the function. See the ImageMagick documentation for
 *     details.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 * @see https://www.imagemagick.org/script/command-line-options.php#function
 */
VALUE
Image_function_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    MagickFunction function;
    unsigned long n, nparms;
    double *parms;
    ChannelType channels;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    // The number of parameters depends on the function.
    if (argc == 0)
    {
        rb_raise(rb_eArgError, "no function specified");
    }

    VALUE_TO_ENUM(argv[0], function, MagickFunction);
    argc -= 1;
    argv += 1;

    switch (function)
    {
        case PolynomialFunction:
            if (argc == 0)
            {
                rb_raise(rb_eArgError, "PolynomialFunction requires at least one argument.");
            }
            break;
        case SinusoidFunction:
        case ArcsinFunction:
        case ArctanFunction:
           if (argc < 1 || argc > 4)
           {
               rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 to 4)", argc);
           }
           break;
        default:
            rb_raise(rb_eArgError, "undefined function");
            break;
    }

    nparms = argc;
    parms = ALLOC_N(double, nparms);

    for (n = 0; n < nparms; n++)
    {
        VALUE element = argv[n];
        if (rm_check_num2dbl(element))
        {
            parms[n] = NUM2DBL(element);
        }
        else
        {
            xfree(parms);
            rb_raise(rb_eTypeError, "type mismatch: %s given", rb_class2name(CLASS_OF(element)));
        }
    }

    exception = AcquireExceptionInfo();
    new_image = rm_clone_image(image);
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(new_image, channels);
    GVL_STRUCT_TYPE(FunctionImage) args = { new_image, function, nparms, parms, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(FunctionImage), &args);
    END_CHANNEL_MASK(new_image);
#else
    GVL_STRUCT_TYPE(FunctionImageChannel) args = { new_image, channels, function, nparms, parms, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(FunctionImageChannel), &args);
#endif
    xfree(parms);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Get the number of algorithms search for a target color.
 * By default the color must be exact.
 * Use this attribute to match colors that are close to the target color in RGB space.
 *
 * @return [Float] the fuzz
 * @see Info#fuzz
 */
VALUE
Image_fuzz(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, fuzz, dbl, &rm_image_data_type);
}


/**
 * Set the number of algorithms search for a target color.
 *
 * @param fuzz [String, Numeric] The argument may be a floating-point numeric value or a string in the
 *   form "NN%".
 * @return [String, Numeric] the given value
 * @see Info#fuzz=
 */
VALUE
Image_fuzz_eq(VALUE self, VALUE fuzz)
{
    Image *image = rm_check_frozen(self);
    image->fuzz = rm_fuzz_to_dbl(fuzz);
    return fuzz;
}


/**
 * Apply fx on the image.
 *
 * @overload fx(expression, channel = Magick::AllChannels)
 *   @param expression [String] A mathematical expression
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload fx(expression, *channels)
 *   @param expression [String] A mathematical expression
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_fx(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    char *expression;
    ChannelType channels;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    // There must be exactly 1 remaining argument.
    if (argc == 0)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (0 for 1 or more)");
    }
    else if (argc > 1)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    expression = StringValueCStr(argv[0]);

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(FxImage) args = { image, expression, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(FxImage), &args);
    CHANGE_RESULT_CHANNEL_MASK(new_image);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(FxImageChannel) args = { image, channels, expression, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(FxImageChannel), &args);
#endif
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}

/**
 * Get the gamma level of the image.
 *
 * @return [Float] the gamma level
 */
VALUE
Image_gamma(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, gamma, dbl, &rm_image_data_type);
}

/**
 * Set the gamma level of the image.
 *
 * @param val [Numeric] the gamma level
 * @return [Numeric] the gamma level
 */
VALUE
Image_gamma_eq(VALUE self, VALUE val)
{
    IMPLEMENT_TYPED_ATTR_WRITER(Image, gamma, dbl, &rm_image_data_type);
}


/**
 * Apply gamma to a channel.
 *
 * @overload gamma_channel(gamma, channel = Magick::AllChannels)
 *   @param Values gamma [Numeric] typically range from 0.8 to 2.3. You can also reduce the influence
 *     of a particular channel with a gamma value of 0.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload gamma_channel(gamma, *channels)
 *   @param Values gamma [Numeric] typically range from 0.8 to 2.3. You can also reduce the influence
 *     of a particular channel with a gamma value of 0.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_gamma_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ChannelType channels;
    double gamma;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    // There must be exactly one remaining argument.
    if (argc == 0)
    {
        rb_raise(rb_eArgError, "missing gamma argument");
    }
    else if (argc > 1)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    gamma = NUM2DBL(argv[0]);
    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(new_image, channels);
    GVL_STRUCT_TYPE(GammaImage) args = { new_image, gamma, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GammaImage), &args);
    END_CHANNEL_MASK(new_image);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(GammaImageChannel) args = { new_image, channels, gamma };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GammaImageChannel), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * gamma-correct an image.
 *
 * @overload gamma_correct(red_gamma, green_gamma = red_gamma, blue_gamma = green_gamma)
 *   @return [Magick::Image] a new image
 */
VALUE
Image_gamma_correct(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double red_gamma, green_gamma, blue_gamma;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 1:
            red_gamma   = NUM2DBL(argv[0]);
            green_gamma = blue_gamma = red_gamma;
            break;
        case 2:
            red_gamma   = NUM2DBL(argv[0]);
            green_gamma = NUM2DBL(argv[1]);
            blue_gamma  = green_gamma;
            break;
        case 3:
        case 4:
            red_gamma     = NUM2DBL(argv[0]);
            green_gamma   = NUM2DBL(argv[1]);
            blue_gamma    = NUM2DBL(argv[2]);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 to 3)", argc);
            break;
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
#endif

    if ((red_gamma == green_gamma) && (green_gamma == blue_gamma))
    {
#if defined(IMAGEMAGICK_7)
        BEGIN_CHANNEL_MASK(new_image, (ChannelType) (RedChannel | GreenChannel | BlueChannel));
        GVL_STRUCT_TYPE(GammaImage) args = { new_image, red_gamma, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GammaImage), &args);
        END_CHANNEL_MASK(new_image);
#else
        GVL_STRUCT_TYPE(GammaImageChannel) args = { new_image, (ChannelType) (RedChannel | GreenChannel | BlueChannel), red_gamma };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GammaImageChannel), &args);
#endif
    }
    else
    {
#if defined(IMAGEMAGICK_7)
        BEGIN_CHANNEL_MASK(new_image, RedChannel);
        GVL_STRUCT_TYPE(GammaImage) args1 = { new_image, red_gamma, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GammaImage), &args1);
        END_CHANNEL_MASK(new_image);

        BEGIN_CHANNEL_MASK(new_image, GreenChannel);
        GVL_STRUCT_TYPE(GammaImage) args2 = { new_image, green_gamma, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GammaImage), &args2);
        END_CHANNEL_MASK(new_image);

        BEGIN_CHANNEL_MASK(new_image, BlueChannel);
        GVL_STRUCT_TYPE(GammaImage) args3 = { new_image, blue_gamma, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GammaImage), &args3);
        END_CHANNEL_MASK(new_image);
#else
        GVL_STRUCT_TYPE(GammaImageChannel) args1 = { new_image, RedChannel, red_gamma };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GammaImageChannel), &args1);

        GVL_STRUCT_TYPE(GammaImageChannel) args2 = { new_image, GreenChannel, green_gamma };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GammaImageChannel), &args2);

        GVL_STRUCT_TYPE(GammaImageChannel) args3 = { new_image, BlueChannel, blue_gamma };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GammaImageChannel), &args3);
#endif
    }

#if defined(IMAGEMAGICK_7)
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Blur the image.
 *
 * @overload gaussian_blur(radius = 0.0, sigma = 1.0)
 *   @param radius [Numeric] The radius of the Gaussian operator.
 *   @param sigma [Numeric] The sigma (standard deviation) of the Gaussian operator.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_gaussian_blur(int argc, VALUE *argv, VALUE self)
{
    return effect_image(self, argc, argv, GVL_FUNC(GaussianBlurImage));
}


/**
 * Blur the image on a channel.
 *
 * @overload gaussian_blur_channel(radius = 0.0, sigma = 1.0, channel = Magick::AllChannels)
 *   @param radius [Numeric] The radius of the Gaussian operator.
 *   @param sigma [Numeric] The sigma (standard deviation) of the Gaussian operator.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload gaussian_blur_channel(radius = 0.0, sigma = 1.0, *channels)
 *   @param radius [Numeric] The radius of the Gaussian operator.
 *   @param sigma [Numeric] The sigma (standard deviation) of the Gaussian operator.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_gaussian_blur_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ChannelType channels;
    ExceptionInfo *exception;
    double radius = 0.0, sigma = 1.0;

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    // There can be 0, 1, or 2 remaining arguments.
    switch (argc)
    {
        case 2:
            sigma = NUM2DBL(argv[1]);
            /* Fall thru */
        case 1:
            radius = NUM2DBL(argv[0]);
            /* Fall thru */
        case 0:
            break;
        default:
            raise_ChannelType_error(argv[argc-1]);
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(GaussianBlurImage) args = { image, radius, sigma, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GaussianBlurImage), &args);
    CHANGE_RESULT_CHANNEL_MASK(new_image);
    END_CHANNEL_MASK(image);
    rm_check_exception(exception, new_image, DestroyOnError);
#else
    GVL_STRUCT_TYPE(GaussianBlurImageChannel) args = { image, channels, radius, sigma, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GaussianBlurImageChannel), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
#endif

    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Get the preferred size of the image when encoding.
 *
 * @return [String] the geometry
 * @see https://www.imagemagick.org/Magick++/Geometry.html
 */
VALUE
Image_geometry(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, geometry, str, &rm_image_data_type);
}


/**
 * Set the preferred size of the image when encoding.
 *
 * @param geometry [Magick::Geometry, String] the geometry
 * @return [Magick::Geometry, String] the given geometry
 * @see https://www.imagemagick.org/Magick++/Geometry.html
 */
VALUE
Image_geometry_eq(VALUE self, VALUE geometry)
{
    Image *image;
    VALUE geom_str;
    char *geom;

    image = rm_check_frozen(self);

    if (geometry == Qnil)
    {
        magick_free(image->geometry);
        image->geometry = NULL;
        return self;
    }


    geom_str = rb_String(geometry);
    geom = StringValueCStr(geom_str);
    if (!IsGeometry(geom))
    {
        rb_raise(rb_eTypeError, "invalid geometry: %s", geom);
    }
    magick_clone_string(&image->geometry, geom);

    RB_GC_GUARD(geom_str);

    return geometry;
}


/**
 * Gets the pixels from the specified rectangle within the image.
 *
 * @param x_arg [Numeric] x position of start of region
 * @param y_arg [Numeric] y position of start of region
 * @param cols_arg [Numeric] width of region
 * @param rows_arg [Numeric] height of region
 * @return [Array<Magick::Pixel>] An array of Magick::Pixel objects corresponding to the pixels in the rectangle
 *   defined by the geometry parameters.
 * @see Image#store_pixels
 */
VALUE
Image_get_pixels(VALUE self, VALUE x_arg, VALUE y_arg, VALUE cols_arg, VALUE rows_arg)
{
    Image *image;
    ExceptionInfo *exception;
    long x, y;
    unsigned long columns, rows;
    long size, n;
    VALUE pixel_ary;
#if defined(IMAGEMAGICK_7)
    const Quantum *pixels;
#else
    const PixelPacket *pixels;
    const IndexPacket *indexes;
#endif

    image = rm_check_destroyed(self);
    x       = NUM2LONG(x_arg);
    y       = NUM2LONG(y_arg);
    columns = NUM2ULONG(cols_arg);
    rows    = NUM2ULONG(rows_arg);

    if ((x+columns) > image->columns || (y+rows) > image->rows)
    {
        rb_raise(rb_eRangeError, "geometry (%lux%lu%+ld%+ld) exceeds image bounds",
                 columns, rows, x, y);
    }

    // Cast AcquireImagePixels to get rid of the const qualifier. We're not going
    // to change the pixels but I don't want to make "pixels" const.
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(GetVirtualPixels) args = { image, x, y, columns, rows, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetVirtualPixels), &args);
    pixels = reinterpret_cast<decltype(pixels)>(ret);
    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    // If the function failed, return a 0-length array.
    if (!pixels)
    {
        return rb_ary_new();
    }

    // Allocate an array big enough to contain the PixelPackets.
    size = (long)(columns * rows);
    pixel_ary = rb_ary_new2(size);

#if defined(IMAGEMAGICK_6)
    indexes = GetVirtualIndexQueue(image);
#endif

    // Convert the PixelPackets to Magick::Pixel objects
    for (n = 0; n < size; n++)
    {
#if defined(IMAGEMAGICK_7)
        PixelPacket color;
        memset(&color, 0, sizeof(color));
        color.red   = GetPixelRed(image, pixels);
        color.green = GetPixelGreen(image, pixels);
        color.blue  = GetPixelBlue(image, pixels);
        color.alpha = GetPixelAlpha(image, pixels);
        color.black = GetPixelBlack(image, pixels);
        rb_ary_store(pixel_ary, n, Pixel_from_PixelPacket(&color));

        pixels += GetPixelChannels(image);
#else
        MagickPixel mpp;
        mpp.red = GetPixelRed(pixels);
        mpp.green = GetPixelGreen(pixels);
        mpp.blue = GetPixelBlue(pixels);
        mpp.opacity = GetPixelOpacity(pixels);
        if (indexes)
        {
            mpp.index = GetPixelIndex(indexes + n);
        }
        rb_ary_store(pixel_ary, n, Pixel_from_MagickPixel(&mpp));
        pixels++;
#endif
    }

    return pixel_ary;
}


/**
 * Run a function testing whether this image has an attribute.
 *
 * No Ruby usage (internal function)
 *
 * @param self this object
 * @param attr_test the attribute testing function
 * @return the result of attr_test.
 */
static VALUE
has_attribute(VALUE self, MagickBooleanType (attr_test)(const Image *, ExceptionInfo *))
{
    Image *image;
    ExceptionInfo *exception;
    MagickBooleanType r;

    image = rm_check_destroyed(self);
    exception = AcquireExceptionInfo();

    r = (attr_test)(image, exception);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);

    return r ? Qtrue : Qfalse;
}


#if defined(IMAGEMAGICK_7)
/**
 * Run a function testing whether this image has an attribute.
 *
 * No Ruby usage (internal function)
 *
 * @param self this object
 * @param attr_test the attribute testing function
 * @return the result of attr_test.
 */
static VALUE
has_image_attribute(VALUE self, MagickBooleanType (attr_test)(const Image *))
{
    Image *image;
    MagickBooleanType r;

    image = rm_check_destroyed(self);
    r = (attr_test)(image);

    return r ? Qtrue : Qfalse;
}
#endif


/**
 * Return true if all the pixels in the image have the same red, green, and blue intensities.
 *
 * @return [Boolean] true if image is gray, false otherwise
 */
VALUE
Image_gray_q(VALUE self)
{
#if defined(HAVE_SETIMAGEGRAY)
    return has_attribute(self, (MagickBooleanType (*)(const Image *, ExceptionInfo *))SetImageGray);
#else
    return has_attribute(self, IsGrayImage);
#endif
}


/**
 * Return true if has 1024 unique colors or less.
 *
 * @return [Boolean] true if image has <= 1024 unique colors
 */
VALUE
Image_histogram_q(VALUE self)
{
    return has_attribute(self, IsHistogramImage);
}


/**
 * Implode the image by the specified percentage.
 *
 * @overload implode(amount = 0.50)
 *   @param amount [Numeric] Increasing the absolute value of the argument increases the effect.
 *     The value may be positive for implosion, or negative for explosion. The default is 0.50.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_implode(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double amount = 0.50;
    ExceptionInfo *exception;

    switch (argc)
    {
        case 1:
            amount = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 or 1)", argc);
    }

    image = rm_check_destroyed(self);
    exception = AcquireExceptionInfo();

#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(ImplodeImage) args = { image, amount, image->interpolate, exception };
#else
    GVL_STRUCT_TYPE(ImplodeImage) args = { image, amount, exception };
#endif
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ImplodeImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Store image pixel data from an array.
 *
 * @overload store_pixels(x, y, columns, rows, map, pixels, type = Magick::CharPixel)
 *   @param x [Numeric] The x-offset of the rectangle to be replaced.
 *   @param y [Numeric] The y-offset of the rectangle to be replaced.
 *   @param columns [Numeric] The number of columns in the rectangle.
 *   @param rows [Numeric] The number of rows in the rectangle.
 *   @param map [String] his string reflects the expected ordering of the pixel array.
 *   @param pixels [Array] An array of pixels.
 *     The number of pixels in the array must be the same as the number
 *     of pixels in the rectangle, that is, rows*columns.
 *   @param type [Magick::StorageType] A StorageType value that specifies the C datatype to which
 *     the pixel data will be converted.
 *   @return [Magick::Image] self
 *   @see Image#export_pixels
 */
VALUE
Image_import_pixels(int argc, VALUE *argv, VALUE self)
{
    Image *image;
    long x_off, y_off;
    unsigned long cols, rows;
    unsigned long n, npixels;
    size_t buffer_l;
    char *map;
    VALUE pixel_arg, pixel_ary;
    StorageType stg_type = CharPixel;
    size_t type_sz, map_l;
    Quantum *pixels = NULL;
    double *fpixels = NULL;
    void *buffer;
    MagickBooleanType okay;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_frozen(self);

    switch (argc)
    {
        case 7:
            VALUE_TO_ENUM(argv[6], stg_type, StorageType);
        case 6:
            x_off = NUM2LONG(argv[0]);
            y_off = NUM2LONG(argv[1]);
            cols = NUM2ULONG(argv[2]);
            rows = NUM2ULONG(argv[3]);
            map = StringValueCStr(argv[4]);
            pixel_arg = argv[5];
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 6 or 7)", argc);
            break;
    }

    if (x_off < 0 || y_off < 0 || cols <= 0 || rows <= 0)
    {
        rb_raise(rb_eArgError, "invalid import geometry");
    }

    map_l = rm_strnlen_s(map, MaxTextExtent);
    npixels = cols * rows * map_l;

    // Assume that any object that responds to :to_str is a string buffer containing
    // binary pixel data.
    if (rb_respond_to(pixel_arg, rb_intern("to_str")))
    {
        buffer = (void *)rm_str2cstr(pixel_arg, &buffer_l);
        switch (stg_type)
        {
            case CharPixel:
                type_sz = 1;
                break;
            case ShortPixel:
                type_sz = sizeof(unsigned short);
                break;
            case LongPixel:
                type_sz = sizeof(unsigned long);
                break;
            case DoublePixel:
                type_sz = sizeof(double);
                break;
            case FloatPixel:
                type_sz = sizeof(float);
                break;
            case QuantumPixel:
                type_sz = sizeof(Quantum);
                break;
            default:
                rb_raise(rb_eArgError, "unsupported storage type %s", StorageType_name(stg_type));
                break;
        }

        if (buffer_l % type_sz != 0)
        {
            rb_raise(rb_eArgError, "pixel buffer must be an exact multiple of the storage type size");
        }
        if ((buffer_l / type_sz) % map_l != 0)
        {
            rb_raise(rb_eArgError, "pixel buffer must contain an exact multiple of the map length");
        }
        if ((unsigned long)(buffer_l / type_sz) < npixels)
        {
            rb_raise(rb_eArgError, "pixel buffer too small (need %lu channel values, got %" RMIuSIZE ")",
                     npixels, buffer_l/type_sz);
        }
    }
    // Otherwise convert the argument to an array and convert the array elements
    // to binary pixel data.
    else
    {
        // rb_Array converts an object that is not an array to an array if possible,
        // and raises TypeError if it can't. It usually is possible.
        pixel_ary = rb_Array(pixel_arg);

        if (RARRAY_LEN(pixel_ary) % map_l != 0)
        {
            rb_raise(rb_eArgError, "pixel array must contain an exact multiple of the map length");
        }
        if ((unsigned long)RARRAY_LEN(pixel_ary) < npixels)
        {
            rb_raise(rb_eArgError, "pixel array too small (need %lu elements, got %ld)",
                     npixels, RARRAY_LEN(pixel_ary));
        }

        if (stg_type == DoublePixel || stg_type == FloatPixel)
        {
            fpixels = ALLOC_N(double, npixels);
            for (n = 0; n < npixels; n++)
            {
                VALUE element = rb_ary_entry(pixel_ary, n);
                if (rm_check_num2dbl(element))
                {
                    fpixels[n] = NUM2DBL(element);
                }
                else
                {
                    xfree(fpixels);
                    rb_raise(rb_eTypeError, "type mismatch: %s given", rb_class2name(CLASS_OF(element)));
                }
            }
            buffer = (void *) fpixels;
            stg_type = DoublePixel;
        }
        else
        {
            pixels = ALLOC_N(Quantum, npixels);
            for (n = 0; n < npixels; n++)
            {
                VALUE element = rb_ary_entry(pixel_ary, n);
                if (rm_check_num2dbl(element))
                {
                    pixels[n] = NUM2DBL(element);
                }
                else
                {
                    xfree(pixels);
                    rb_raise(rb_eTypeError, "type mismatch: %s given", rb_class2name(CLASS_OF(element)));
                }
            }
            buffer = (void *) pixels;
            stg_type = QuantumPixel;
        }
    }


#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(ImportImagePixels) args = { image, x_off, y_off, cols, rows, map, stg_type, buffer, exception };
#else
    GVL_STRUCT_TYPE(ImportImagePixels) args = { image, x_off, y_off, cols, rows, map, stg_type, buffer };
#endif
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ImportImagePixels), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));

    // Free pixel array before checking for errors.
    if (pixels)
    {
        xfree((void *)pixels);
    }
    if (fpixels)
    {
        xfree((void *)fpixels);
    }

    if (!okay)
    {
#if defined(IMAGEMAGICK_7)
        CHECK_EXCEPTION();
        DestroyExceptionInfo(exception);
#else
        rm_check_image_exception(image, RetainOnError);
#endif
        // Shouldn't get here...
        rm_magick_error("ImportImagePixels failed with no explanation.");
    }
#if defined(IMAGEMAGICK_7)
    DestroyExceptionInfo(exception);
#endif

    RB_GC_GUARD(pixel_arg);
    RB_GC_GUARD(pixel_ary);

    return self;
}


/**
 * Override Object#inspect - return a string description of the image.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - This is essentially the IdentifyImage except the description is built in
 *     a char buffer instead of being written to a file.
 *
 * @param image the image to inspect
 * @param buffer buffer for the output string
 * @param len length of buffer
 * @see Image_inspect
 */
static void
build_inspect_string(Image *image, char *buffer, size_t len)
{
    unsigned long quantum_depth;
    int x = 0;                  // # bytes used in buffer

    // Print magick filename if different from current filename.
    if (*image->magick_filename != '\0' && strcmp(image->magick_filename, image->filename) != 0)
    {
        x += snprintf(buffer+x, len-x, "%.1024s=>", image->magick_filename);
    }
    // Print current filename.
    x += snprintf(buffer+x, len-x, "%.1024s", image->filename);
    // Print scene number.
    if ((GetPreviousImageInList(image) != NULL) && (GetNextImageInList(image) != NULL) && image->scene > 0)
    {
        x += snprintf(buffer+x, len-x, "[%" RMIuSIZE "]", image->scene);
    }
    // Print format
    x += snprintf(buffer+x, len-x, " %s ", image->magick);

    // Print magick columnsXrows if different from current.
    if (image->magick_columns != 0 || image->magick_rows != 0)
    {
        if (image->magick_columns != image->columns || image->magick_rows != image->rows)
        {
            x += snprintf(buffer+x, len-x, "%" RMIuSIZE "x%" RMIuSIZE "=>", image->magick_columns, image->magick_rows);
        }
    }

    x += snprintf(buffer+x, len-x, "%" RMIuSIZE "x%" RMIuSIZE " ", image->columns, image->rows);

    // Print current columnsXrows
    if (   image->page.width != 0 || image->page.height != 0
           || image->page.x != 0     || image->page.y != 0)
    {
        x += snprintf(buffer+x, len-x, "%" RMIuSIZE "x%" RMIuSIZE "+%" RMIdSIZE "+%" RMIdSIZE " ",
                      image->page.width, image->page.height,
                      image->page.x, image->page.y);
    }

    if (image->storage_class == DirectClass)
    {
        x += snprintf(buffer+x, len-x, "DirectClass ");
        if (image->total_colors != 0)
        {
            if (image->total_colors >= (unsigned long)(1 << 24))
            {
                x += snprintf(buffer+x, len-x, "%" RMIuSIZE "mc ", image->total_colors/1024/1024);
            }
            else
            {
                if (image->total_colors >= (unsigned long)(1 << 16))
                {
                    x += snprintf(buffer+x, len-x, "%" RMIuSIZE "kc ", image->total_colors/1024);
                }
                else
                {
                    x += snprintf(buffer+x, len-x, "%" RMIuSIZE "c ", image->total_colors);
                }
            }
        }
    }
    else
    {
        // Cast `image->colors' to long to suppress gcc warnings when
        // building with GM. GM defines that field as an unsigned int.
        if (image->total_colors <= image->colors)
        {
            x += snprintf(buffer+x, len-x, "PseudoClass %ldc ", (long) image->colors);
        }
        else
        {
            x += snprintf(buffer+x, len-x, "PseudoClass %" RMIuSIZE "=>%" RMIuSIZE "c ", image->total_colors, image->colors);
            if (image->error.mean_error_per_pixel != 0.0)
            {
                x += snprintf(buffer+x, len-x, "%ld/%.6f/%.6fdb ",
                              (long) (image->error.mean_error_per_pixel+0.5),
                              image->error.normalized_mean_error,
                              image->error.normalized_maximum_error);
            }
        }
    }

    // Print bit depth
    quantum_depth = GetImageQuantumDepth(image, MagickTrue);
    x += snprintf(buffer+x, len-x, "%lu-bit", quantum_depth);

    // Print blob info if appropriate.
    if (GetBlobSize(image) != 0)
    {
        if (GetBlobSize(image) >= (1 << 24))
        {
            x += snprintf(buffer+x, len-x, " %lumb", (unsigned long) (GetBlobSize(image)/1024/1024));
        }
        else if (GetBlobSize(image) >= 1024)
        {
            x += snprintf(buffer+x, len-x, " %lukb", (unsigned long) (GetBlobSize(image)/1024));
        }
        else
        {
            x += snprintf(buffer+x, len-x, " %lub", (unsigned long) GetBlobSize(image));
        }
    }


    if (len-1-x > 6)
    {
        size_t value_l;
        const char *value = GetImageArtifact(image, "user");
        if (value)
        {
            strcpy(buffer+x, " user:");
            x += 6;
            value_l = len - x - 1;
            value_l = min(rm_strnlen_s(value, MaxTextExtent), value_l);
            memcpy(buffer+x, value, value_l);
            x += value_l;
        }
    }

    assert(x < (int)(len-1));
    buffer[x] = '\0';

    return;
}


/**
 * Override {Object#inspect} - return a string description of the image.
 *
 * @return [String] the string
 */
VALUE
Image_inspect(VALUE self)
{
    Image *image;
    char buffer[MaxTextExtent];          // image description buffer

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);
    if (!image)
    {
        return rb_str_new2("#<Magick::Image: (destroyed)>");
    }
    build_inspect_string(image, buffer, sizeof(buffer));
    return rb_str_new2(buffer);
}


/**
 * Get the type of interlacing scheme (default NoInterlace).
 * This option is used to specify the type of interlacing scheme for raw image formats such as RGB
 * or YUV.
 * NoInterlace means do not interlace, LineInterlace uses scanline interlacing, and PlaneInterlace
 * uses plane interlacing. PartitionInterlace is like PlaneInterlace except the different planes are
 * saved to individual files (e.g. image.R, image.G, and image.B).
 *
 * @return [Magick::InterlaceType] the interlace
 */
VALUE
Image_interlace(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return InterlaceType_find(image->interlace);
}


/**
 * Set the type of interlacing scheme.
 *
 * @param interlace [Magick::InterlaceType] the interlace
 * @return [Magick::InterlaceType] the given value
 */
VALUE
Image_interlace_eq(VALUE self, VALUE interlace)
{
    Image *image = rm_check_frozen(self);
    VALUE_TO_ENUM(interlace, image->interlace, InterlaceType);
    return interlace;
}


/**
 * Return the IPTC profile as a String.
 *
 * @return [String, nil] the IPTC profile if it exists, otherwise nil
 */
VALUE
Image_iptc_profile(VALUE self)
{
    Image *image;
    const StringInfo *profile;

    image = rm_check_destroyed(self);
    profile = GetImageProfile(image, "iptc");
    if (!profile)
    {
        return Qnil;
    }

    return rb_str_new((char *)profile->datum, (long)profile->length);

}



/**
 * Set the IPTC profile. The argument is a string.
 *
 * @param profile [String, nil] the IPTC profile
 * @return [String, nil] the given profile
 */
VALUE
Image_iptc_profile_eq(VALUE self, VALUE profile)
{
    Image_delete_profile(self, rb_str_new2("iptc"));
    if (profile != Qnil)
    {
        set_profile(self, "iptc", profile);
    }
    return profile;
}


/*
 *  These are undocumented methods. The writer is
 *  called only by Image#iterations=.
 *  The reader is only used by the unit tests!
 */
VALUE
Image_iterations(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, iterations, int, &rm_image_data_type);
}
VALUE
Image_iterations_eq(VALUE self, VALUE val)
{
    IMPLEMENT_TYPED_ATTR_WRITER(Image, iterations, int, &rm_image_data_type);
}

/**
 * Adjusts the levels of an image by scaling the colors falling between specified white and black
 * points to the full available quantum range.
 *
 * @overload level2(black_point = 0.0, white_point = Magick::QuantumRange, gamma = 1.0)
 *   @param black_point [Numeric] A black point level in the range 0 - QuantumRange.
 *   @param white_point [Numeric] A white point level in the range 0..QuantumRange.
 *   @param gamma [Numeric] A gamma correction in the range 0.0 - 10.0.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_level2(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double black_point = 0.0, gamma_val = 1.0, white_point = (double)QuantumRange;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#else
    char level[50];
#endif

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 0:             // take all the defaults
            break;
        case 1:
            black_point = NUM2DBL(argv[0]);
            white_point = QuantumRange - black_point;
            break;
        case 2:
            black_point = NUM2DBL(argv[0]);
            white_point = NUM2DBL(argv[1]);
            break;
        case 3:
            black_point = NUM2DBL(argv[0]);
            white_point = NUM2DBL(argv[1]);
            gamma_val   = NUM2DBL(argv[2]);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 3)", argc);
            break;
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(LevelImage) args = { new_image, black_point, white_point, gamma_val, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(LevelImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    snprintf(level, sizeof(level), "%gx%g+%g", black_point, white_point, gamma_val);
    GVL_STRUCT_TYPE(LevelImage) args = { new_image, level };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(LevelImage), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Similar to {Image#level2} but applies to a single channel only.
 *
 * @overload level_channel(aChannelType, black = 0.0, white = 1.0, gamma = Magick::QuantumRange)
 *   @param aChannelType [Magick::ChannelType] A ChannelType value.
 *   @param black [Numeric] A black point level in the range 0..QuantumRange.
 *   @param white [Numeric] A white point level in the range 0..QuantumRange.
 *   @param gamma [Numeric] A gamma correction in the range 0.0 - 10.0.
 *   @return [Magick::Image] a new image
 *   @see Image#level2
 */
VALUE
Image_level_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double black_point = 0.0, gamma_val = 1.0, white_point = (double)QuantumRange;
    ChannelType channel;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 1:             // take all the defaults
            break;
        case 2:
            black_point = NUM2DBL(argv[1]);
            white_point = QuantumRange - black_point;
            break;
        case 3:
            black_point = NUM2DBL(argv[1]);
            white_point = NUM2DBL(argv[2]);
            break;
        case 4:
            black_point = NUM2DBL(argv[1]);
            white_point = NUM2DBL(argv[2]);
            gamma_val   = NUM2DBL(argv[3]);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 to 4)", argc);
            break;
    }

    VALUE_TO_ENUM(argv[0], channel, ChannelType);

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(new_image, channel);
    GVL_STRUCT_TYPE(LevelImage) args = { new_image, black_point, white_point, gamma_val, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(LevelImage), &args);
    END_CHANNEL_MASK(new_image);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(LevelImageChannel) args = { new_image, channel, black_point, white_point, gamma_val };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(LevelImageChannel), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * When invert is true, black and white will be mapped to the black_color and white_color colors,
 * compressing all other colors linearly. When invert is false, black and white will be mapped to
 * the black_color and white_color colors, stretching all other colors linearly.
 *
 * @overload level_colors(black_color = "black", white_color = "white", invert = true, channel = Magick::AllChannels)
 *   @param black_color [Magick::Pixel, String] The color to be mapped to black
 *   @param white_color [Magick::Pixel, String] The color to be mapped to white
 *   @param invert See the description above
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload level_colors(black_color = "black", white_color = "white", invert = true, *channels)
 *   @param black_color [Magick::Pixel, String] The color to be mapped to black
 *   @param white_color [Magick::Pixel, String] The color to be mapped to white
 *   @param invert See the description above
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_level_colors(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    MagickPixel black_color, white_color;
    ChannelType channels;
    MagickBooleanType invert = MagickTrue;
    MagickBooleanType okay;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

    channels = extract_channels(&argc, argv);

    rm_init_magickpixel(image, &white_color);
    rm_init_magickpixel(image, &black_color);

    switch (argc)
    {
        case 3:
            invert = (MagickBooleanType)RTEST(argv[2]);

        case 2:
            Color_to_MagickPixel(image, &white_color, argv[1]);
            Color_to_MagickPixel(image, &black_color, argv[0]);
            break;

        case 1:
            rm_set_magickpixel(&white_color, "white");
            Color_to_MagickPixel(image, &black_color, argv[0]);
            break;

        case 0:
            rm_set_magickpixel(&white_color, "white");
            rm_set_magickpixel(&black_color, "black");
            break;

        default:
            raise_ChannelType_error(argv[argc-1]);
            break;
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(new_image, channels);
    GVL_STRUCT_TYPE(LevelImageColors) args = { new_image, &black_color, &white_color, invert, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(LevelImageColors), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    END_CHANNEL_MASK(new_image);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(LevelColorsImageChannel) args = { new_image, channels, &black_color, &white_color, invert };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(LevelColorsImageChannel), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    rm_check_image_exception(new_image, DestroyOnError);
#endif
    if (!okay)
    {
        rb_raise(rb_eRuntimeError, "LevelImageColors failed for unknown reason.");
    }

    return rm_image_new(new_image);
}



/**
 * Maps black and white to the specified points. The reverse of {Image#level_channel}.
 *
 * @overload levelize_channel(black_point, white_point = Magick::QuantumRange - black_point, gamma = 1.0, channel = Magick::AllChannels)
 *   @param black [Numeric] A black point level in the range 0..QuantumRange.
 *   @param white [Numeric] A white point level in the range 0..QuantumRange.
 *   @param gamma [Numeric] A gamma correction in the range 0.0 - 10.0.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload levelize_channel(black_point, white_point = Magick::QuantumRange - black_point, gamma = 1.0, *channels)
 *   @param black [Numeric] A black point level in the range 0..QuantumRange.
 *   @param white [Numeric] A white point level in the range 0..QuantumRange.
 *   @param gamma [Numeric] A gamma correction in the range 0.0 - 10.0.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_levelize_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ChannelType channels;
    double black_point, white_point;
    double gamma = 1.0;
    MagickBooleanType okay;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);
    if (argc > 3)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    switch (argc)
    {
        case 3:
            gamma = NUM2DBL(argv[2]);
        case 2:
            white_point = NUM2DBL(argv[1]);
            black_point = NUM2DBL(argv[0]);
            break;
        case 1:
            black_point = NUM2DBL(argv[0]);
            white_point = QuantumRange - black_point;
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or more)", argc);
            break;
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(new_image, channels);
    GVL_STRUCT_TYPE(LevelizeImage) args = { new_image, black_point, white_point, gamma, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(LevelizeImage), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    END_CHANNEL_MASK(new_image);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(LevelizeImageChannel) args = { new_image, channels, black_point, white_point, gamma };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(LevelizeImageChannel), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    if (!okay)
    {
        rb_raise(rb_eRuntimeError, "LevelizeImageChannel failed for unknown reason.");
    }
    return rm_image_new(new_image);
}


/**
 * Linear with saturation stretch.
 *
 * @overload linear_stretch(black_point, white_point = pixels - black_point)
 *   @param black_point [Numeric, String] black out at most this many pixels.
 *     Specify an absolute number of pixels as a numeric value, or a percentage as a string in the
 *     form 'NN%'.
 *   @param white_point [Numeric, String] burn at most this many pixels.
 *     Specify an absolute number of pixels as a numeric value, or a percentage as a string in the
 *     form 'NN%'.
 *     This argument is optional. If not specified the default is `(columns * rows) - black_point`.
 *   @return [Magick::Image] a new image
 *   @see Image#contrast_stretch_channel
 */
VALUE
Image_linear_stretch(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double black_point, white_point;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    get_black_white_point(image, argc, argv, &black_point, &white_point);
    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(LinearStretchImage) args = { new_image, black_point, white_point, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(LinearStretchImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(LinearStretchImage) args = { new_image, black_point, white_point };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(LinearStretchImage), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Rescale image with seam carving.
 *
 * @overload liquid_rescale(columns, rows, delta_x = 0.0, rigidity = 0.0)
 *   @param columns [Numeric] The desired width height. Should not exceed 200% of the original
 *     dimension.
 *   @param rows [Numeric] The desired height. Should not exceed 200% of the original dimension.
 *   @param delta_x [Numeric] Maximum seam transversal step (0 means straight seams).
 *   @param rigidity [Numeric] Introduce a bias for non-straight seams (typically 0).
 *   @return [Magick::Image] a new image
 */
VALUE
Image_liquid_rescale(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    unsigned long cols, rows;
    double delta_x = 0.0;
    double rigidity = 0.0;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 4:
            rigidity = NUM2DBL(argv[3]);
        case 3:
            delta_x = NUM2DBL(argv[2]);
        case 2:
            rows = NUM2ULONG(argv[1]);
            cols = NUM2ULONG(argv[0]);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 to 4)", argc);
            break;
    }

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(LiquidRescaleImage) args = { image, cols, rows, delta_x, rigidity, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(LiquidRescaleImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Implement marshalling.
 *
 * @param str [String] the marshalled string
 * @return [Magic::Image] a new image
 * @see Image#_dump
 */
VALUE
Image__load(VALUE klass ATTRIBUTE_UNUSED, VALUE str)
{
    Image *image;
    ImageInfo *info;
    DumpedImage mi;
    ExceptionInfo *exception;
    char *blob;
    size_t length;

    blob = rm_str2cstr(str, &length);

    // Must be as least as big as the 1st 4 fields in DumpedImage
    if (length <= (long)(sizeof(DumpedImage)-MaxTextExtent))
    {
        rb_raise(rb_eTypeError, "image is invalid or corrupted (too short)");
    }

    // Retrieve & validate the image format from the header portion
    mi.id = ((DumpedImage *)blob)->id;
    if (mi.id != DUMPED_IMAGE_ID)
    {
        rb_raise(rb_eTypeError, "image is invalid or corrupted (invalid header)");
    }

    mi.mj = ((DumpedImage *)blob)->mj;
    mi.mi = ((DumpedImage *)blob)->mi;
    if (   mi.mj != DUMPED_IMAGE_MAJOR_VERS
           || mi.mi > DUMPED_IMAGE_MINOR_VERS)
    {
        rb_raise(rb_eTypeError, "incompatible image format (can't be read)\n"
                 "\tformat version %d.%d required; %d.%d given",
                 DUMPED_IMAGE_MAJOR_VERS, DUMPED_IMAGE_MINOR_VERS,
                 mi.mj, mi.mi);
    }

    mi.len = ((DumpedImage *)blob)->len;

    // Must be bigger than the header
    if (length <= (mi.len + sizeof(DumpedImage) - MaxTextExtent))
    {
        rb_raise(rb_eTypeError, "image is invalid or corrupted (too short)");
    }

    info = CloneImageInfo(NULL);

    memcpy(info->magick, ((DumpedImage *)blob)->magick, mi.len);
    info->magick[mi.len] = '\0';

    exception = AcquireExceptionInfo();

    blob += offsetof(DumpedImage, magick) + mi.len;
    length -= offsetof(DumpedImage, magick) + mi.len;
    GVL_STRUCT_TYPE(BlobToImage) args = { info, blob, (size_t)length, exception };
    image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(BlobToImage), &args);
    DestroyImageInfo(info);

    rm_check_exception(exception, image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(image);
}


// aliases for common use of structure types; MagnifyImage, MinifyImage
typedef GVL_STRUCT_TYPE(MagnifyImage) GVL_STRUCT_TYPE(magnify);

/**
 * Scale an image proportionally to twice its size.
 *
 * No Ruby usage (internal function)
 *
 * @param bang whether the bang (!) version of the method was called
 * @param self this object
 * @param magnifier function to use for magnification
 * @return self if bang, otherwise a new image
 */
static VALUE
magnify(int bang, VALUE self, gvl_function_t fp)
{
    Image *image;
    Image *new_image;
    ExceptionInfo *exception;

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);
    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(magnify) args = { image, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(fp, &args);
    rm_check_exception(exception, new_image, DestroyOnError);

    DestroyExceptionInfo(exception);

    if (bang)
    {
        rm_ensure_result(new_image);
        UPDATE_DATA_PTR(self, new_image);
        rm_image_destroy(image);
        return self;
    }

    return rm_image_new(new_image);
}


/**
 * Scale an image proportionally to twice its size.
 *
 * @return [Magick::Image] a new image
 * @see Image#magnify!
 */
VALUE
Image_magnify(VALUE self)
{
    rm_check_destroyed(self);
    return magnify(False, self, GVL_FUNC(MagnifyImage));
}


/**
 * Scale an image proportionally to twice its size.
 * In-place form of {Image#magnify}.
 *
 * @return [Magick::Image] self
 * @see Image#magnify
 */
VALUE
Image_magnify_bang(VALUE self)
{
    rm_check_frozen(self);
    return magnify(True, self, GVL_FUNC(MagnifyImage));
}


/**
 * Support Marshal.dump.
 *
 * @return [Array<String>] The first element in the array is the file name. The second element is the string
 *   of blob.
 */
VALUE
Image_marshal_dump(VALUE self)
{
    Image *image;
    Info *info;
    unsigned char *blob;
    size_t length;
    VALUE ary;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    info = CloneImageInfo(NULL);
    if (!info)
    {
        rb_raise(rb_eNoMemError, "not enough memory to initialize Info object");
    }

    ary = rb_ary_new2(2);
    rb_ary_store(ary, 0, rb_str_new2(image->filename));

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(ImageToBlob) args = { info, image, &length, exception };
    blob = (unsigned char *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ImageToBlob), &args);

    // Destroy info before raising an exception
    DestroyImageInfo(info);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);

    rb_ary_store(ary, 1, rb_str_new((char *)blob, (long)length));
    magick_free((void*)blob);

    return ary;
}


/**
 * Support Marshal.load.
 *
 * @param ary [Array<String>] the array returned from {Image#marshal_dump}
 * @return self
 */
VALUE
Image_marshal_load(VALUE self, VALUE ary)
{
    VALUE blob, filename;
    Info *info;
    Image *image;
    ExceptionInfo *exception;

    info = CloneImageInfo(NULL);
    if (!info)
    {
        rb_raise(rb_eNoMemError, "not enough memory to initialize Info object");
    }

    filename = rb_ary_shift(ary);
    blob = rb_ary_shift(ary);

    filename = StringValue(filename);
    blob = StringValue(blob);

    exception = AcquireExceptionInfo();
    if (filename != Qnil)
    {
        strlcpy(info->filename, RSTRING_PTR(filename), sizeof(info->filename));
    }
    GVL_STRUCT_TYPE(BlobToImage) args = { info, RSTRING_PTR(blob), (size_t)RSTRING_LEN(blob), exception };
    image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(BlobToImage), &args);

    // Destroy info before raising an exception
    DestroyImageInfo(info);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);

    UPDATE_DATA_PTR(self, image);

    return self;
}

/**
 * Return the image's clip mask, or nil if it doesn't have a clip mask.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - Distinguish from Image#clip_mask
 *
 * @param image the image
 * @return copy of the current clip-mask or nil
 */
static VALUE
get_image_mask(Image *image)
{
    Image *mask;
    ExceptionInfo *exception;

    exception = AcquireExceptionInfo();

    // The returned clip mask is a clone, ours to keep.
#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(GetImageMask) args = { image, WritePixelMask, exception };
    mask = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetImageMask), &args);
#else
    GVL_STRUCT_TYPE(GetImageClipMask) args = { image, exception };
    mask = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetImageClipMask), &args);
#endif
    rm_check_exception(exception, mask, DestroyOnError);

    DestroyExceptionInfo(exception);

    return mask ? rm_image_new(mask) : Qnil;
}

/**
 * Associate a mask with the image.
 *
 * No Ruby usage (internal function)
 *
 * @param image the image
 * @param mask the mask
 * @return copy of the current clip-mask or nil
 * @see get_image_mask
 */
#if defined(IMAGEMAGICK_7)
static VALUE
set_image_mask(Image *image, VALUE mask)
{
    Image *mask_image, *resized_image;
    Image *clip_mask;
    ExceptionInfo *exception;

    exception = AcquireExceptionInfo();

    if (mask != Qnil)
    {
        mask = rm_cur_image(mask);
        mask_image = rm_check_destroyed(mask);
        clip_mask = rm_clone_image(mask_image);

        // Resize if necessary
        if (clip_mask->columns != image->columns || clip_mask->rows != image->rows)
        {
            GVL_STRUCT_TYPE(ResizeImage) args = { clip_mask, image->columns, image->rows, image->filter, exception };
            resized_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ResizeImage), &args);
            DestroyImage(clip_mask);
            rm_check_exception(exception, resized_image, DestroyOnError);
            rm_ensure_result(resized_image);
            clip_mask = resized_image;
        }

        GVL_STRUCT_TYPE(SetImageMask) args = { image, WritePixelMask, clip_mask, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageMask), &args);
        DestroyImage(clip_mask);
    }
    else
    {
        GVL_STRUCT_TYPE(SetImageMask) args = { image, WritePixelMask, NULL, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageMask), &args);
    }
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);

    // Always return a copy of the mask!
    return get_image_mask(image);
}
#else
static VALUE
set_image_mask(Image *image, VALUE mask)
{
    Image *mask_image, *resized_image;
    Image *clip_mask;
    long x, y;
    PixelPacket *q;
    ExceptionInfo *exception;

    if (mask != Qnil)
    {
        mask = rm_cur_image(mask);
        mask_image = rm_check_destroyed(mask);
        clip_mask = rm_clone_image(mask_image);

        // Resize if necessary
        if (clip_mask->columns != image->columns || clip_mask->rows != image->rows)
        {
            exception = AcquireExceptionInfo();
            GVL_STRUCT_TYPE(ResizeImage) args = { clip_mask, image->columns, image->rows, UndefinedFilter, 0.0, exception };
            resized_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ResizeImage), &args);
            rm_check_exception(exception, resized_image, DestroyOnError);
            DestroyExceptionInfo(exception);
            rm_ensure_result(resized_image);
            DestroyImage(clip_mask);
            clip_mask = resized_image;
        }

        // The following section is copied from mogrify.c (6.2.8-8)
        exception = AcquireExceptionInfo();

        for (y = 0; y < (long) clip_mask->rows; y++)
        {
            GVL_STRUCT_TYPE(GetAuthenticPixels) args_GetAuthenticPixels = { clip_mask, 0, y, clip_mask->columns, 1, exception };
            q = (PixelPacket *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetAuthenticPixels), &args_GetAuthenticPixels);
            rm_check_exception(exception, clip_mask, DestroyOnError);

            if (!q)
            {
                break;
            }
            for (x = 0; x < (long) clip_mask->columns; x++)
            {
                if (clip_mask->matte == MagickFalse)
                {
                    q->opacity = PIXEL_INTENSITY(q);
                }
                q->red = q->opacity;
                q->green = q->opacity;
                q->blue = q->opacity;
                q += 1;
            }

            GVL_STRUCT_TYPE(SyncAuthenticPixels) args_SyncAuthenticPixels = { clip_mask, exception };
            CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SyncAuthenticPixels), &args_SyncAuthenticPixels);
            rm_check_exception(exception, clip_mask, DestroyOnError);
        }
        DestroyExceptionInfo(exception);

        GVL_STRUCT_TYPE(SetImageStorageClass) args_SetImageStorageClass = { clip_mask, DirectClass };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageStorageClass), &args_SetImageStorageClass);
        rm_check_image_exception(clip_mask, DestroyOnError);

        clip_mask->matte = MagickTrue;

        // SetImageClipMask clones the clip_mask image. We can
        // destroy our copy after SetImageClipMask is done with it.

        GVL_STRUCT_TYPE(SetImageClipMask) args_SetImageClipMask = { image, clip_mask };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageClipMask), &args_SetImageClipMask);
        DestroyImage(clip_mask);
    }
    else
    {
        GVL_STRUCT_TYPE(SetImageClipMask) args_SetImageClipMask = { image, NULL };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageClipMask), &args_SetImageClipMask);
    }

    RB_GC_GUARD(mask);

    // Always return a copy of the mask!
    return get_image_mask(image);
}
#endif


/**
 * Get/Sets an image clip mask created from the specified mask image.
 * The mask image must have the same dimensions as the image being masked.
 * If not, the mask image is resized to match. If the mask image has an alpha channel the opacity of
 * each pixel is used to define the mask. Otherwise, the intensity (gray level) of each pixel is
 * used.
 *
 * In general, if the mask image does not have an alpha channel, a white pixel in the mask prevents
 * changes to the corresponding pixel in the image being masked, while a black pixel allows changes.
 * A pixel that is neither black nor white will allow partial changes depending on its intensity.
 *
 * @overload mask()
 *   Get an image clip mask.
 *
 * @overload mask(image)
 *   Set an image clip mask.
 *   @param image [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *
 * @return [Magick::Image, nil] the mask image
 */
VALUE
Image_mask(int argc, VALUE *argv, VALUE self)
{
    VALUE mask;
    Image *image;

    image = rm_check_destroyed(self);
    if (argc == 0)
    {
        return get_image_mask(image);
    }
    if (argc > 1)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (expected 0 or 1, got %d)", argc);
    }

    rb_check_frozen(self);
    mask = argv[0];
    return set_image_mask(image, mask);
}


/**
 * Return the matte color.
 *
 * @return [String] the matte color
 */
VALUE
Image_matte_color(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return rm_pixelcolor_to_color_name(image, &image->matte_color);
}

/**
 * Set the matte color.
 *
 * @param color [Magick::Pixel, String] the matte color
 * @return [Magick::Pixel, String] the given color
 */
VALUE
Image_matte_color_eq(VALUE self, VALUE color)
{
    Image *image = rm_check_frozen(self);
    Color_to_PixelColor(&image->matte_color, color);
    return color;
}


/**
 * Makes transparent all the pixels that are the same color as the pixel at x, y, and are neighbors.
 *
 * @overload Image#matte_flood_fill(color, x, y, method_obj, alpha:)
 *   @param color [Magick::Pixel, String] the color name
 *   @param x_obj [Numeric] x position
 *   @param y_obj [Numeric] y position
 *   @param method_obj [Magick::PaintMethod] which method to call: FloodfillMethod or FillToBorderMethod
 *   @param alpha [Numeric] the alpha
 *   @return [Magick::Image] a new image
 */
VALUE
Image_matte_flood_fill(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    PixelColor target;
    Quantum alpha;
    long x, y;
    PaintMethod method;
    DrawInfo *draw_info;
    MagickPixel target_mpp;
    MagickBooleanType invert;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

    if (argc != 5)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 5)", argc);
    }

    alpha = get_named_alpha_value(argv[4]);

    Color_to_PixelColor(&target, argv[0]);
    VALUE_TO_ENUM(argv[3], method, PaintMethod);
    if (!(method == FloodfillMethod || method == FillToBorderMethod))
    {
        rb_raise(rb_eArgError, "paint method_obj must be FloodfillMethod or "
                 "FillToBorderMethod (%d given)", method);
    }
    x = NUM2LONG(argv[1]);
    y = NUM2LONG(argv[2]);
    if ((unsigned long)x > image->columns || (unsigned long)y > image->rows)
    {
        rb_raise(rb_eArgError, "target out of range. %ldx%ld given, image is %" RMIuSIZE "x%" RMIuSIZE "",
                 x, y, image->columns, image->rows);
    }


    new_image = rm_clone_image(image);

    // FloodfillPaintImage looks for the opacity in the DrawInfo.fill field.
    draw_info = CloneDrawInfo(NULL, NULL);
    if (!draw_info)
    {
        rb_raise(rb_eNoMemError, "not enough memory to continue");
    }
#if defined(IMAGEMAGICK_7)
    rm_set_pixelinfo_alpha(&draw_info->fill, alpha);
#else
    draw_info->fill.opacity = QuantumRange - alpha;
#endif

    if (method == FillToBorderMethod)
    {
        invert = MagickTrue;
        target_mpp.red   = (MagickRealType) image->border_color.red;
        target_mpp.green = (MagickRealType) image->border_color.green;
        target_mpp.blue  = (MagickRealType) image->border_color.blue;
#if defined(IMAGEMAGICK_7)
        rm_set_pixelinfo_alpha(&target_mpp, (MagickRealType) image->border_color.alpha);
#else
        target_mpp.opacity = (MagickRealType) image->border_color.opacity;
#endif
    }
    else
    {
        invert = MagickFalse;
        target_mpp.red   = (MagickRealType) target.red;
        target_mpp.green = (MagickRealType) target.green;
        target_mpp.blue  = (MagickRealType) target.blue;
#if defined(IMAGEMAGICK_7)
        rm_set_pixelinfo_alpha(&target_mpp, (MagickRealType) target.alpha);
#else
        target_mpp.opacity = (MagickRealType) target.opacity;
#endif
    }

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(new_image, OpacityChannel);
    GVL_STRUCT_TYPE(FloodfillPaintImage) args = { new_image, draw_info, &target_mpp, x, y, invert, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(FloodfillPaintImage), &args);
    END_CHANNEL_MASK(new_image);
    DestroyDrawInfo(draw_info);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(FloodfillPaintImage) args = { new_image, OpacityChannel, draw_info, &target_mpp, x, y, invert };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(FloodfillPaintImage), &args);
    DestroyDrawInfo(draw_info);

    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Apply a digital filter that improves the quality of a noisy image. Each pixel is replaced by the
 * median in a set of neighboring pixels as defined by radius.
 *
 * @overload median_filter(radius = 0.0)
 *   @param radius [Numeric] The filter radius.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_median_filter(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double radius = 0.0;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 1:
            radius = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 or 1)", argc);
            break;
    }

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(StatisticImage) args = { image, MedianStatistic, (size_t)radius, (size_t)radius, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(StatisticImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Get the mean error per pixel computed when a image is color reduced.
 *
 * @return [Float] the mean error per pixel
 */
VALUE
Image_mean_error_per_pixel(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READERF(Image, mean_error_per_pixel, error.mean_error_per_pixel, dbl, &rm_image_data_type);
}


/**
 * Return the officially registered (or de facto) MIME media-type corresponding to the image format.
 *
 * @return [String, nil] the mime type
 */
VALUE
Image_mime_type(VALUE self)
{
    Image *image;
    char *type;
    VALUE mime_type;

    image = rm_check_destroyed(self);
    type = MagickToMime(image->magick);
    if (!type)
    {
        return Qnil;
    }
    mime_type = rb_str_new2(type);

    // The returned string must be deallocated by the user.
    magick_free(type);

    RB_GC_GUARD(mime_type);

    return mime_type;
}


/**
 * Scale an image proportionally to half its size.
 *
 * @return [Magick::Image] a new image
 * @see Image#minify!
 */
VALUE
Image_minify(VALUE self)
{
    rm_check_destroyed(self);
    return magnify(False, self, GVL_FUNC(MinifyImage));
}


/**
 * Scale an image proportionally to half its size.  In-place form of {Image#minify}.
 *
 * @return [Magick::Image] self
 * @see Image#minify
 */
VALUE
Image_minify_bang(VALUE self)
{
    rm_check_frozen(self);
    return magnify(True, self, GVL_FUNC(MinifyImage));
}


/**
 * Changes the brightness, saturation, and hue.
 *
 * @overload modulate(brightness = 1.0, saturation = 1.0, hue = 1.0)
 *   @param brightness [Numeric, String] The percent change in the brightness.
 *     Must be a non-negative number or a string in the form "NN%".
 *   @param saturation [Numeric, String] The percent change in the saturation.
 *     Must be a number or a string in the form "NN%".
 *   @param hue [Numeric, String] The percent change in the hue.
 *     Must be a number or a string in the form "NN%".
 *   @return [Magick::Image] a new image
 */
VALUE
Image_modulate(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double pct_brightness = 100.0,
    pct_saturation = 100.0,
    pct_hue        = 100.0;
    char modulate[100];
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 3:
            pct_hue        = rm_percentage2(argv[2], 1.0, false) * 100.0;
        case 2:
            pct_saturation = rm_percentage2(argv[1], 1.0, false) * 100.0;
        case 1:
            pct_brightness = rm_percentage(argv[0], 1.0) * 100.0;
            break;
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 3)", argc);
            break;
    }

    if (pct_brightness <= 0.0)
    {
        rb_raise(rb_eArgError, "brightness is %g%%, must be positive", pct_brightness);
    }
    snprintf(modulate, sizeof(modulate), "%f%%,%f%%,%f%%", pct_brightness, pct_saturation, pct_hue);

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(ModulateImage) args = { new_image, modulate, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ModulateImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(ModulateImage) args = { new_image, modulate };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ModulateImage), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Return true if all the pixels in the image have the same red, green, and blue intensities and the
 * intensity is either 0 or {Magick::QuantumRange}.
 *
 * @return [Boolean] true if monochrome, false otherwise
 */
VALUE
Image_monochrome_q(VALUE self)
{
#if defined(IMAGEMAGICK_7)
    return has_image_attribute(self, IsImageMonochrome);
#else
    return has_attribute(self, IsMonochromeImage);
#endif
}


/**
 * Tile size and offset within an image montage. Only valid for montage images.
 *
 * @return [String, nil] the tile size and offset
 */
VALUE
Image_montage(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, montage, str, &rm_image_data_type);
}


// aliases for common use of structure types; MotionBlurImage, SketchImage
typedef GVL_STRUCT_TYPE(MotionBlurImage) GVL_STRUCT_TYPE(motion_blur);

/**
 * Called from Image_motion_blur and Image_sketch.
 *
 * No Ruby usage (internal function)
 *
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @param fp the blur function to call
 * @return a new image
 * @see Image_motion_blur
 * @see Image_sketch
 */
static VALUE
motion_blur(int argc, VALUE *argv, VALUE self, gvl_function_t fp)
{
    Image *image, *new_image;
    double radius = 0.0;
    double sigma = 1.0;
    double angle = 0.0;
    ExceptionInfo *exception;

    switch (argc)
    {
        case 3:
            angle = NUM2DBL(argv[2]);
        case 2:
            sigma = NUM2DBL(argv[1]);
        case 1:
            radius = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 3)", argc);
            break;
    }

    if (sigma == 0.0)
    {
        rb_raise(rb_eArgError, "sigma must be != 0.0");
    }

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(motion_blur) args = { image, radius, sigma, angle, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(fp, &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Simulate motion blur. Convolve the image with a Gaussian operator of the given radius and
 * standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a
 * radius of 0 and motion_blur selects a suitable radius for you. Angle gives the angle of the
 * blurring motion.
 *
 * @overload motion_blur(radius = 0.0, sigma = 1.0, angle = 0.0)
 *   @param radius [Numeric] The radius
 *   @param sigma [Numeric] The standard deviation
 *   @param angle [Numeric] The angle (in degrees)
 *   @return [Magick::Image] a new image
 */
VALUE
Image_motion_blur(int argc, VALUE *argv, VALUE self)
{
    rm_check_destroyed(self);
    return motion_blur(argc, argv, self, GVL_FUNC(MotionBlurImage));
}


/**
 * Negate the colors in the reference image. The grayscale option means that only grayscale values
 * within the image are negated.
 *
 * @overload negate(grayscale = false)
 *   @param grayscale [Boolean] If the grayscale argument is true, only the grayscale values are negated.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_negate(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    MagickBooleanType grayscale = MagickFalse;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    if (argc == 1)
    {
        grayscale = (MagickBooleanType)RTEST(argv[0]);
    }
    else if (argc > 1)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 or 1)", argc);
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(NegateImage) args = { new_image, grayscale, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(NegateImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(NegateImage) args = { new_image, grayscale };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(NegateImage), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Negate the colors on a particular channel. The grayscale option means that
 * only grayscale values within the image are negated.
 *
 * @overload negate_channel(grayscale = false, channel = Magick::AllChannels)
 *   @param grayscale [Boolean] If the grayscale argument is true, only the grayscale values are
 *     negated.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload negate_channel(grayscale = false, *channels)
 *   @param grayscale [Boolean] If the grayscale argument is true, only the grayscale values are
 *     negated.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_negate_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ChannelType channels;
    MagickBooleanType grayscale = MagickFalse;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    // There can be at most 1 remaining argument.
    if (argc > 1)
    {
        raise_ChannelType_error(argv[argc-1]);
    }
    else if (argc == 1)
    {
        grayscale = (MagickBooleanType)RTEST(argv[0]);
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(new_image, channels);
    GVL_STRUCT_TYPE(NegateImage) args = { new_image, grayscale, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(NegateImage), &args);
    END_CHANNEL_MASK(new_image);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(NegateImageChannel) args = { new_image, channels, grayscale };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(NegateImageChannel), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * "Allocate" a new Image object
 *
 * @return [Magick::Image] a newly allocated image
 */
VALUE
Image_alloc(VALUE klass)
{
    VALUE image_obj;

    image_obj = TypedData_Wrap_Struct(klass, &rm_image_data_type, NULL);

    RB_GC_GUARD(image_obj);

    return image_obj;
}

/**
 * Initialize a new Image object If the fill argument is omitted, fill with background color.
 *
 * @overload initialize(cols, rows, fill = nil)
 *   @param cols [Numeric] the image width
 *   @param rows [Numeric] the image height
 *   @param fill [Magick::HatchFill, Magick::SolidFill] if object is given as fill argument,
 *     background color will be filled using it.
 *   @return [Magick::Image] self
 */
VALUE
Image_initialize(int argc, VALUE *argv, VALUE self)
{
    VALUE fill = Qnil;
    Info *info;
    VALUE info_obj;
    Image *image;
    unsigned long cols, rows;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    switch (argc)
    {
        case 3:
            fill = argv[2];
        case 2:
            rows = NUM2ULONG(argv[1]);
            cols = NUM2ULONG(argv[0]);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 or 3)", argc);
            break;
    }

    // Create a new Info object to use when creating this image.
    info_obj = rm_info_new();
    TypedData_Get_Struct(info_obj, Info, &rm_info_data_type, info);

    image = rm_acquire_image(info);
    if (!image)
    {
        rb_raise(rb_eNoMemError, "not enough memory to continue");
    }

    rm_set_user_artifact(image, info);

    // NOW store a real image in the image object.
    UPDATE_DATA_PTR(self, image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(SetImageExtent) args = { image, cols, rows, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageExtent), &args);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(SetImageExtent) args = { image, cols, rows };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageExtent), &args);
#endif

    rm_sync_image_options(image, info);

    // If the caller did not supply a fill argument, call SetImageBackgroundColor
    // to fill the image using the background color. The background color can
    // be set by specifying it when creating the Info parm block.
    if (NIL_P(fill))
    {
#if defined(IMAGEMAGICK_7)
        exception = AcquireExceptionInfo();
        GVL_STRUCT_TYPE(SetImageBackgroundColor) args = { image, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageBackgroundColor), &args);
        CHECK_EXCEPTION();
        DestroyExceptionInfo(exception);
#else
        GVL_STRUCT_TYPE(SetImageBackgroundColor) args = { image };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageBackgroundColor), &args);
#endif
    }
    // fillobj.fill(self)
    else
    {
        rb_funcall(fill, rm_ID_fill, 1, self);
    }

    RB_GC_GUARD(fill);
    RB_GC_GUARD(info_obj);

    return self;
}


/**
 * Create a new Image object from an Image structure.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - Since the Image is already created we don't need to call Image_alloc or
 *     Image_initialize.
 *
 * @param image the Image structure
 * @return a new image
 */
VALUE
rm_image_new(Image *image)
{
    rm_ensure_result(image);

    return TypedData_Wrap_Struct(Class_Image, &rm_image_data_type, image);
}


/**
 * Enhance the contrast of a color image by adjusting the pixels color to span the entire range of
 * colors available.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_normalize(VALUE self)
{
    Image *image, *new_image;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(NormalizeImage) args = { new_image, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(NormalizeImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(NormalizeImage) args = { new_image };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(NormalizeImage), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Enhances the contrast of a color image by adjusting the pixel color to span the entire range of
 * colors available. Only the specified channels are normalized.
 *
 * @overload normalize_channel(channel = Magick::AllChannels)
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload normalize_channel(*channels)
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_normalize_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ChannelType channels;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);
    // Ensure all arguments consumed.
    if (argc > 0)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(new_image, channels);
    GVL_STRUCT_TYPE(NormalizeImage) args = { new_image, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(NormalizeImage), &args);
    END_CHANNEL_MASK(new_image);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(NormalizeImageChannel) args = { new_image, channels };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(NormalizeImageChannel), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Get the normalized mean error per pixel computed when an image is color reduced.
 *
 * @return [Float] the normalized mean error
 */
VALUE
Image_normalized_mean_error(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READERF(Image, normalized_mean_error, error.normalized_mean_error, dbl, &rm_image_data_type);
}

/**
 * Get The normalized maximum error per pixel computed when an image is color reduced.
 *
 * @return [Float] the normalized maximum error
 */
VALUE
Image_normalized_maximum_error(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READERF(Image, normalized_maximum_error, error.normalized_maximum_error, dbl, &rm_image_data_type);
}


/**
 * Return the number of unique colors in the image.
 *
 * @return [Integer] number of unique colors
 */
VALUE
Image_number_colors(VALUE self)
{
    Image *image;
    ExceptionInfo *exception;
    size_t n = 0;

    image = rm_check_destroyed(self);
    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(GetNumberColors) args = { image, NULL, exception };
    n = (size_t)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetNumberColors), &args);
    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    return ULONG2NUM(n);
}


/**
 * Get the number of bytes to skip over when reading raw image.
 *
 * @return [Integer] the offset
 */
VALUE
Image_offset(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, offset, long, &rm_image_data_type);
}

/**
 * Set the number of bytes to skip over when reading raw image.
 *
 * @param val [Numeric] the offset
 * @return [Numeric] the given offset
 */
VALUE
Image_offset_eq(VALUE self, VALUE val)
{
    IMPLEMENT_TYPED_ATTR_WRITER(Image, offset, long, &rm_image_data_type);
}


/**
 * Apply a special effect filter that simulates an oil painting.
 *
 * @overload oil_paint(radius = 3.0)
 *   @param radius [Numeric] The radius of the Gaussian in pixels.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_oil_paint(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double radius = 3.0;
    ExceptionInfo *exception;
#if defined(IMAGEMAGICK_7)
    double sigma = 1.0;
#endif

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 1:
            radius = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 or 1)", argc);
            break;
    }

    exception = AcquireExceptionInfo();

#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(OilPaintImage) args = { image, radius, sigma, exception };
#else
    GVL_STRUCT_TYPE(OilPaintImage) args = { image, radius, exception };
#endif
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(OilPaintImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Change any pixel that matches target with the color defined by fill.
 *
 *  - By default a pixel must match the specified target color exactly.
 *  - Use {Image#fuzz=} to set the amount of tolerance acceptable to consider two colors as the
 *    same.
 *
 * @param target [Magick::Pixel, String] the color name
 * @param fill [Magick::Pixel, String] the color for filling
 * @return [Magick::Image] a new image
 * @see Image#fuzz=
 */
VALUE
Image_opaque(VALUE self, VALUE target, VALUE fill)
{
    Image *image, *new_image;
    MagickPixel target_pp;
    MagickPixel fill_pp;
    MagickBooleanType okay;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

    // Allow color name or Pixel
    Color_to_MagickPixel(image, &target_pp, target);
    Color_to_MagickPixel(image, &fill_pp, fill);

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(OpaquePaintImage) args = { new_image, &target_pp, &fill_pp, MagickFalse, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(OpaquePaintImage), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(OpaquePaintImageChannel) args = { new_image, DefaultChannels, &target_pp, &fill_pp, MagickFalse };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(OpaquePaintImageChannel), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    if (!okay)
    {
        // Force exception
        DestroyImage(new_image);
        rm_ensure_result(NULL);
    }

    return rm_image_new(new_image);
}


/**
 * Changes all pixels having the target color to the fill color.
 * If invert is true, changes all the pixels that are not the target color to the fill color.
 *
 * @overload opaque_channel(target, fill, invert = false, fuzz = self.fuzz, channel = Magick::AllChannels)
 *   @param target [Magick::Pixel, String] the color name
 *   @param fill [Magick::Pixel, String] the color for filling
 *   @param invert [Boolean] If true, the target pixels are all the pixels that are not the target
 *     color. The default is the value of the target image's fuzz attribute
 *   @param fuzz [Numeric] Colors within this distance are considered equal to the target color.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload opaque_channel(target, fill, invert, fuzz, *channels)
 *   @param target [Magick::Pixel, String] the color name
 *   @param fill [Magick::Pixel, String] the color for filling
 *   @param invert [Boolean] If true, the target pixels are all the pixels that are not the target
 *     color. The default is the value of the target image's fuzz attribute
 *   @param fuzz [Numeric] Colors within this distance are considered equal to the target color.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_opaque_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    MagickPixel target_pp, fill_pp;
    ChannelType channels;
    double keep, fuzz;
    MagickBooleanType okay, invert = MagickFalse;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);
    if (argc > 4)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    // Default fuzz value is image's fuzz attribute.
    fuzz = image->fuzz;

    switch (argc)
    {
        case 4:
            fuzz = NUM2DBL(argv[3]);
            if (fuzz < 0.0)
            {
                rb_raise(rb_eArgError, "fuzz must be >= 0.0 (%g given)", fuzz);
            }
        case 3:
            invert = (MagickBooleanType)RTEST(argv[2]);
        case 2:
            // Allow color name or Pixel
            Color_to_MagickPixel(image, &fill_pp, argv[1]);
            Color_to_MagickPixel(image, &target_pp, argv[0]);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (got %d, expected 2 or more)", argc);
            break;
    }

    new_image = rm_clone_image(image);
    keep = new_image->fuzz;
    new_image->fuzz = fuzz;

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(new_image, channels);
    GVL_STRUCT_TYPE(OpaquePaintImage) args = { new_image, &target_pp, &fill_pp, invert, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(OpaquePaintImage), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    END_CHANNEL_MASK(new_image);
    new_image->fuzz = keep;
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(OpaquePaintImageChannel) args = { new_image, channels, &target_pp, &fill_pp, invert };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(OpaquePaintImageChannel), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));

    new_image->fuzz = keep;
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    if (!okay)
    {
        // Force exception
        DestroyImage(new_image);
        rm_ensure_result(NULL);
    }

    return rm_image_new(new_image);
}


/**
 * Returns true if all of the pixels in the receiver have an opacity value of OpaqueOpacity.
 *
 * @return [Boolean] true if opaque, false otherwise
 */
VALUE
Image_opaque_q(VALUE self)
{
#if defined(IMAGEMAGICK_7)
    return has_attribute(self, IsImageOpaque);
#else
    return has_attribute(self, IsOpaqueImage);
#endif
}


/**
 * Dithers the image to a predefined pattern. The threshold_map argument defines the pattern to use.
 *
 * - Default threshold_map is '2x2'
 * - Order of threshold_map must be 2, 3, or 4.
 *
 * @overload ordered_dither(threshold_map = '2x2')
 *   @param threshold_map [String, Numeric] the threshold
 *   @return [Magick::Image] a new image
 */
VALUE
Image_ordered_dither(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    int order;
    const char *threshold_map = "2x2";
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    if (argc > 1)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 or 1)", argc);
    }
    if (argc == 1)
    {
        if (TYPE(argv[0]) == T_STRING)
        {
            threshold_map = StringValueCStr(argv[0]);
        }
        else
        {
            order = NUM2INT(argv[0]);
            if (order == 3)
            {
                threshold_map = "3x3";
            }
            else if (order == 4)
            {
                threshold_map = "4x4";
            }
            else if (order != 2)
            {
                rb_raise(rb_eArgError, "order must be 2, 3, or 4 (%d given)", order);
            }
        }
    }

    new_image = rm_clone_image(image);

    exception = AcquireExceptionInfo();

#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(OrderedDitherImage) args = { new_image, threshold_map, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(OrderedDitherImage), &args);
#else
    GVL_STRUCT_TYPE(OrderedPosterizeImage) args = { new_image, threshold_map, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(OrderedPosterizeImage), &args);
#endif
    rm_check_exception(exception, new_image, DestroyOnError);

    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Get the value of the Exif Orientation Tag.
 *
 * @return [Magick::OrientationType] the orientation
 */
VALUE
Image_orientation(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return OrientationType_find(image->orientation);
}


/**
 * Set the orientation attribute.
 *
 * @param orientation [Magick::OrientationType] the orientation
 * @return [Magick::OrientationType] the given value
 */
VALUE
Image_orientation_eq(VALUE self, VALUE orientation)
{
    Image *image = rm_check_frozen(self);
    VALUE_TO_ENUM(orientation, image->orientation, OrientationType);
    return orientation;
}


/**
 * The page attribute getter.
 *
 * @return [Magick::Rectangle] the page rectangle
 */
VALUE
Image_page(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return Import_RectangleInfo(&image->page);
}


/**
 * The page attribute setter.
 *
 * @param rect [Magick::Rectangle] the page rectangle
 * @return [Magick::Rectangle] the given value
 */
VALUE
Image_page_eq(VALUE self, VALUE rect)
{
    Image *image = rm_check_frozen(self);
    Export_RectangleInfo(&image->page, rect);
    return rect;
}


/**
 * Changes the opacity value of all the pixels that match color to the value specified by opacity.
 * If invert is true, changes the pixels that don't match color.
 *
 * @overload paint_transparent(color, invert, fuzz, alpha: Magick::TransparentAlpha)
 *   @param color [Magick::Pixel, String] the color name
 *   @param invert [Boolean] If true, the target pixels are all the pixels that are not the target
 *     color.
 *   @param fuzz [Numeric] By default the pixel must match exactly, but you can specify a tolerance
 *     level by passing a positive value.
 *   @param alpha [Numeric] The new alpha value, either an alpha value or a number between 0 and
 *     QuantumRange. The default is TransparentAlpha.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_paint_transparent(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    MagickPixel color;
    Quantum alpha = TransparentAlpha;
    double keep, fuzz;
    MagickBooleanType okay, invert;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

    // Default fuzz value is image's fuzz attribute.
    fuzz = image->fuzz;
    invert = MagickFalse;

    switch (argc)
    {
        case 4:
            if (TYPE(argv[argc - 1]) == T_HASH)
            {
                fuzz = NUM2DBL(argv[2]);
            }
            else
            {
                fuzz = NUM2DBL(argv[3]);
            }
        case 3:
            if (TYPE(argv[argc - 1]) == T_HASH)
            {
                invert = (MagickBooleanType)RTEST(argv[1]);
            }
            else
            {
                invert = (MagickBooleanType)RTEST(argv[2]);
            }
        case 2:
            alpha = get_named_alpha_value(argv[argc - 1]);
        case 1:
            Color_to_MagickPixel(image, &color, argv[0]);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 to 4)", argc);
            break;
    }

    new_image = rm_clone_image(image);

    // Use fuzz value from caller
    keep = new_image->fuzz;
    new_image->fuzz = fuzz;

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(TransparentPaintImage) args = { new_image, (const MagickPixel *)&color, alpha, invert, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(TransparentPaintImage), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    new_image->fuzz = keep;
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(TransparentPaintImage) args = { new_image, (const MagickPixel *)&color, (Quantum)(QuantumRange - alpha), invert };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(TransparentPaintImage), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    new_image->fuzz = keep;

    // Is it possible for TransparentPaintImage to silently fail?
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    if (!okay)
    {
        // Force exception
        DestroyImage(new_image);
        rm_ensure_result(NULL);
    }

    return rm_image_new(new_image);
}


/**
 * Return true if the image is PseudoClass and has 256 unique colors or less.
 *
 * @return [Boolean] true if palette, otherwise false
 */
VALUE
Image_palette_q(VALUE self)
{
#if defined(IMAGEMAGICK_7)
    return has_image_attribute(self, IsPaletteImage);
#else
    return has_attribute(self, IsPaletteImage);
#endif
}


/**
 * Returns all the properties of an image or image sequence except for the pixels.
 *
 * @param file_arg [File, String] the file containing image data or file name
 * @yield [info]
 * @yieldparam info [Magick::Image::Info]
 * @return [Array<Magick::Image>] an array of 1 or more new image objects (without pixel data)
 * @see Image#read
 */
VALUE
Image_ping(VALUE klass, VALUE file_arg)
{
    return rd_image(klass, file_arg, GVL_FUNC(PingImage));
}


/**
 * Get/set the color of the pixel at x, y.
 *
 * @overload pixel_color(x, y)
 *   Get the color
 *   @param x [Numeric] The x-coordinates of the pixel.
 *   @param y [Numeric] The y-coordinates of the pixel.
 *   @return [Magick::Pixel] the pixel at x, y.
 *
 * @overload pixel_color(x, y, color)
 *   Set the color
 *   @param x [Numeric] The x-coordinates of the pixel.
 *   @param y [Numeric] The y-coordinates of the pixel.
 *   @param color [Magick::Pixel, String] the color
 *   @return [Magick::Pixel] the old color at x, y.
 */
VALUE
Image_pixel_color(int argc, VALUE *argv, VALUE self)
{
    Image *image;
    Pixel new_color;
    PixelPacket old_color;
    ExceptionInfo *exception;
    long x, y;
    unsigned int set = False;
    MagickBooleanType okay;
#if defined(IMAGEMAGICK_7)
    Quantum *pixel;
    const Quantum *old_pixel;
#else
    PixelPacket *pixel;
    const PixelPacket *old_pixel;
    MagickPixel mpp;
    IndexPacket *indexes;
#endif

    memset(&old_color, 0, sizeof(old_color));

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 3:
            rb_check_frozen(self);
            set = True;
            // Replace with new color? The arg can be either a color name or
            // a Magick::Pixel.
            Color_to_Pixel(&new_color, argv[2]);
        case 2:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 or 3)", argc);
            break;
    }

    x = NUM2LONG(argv[0]);
    y = NUM2LONG(argv[1]);

    // Get the color of a pixel
    if (!set)
    {
        exception = AcquireExceptionInfo();
        GVL_STRUCT_TYPE(GetVirtualPixels) args = { image, x, y, 1, 1, exception };
        void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetVirtualPixels), &args);
        old_pixel = reinterpret_cast<decltype(old_pixel)>(ret);
        CHECK_EXCEPTION();

        DestroyExceptionInfo(exception);

#if defined(IMAGEMAGICK_7)
        old_color.red   = GetPixelRed(image, old_pixel) + 0.5;
        old_color.green = GetPixelGreen(image, old_pixel) + 0.5;
        old_color.blue  = GetPixelBlue(image, old_pixel) + 0.5;
        old_color.alpha = GetPixelAlpha(image, old_pixel) + 0.5;
        old_color.black = GetPixelBlack(image, old_pixel) + 0.5;
        return Pixel_from_PixelPacket(&old_color);
#else
        old_color = *old_pixel;
        indexes = GetAuthenticIndexQueue(image);
        // PseudoClass
        if (image->storage_class == PseudoClass)
        {
            old_color = image->colormap[(unsigned long)*indexes];
        }
        if (!image->matte)
        {
            old_color.opacity = OpaqueOpacity;
        }

        rm_init_magickpixel(image, &mpp);
        mpp.red = GetPixelRed(&old_color);
        mpp.green = GetPixelGreen(&old_color);
        mpp.blue = GetPixelBlue(&old_color);
        mpp.opacity = GetPixelOpacity(&old_color);
        if (indexes)
        {
            mpp.index = GetPixelIndex(indexes);
        }
        return Pixel_from_MagickPixel(&mpp);
#endif
    }

    // ImageMagick segfaults if the pixel location is out of bounds.
    // Do what IM does and return the background color.
    if (x < 0 || y < 0 || (unsigned long)x >= image->columns || (unsigned long)y >= image->rows)
    {
        return Pixel_from_PixelColor(&image->background_color);
    }

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
#endif

    if (image->storage_class == PseudoClass)
    {
#if defined(IMAGEMAGICK_7)
        GVL_STRUCT_TYPE(SetImageStorageClass) args = { image, DirectClass, exception };
        void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageStorageClass), &args);
        okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
        CHECK_EXCEPTION();
        if (!okay)
        {
            DestroyExceptionInfo(exception);
            rb_raise(Class_ImageMagickError, "SetImageStorageClass failed. Can't set pixel color.");
        }
#else
        GVL_STRUCT_TYPE(SetImageStorageClass) args = { image, DirectClass };
        void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageStorageClass), &args);
        okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
        rm_check_image_exception(image, RetainOnError);
        if (!okay)
        {
            rb_raise(Class_ImageMagickError, "SetImageStorageClass failed. Can't set pixel color.");
        }
#endif
    }

#if defined(IMAGEMAGICK_6)
    exception = AcquireExceptionInfo();
#endif

    GVL_STRUCT_TYPE(GetAuthenticPixels) args = { image, x, y, 1, 1, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetAuthenticPixels), &args);
    pixel = reinterpret_cast<decltype(pixel)>(ret);
    CHECK_EXCEPTION();

    if (pixel)
    {
#if defined(IMAGEMAGICK_7)
        old_color.red   = GetPixelRed(image, pixel) + 0.5;
        old_color.green = GetPixelGreen(image, pixel) + 0.5;
        old_color.blue  = GetPixelBlue(image, pixel) + 0.5;
        old_color.alpha = GetPixelAlpha(image, pixel) + 0.5;
        old_color.black = GetPixelBlack(image, pixel) + 0.5;

        SetPixelRed(image,   new_color.red,   pixel);
        SetPixelGreen(image, new_color.green, pixel);
        SetPixelBlue(image,  new_color.blue,  pixel);
        SetPixelAlpha(image, new_color.alpha, pixel);
        SetPixelBlack(image, new_color.black, pixel);
#else
        old_color = *pixel;
        indexes = GetAuthenticIndexQueue(image);
        if (!image->matte)
        {
            old_color.opacity = OpaqueOpacity;
        }

        SetPixelRed(pixel,     new_color.red);
        SetPixelGreen(pixel,   new_color.green);
        SetPixelBlue(pixel,    new_color.blue);
        SetPixelOpacity(pixel, new_color.opacity);
        if (indexes)
        {
            SetPixelIndex(indexes, new_color.black);
        }
#endif

        GVL_STRUCT_TYPE(SyncAuthenticPixels) args = { image, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SyncAuthenticPixels), &args);
        CHECK_EXCEPTION();
    }

    DestroyExceptionInfo(exception);

    return Pixel_from_PixelPacket(&old_color);
}


/**
 * Get the "interpolate" field.
 *
 * @return [Magick::PixelInterpolateMethod] the interpolate field
 * @see Image#pixel_interpolation_method=
 */
VALUE
Image_pixel_interpolation_method(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return PixelInterpolateMethod_find(image->interpolate);
}


/**
 * Set the "interpolate" field.
 *
 * @param method [Magick::PixelInterpolateMethod] the interpolate field
 * @return [Magick::PixelInterpolateMethod] the given method
 * @see Image#pixel_interpolation_method
 */
VALUE
Image_pixel_interpolation_method_eq(VALUE self, VALUE method)
{
    Image *image = rm_check_frozen(self);
    VALUE_TO_ENUM(method, image->interpolate, PixelInterpolateMethod);
    return method;
}


/**
 * Produce an image that looks like a Polaroid instant picture. If the image has a "Caption"
 * property, the value is used as a caption.
 *
 * The following annotate attributes control the label rendering:
 * align, decorate, density, encoding, fill, font, font_family, font_stretch, font_style,
 * font_weight, gravity, pointsize, stroke, stroke_width, text_antialias, undercolor.
 *
 * @overload polaroid(angle = -5.0)
 *   @param angle [Numeric] The resulting image is rotated by this amount, measured in degrees.
 *
 * @overload polaroid(angle = -5.0)
 *   If present a block, optional arguments may be specified in a block associated with the method.
 *   These arguments control the shadow color and how the label is rendered.
 *   By default the shadow color is gray75. To specify a different shadow color,
 *   use options.shadow_color.
 *   To specify a different border color (that is, the color of the image border) use options.border_color.
 *   Both of these methods accept either a color name or a Pixel argument.
 *   @param angle [Numeric] The resulting image is rotated by this amount, measured in degrees.
 *   @yield [opt]
 *   @yieldparam opt [Magick::Image::PolaroidOptions]
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_polaroid(int argc, VALUE *argv, VALUE self)
{
    Image *image, *clone, *new_image;
    VALUE options;
    double angle = -5.0;
    Draw *draw;
    ExceptionInfo *exception;
#if defined(IMAGEMAGICK_7)
    const char *caption;
#endif

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 1:
            angle = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 or 1)", argc);
            break;
    }

    options = rm_polaroid_new();
    TypedData_Get_Struct(options, Draw, &rm_draw_data_type, draw);

    clone = rm_clone_image(image);
    clone->background_color = draw->shadow_color;
    clone->border_color = draw->info->border_color;

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    caption = GetImageProperty(clone, "Caption", exception);
    GVL_STRUCT_TYPE(PolaroidImage) args = { clone, draw->info, caption, angle, image->interpolate, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(PolaroidImage), &args);
#else
    GVL_STRUCT_TYPE(PolaroidImage) args = { clone, draw->info, angle, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(PolaroidImage), &args);
#endif
    rm_check_exception(exception, clone, DestroyOnError);

    DestroyImage(clone);
    DestroyExceptionInfo(exception);

    RB_GC_GUARD(options);

    return rm_image_new(new_image);
}


/**
 * Reduces the image to a limited number of colors for a "poster" effect.
 *
 * @overload posterize(levels = 4, dither = false)
 *   @param levels [Numeric] number of input arguments
 *   @param dither [Boolean] array of input arguments
 *   @return a new image
 */
VALUE
Image_posterize(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    MagickBooleanType dither = MagickFalse;
    unsigned long levels = 4;
#if defined(IMAGEMAGICK_7)
    DitherMethod dither_method;
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 2:
            dither = (MagickBooleanType) RTEST(argv[1]);
            /* fall through */
        case 1:
            levels = NUM2ULONG(argv[0]);
            /* fall through */
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 2)", argc);
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    dither_method = dither ? RiemersmaDitherMethod : NoDitherMethod;
    GVL_STRUCT_TYPE(PosterizeImage) args = { new_image, levels, dither_method, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(PosterizeImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(PosterizeImage) args = { new_image, levels, dither };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(PosterizeImage), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Creates an image that contains 9 small versions of the receiver image. The center image is the
 * unchanged receiver. The other 8 images are variations created by transforming the receiver
 * according to the specified preview type with varying parameters.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_preview(VALUE self, VALUE preview)
{
    Image *image, *new_image;
    PreviewType preview_type;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    VALUE_TO_ENUM(preview, preview_type, PreviewType);

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(PreviewImage) args = { image, preview_type, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(PreviewImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);

    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Set the image profile. If "profile" is nil, deletes the profile. Otherwise "profile" must be a
 * string containing the specified profile.
 *
 * @param name [String, nil] The profile name, or "*" to represent all the profiles in the image.
 * @param profile [String] The profile value, or nil to cause the profile to be removed.
 * @return [Magick::Image] self
 */
VALUE
Image_profile_bang(VALUE self, VALUE name, VALUE profile)
{

    if (profile == Qnil)
    {
        return Image_delete_profile(self, name);
    }
    else
    {
        return set_profile(self, StringValueCStr(name), profile);
    }

}


/**
 * Get image quality.
 *
 * @return [Integer] the quality
 */
VALUE
Image_quality(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, quality, ulong, &rm_image_data_type);
}


/**
 * Return the image depth to the nearest Quantum (8, 16, or 32).
 *
 * @return [Integer] image depth
 */
VALUE
Image_quantum_depth(VALUE self)
{
    Image *image;
    unsigned long quantum_depth;

    image = rm_check_destroyed(self);
    quantum_depth = GetImageQuantumDepth(image, MagickFalse);

    return ULONG2NUM(quantum_depth);
}


/**
 * Performs the requested integer arithmetic operation on the selected channel of the image.
 * This method allows simple arithmetic operations on the component values of all pixels in an
 * image.
 * Of course, you could also do this in Ruby using get_pixels and store_pixels, or view, but
 * quantum_operator will be faster, especially for large numbers of pixels, since it does not need
 * to convert the pixels from C to Ruby.
 *
 * @overload quantum_operator(quantum_expression_op, rvalue, channel = Magick::AllChannels)
 *   @param quantum_expression_op [Magick::QuantumExpressionOperator] the operator
 *   @param rvalue [Numeric] the operation rvalue.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload quantum_operator(quantum_expression_op, rvalue, *channels)
 *   @param quantum_expression_op [Magick::QuantumExpressionOperator] the operator
 *   @param rvalue [Numeric] the operation rvalue.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] self
 */
VALUE
Image_quantum_operator(int argc, VALUE *argv, VALUE self)
{
    Image *image;
    QuantumExpressionOperator quantum_expression_op;
    MagickEvaluateOperator qop;
    double rvalue;
    ChannelType channel;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    // The default channel is AllChannels
    channel = AllChannels;

    /*
        If there are 3 arguments, argument 2 is a ChannelType argument.
        Arguments 1 and 0 are required and are the rvalue and operator,
        respectively.
    */
    switch (argc)
    {
        case 3:
            VALUE_TO_ENUM(argv[2], channel, ChannelType);
            /* Fall through */
        case 2:
            rvalue = NUM2DBL(argv[1]);
            VALUE_TO_ENUM(argv[0], quantum_expression_op, QuantumExpressionOperator);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 or 3)", argc);
            break;
    }

    // Map QuantumExpressionOperator to MagickEvaluateOperator
    switch (quantum_expression_op)
    {
        default:
        case UndefinedQuantumOperator:
            qop = UndefinedEvaluateOperator;
            break;
        case AddQuantumOperator:
            qop = AddEvaluateOperator;
            break;
        case AndQuantumOperator:
            qop = AndEvaluateOperator;
            break;
        case DivideQuantumOperator:
            qop = DivideEvaluateOperator;
            break;
        case LShiftQuantumOperator:
            qop = LeftShiftEvaluateOperator;
            break;
        case MaxQuantumOperator:
            qop = MaxEvaluateOperator;
            break;
        case MinQuantumOperator:
            qop = MinEvaluateOperator;
            break;
        case MultiplyQuantumOperator:
            qop = MultiplyEvaluateOperator;
            break;
        case OrQuantumOperator:
            qop = OrEvaluateOperator;
            break;
        case RShiftQuantumOperator:
            qop = RightShiftEvaluateOperator;
            break;
        case SubtractQuantumOperator:
            qop = SubtractEvaluateOperator;
            break;
        case XorQuantumOperator:
            qop = XorEvaluateOperator;
            break;
        case PowQuantumOperator:
            qop = PowEvaluateOperator;
            break;
        case LogQuantumOperator:
            qop = LogEvaluateOperator;
            break;
        case ThresholdQuantumOperator:
            qop = ThresholdEvaluateOperator;
            break;
        case ThresholdBlackQuantumOperator:
            qop = ThresholdBlackEvaluateOperator;
            break;
        case ThresholdWhiteQuantumOperator:
            qop = ThresholdWhiteEvaluateOperator;
            break;
        case GaussianNoiseQuantumOperator:
            qop = GaussianNoiseEvaluateOperator;
            break;
        case ImpulseNoiseQuantumOperator:
            qop = ImpulseNoiseEvaluateOperator;
            break;
        case LaplacianNoiseQuantumOperator:
            qop = LaplacianNoiseEvaluateOperator;
            break;
        case MultiplicativeNoiseQuantumOperator:
            qop = MultiplicativeNoiseEvaluateOperator;
            break;
        case PoissonNoiseQuantumOperator:
            qop = PoissonNoiseEvaluateOperator;
            break;
        case UniformNoiseQuantumOperator:
            qop = UniformNoiseEvaluateOperator;
            break;
        case CosineQuantumOperator:
            qop = CosineEvaluateOperator;
            break;
        case SetQuantumOperator:
            qop = SetEvaluateOperator;
            break;
        case SineQuantumOperator:
            qop = SineEvaluateOperator;
            break;
        case AddModulusQuantumOperator:
            qop = AddModulusEvaluateOperator;
            break;
        case MeanQuantumOperator:
            qop = MeanEvaluateOperator;
            break;
        case AbsQuantumOperator:
            qop = AbsEvaluateOperator;
            break;
        case ExponentialQuantumOperator:
            qop = ExponentialEvaluateOperator;
            break;
        case MedianQuantumOperator:
            qop = MedianEvaluateOperator;
            break;
        case SumQuantumOperator:
            qop = SumEvaluateOperator;
            break;
        case RootMeanSquareQuantumOperator:
            qop = RootMeanSquareEvaluateOperator;
            break;
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channel);
    GVL_STRUCT_TYPE(EvaluateImage) args = { image, qop, rvalue, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(EvaluateImage), &args);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(EvaluateImageChannel) args = { image, channel, qop, rvalue, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(EvaluateImageChannel), &args);
#endif
    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    return self;
}


/**
 * Analyzes the colors within a reference image and chooses a fixed number of colors to represent
 * the image. The goal of the algorithm is to minimize the difference between the input and output
 * image while minimizing the processing time.
 *
 * @overload quantize(number_colors = 256, colorspace = Magick::RGBColorspace, dither = true, tree_depth = 0, measure_error = false)
 *   @param number_colors [Numeric] The maximum number of colors in the result image.
 *   @param colorspace [Magick::ColorspaceType] The colorspace to quantize in.
 *   @param dither [Boolean] If true, Magick::RiemersmaDitherMethod will be used as
 *     DitherMethod. otherwise NoDitherMethod.
 *   @param tree_depth [Numeric] The tree depth to use while quantizing. The values 0 and 1 support
 *     automatic tree depth determination. The tree depth may be forced via values ranging from 2 to
 *     8. The ideal tree depth depends on the characteristics of the input image, and may be
 *     determined through experimentation.
 *   @param measure_error [Boolean] Set to true to calculate quantization errors when quantizing the
 *     image.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_quantize(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    QuantizeInfo quantize_info;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    GetQuantizeInfo(&quantize_info);

    switch (argc)
    {
        case 5:
            quantize_info.measure_error = (MagickBooleanType) RTEST(argv[4]);
        case 4:
            quantize_info.tree_depth = NUM2UINT(argv[3]);
        case 3:
            if (rb_obj_is_kind_of(argv[2], Class_DitherMethod))
            {
                VALUE_TO_ENUM(argv[2], quantize_info.dither_method, DitherMethod);
#if defined(IMAGEMAGICK_6)
                quantize_info.dither = (MagickBooleanType)(quantize_info.dither_method != NoDitherMethod);
#endif
            }
            else
            {
#if defined(IMAGEMAGICK_7)
                quantize_info.dither_method = RTEST(argv[2]) ? RiemersmaDitherMethod : NoDitherMethod;
#else
                quantize_info.dither = (MagickBooleanType) RTEST(argv[2]);
#endif
            }
        case 2:
            VALUE_TO_ENUM(argv[1], quantize_info.colorspace, ColorspaceType);
        case 1:
            quantize_info.number_colors = NUM2UINT(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 5)", argc);
            break;
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(QuantizeImage) args = { &quantize_info, new_image, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(QuantizeImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(QuantizeImage) args = { &quantize_info, new_image };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(QuantizeImage), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Applies a radial blur to the image.
 *
 * @param angle_obj [Numeric] the angle (in degrees)
 * @return [Magick::Image] a new image
 */
VALUE
Image_radial_blur(VALUE self, VALUE angle_obj)
{
    Image *image, *new_image;
    ExceptionInfo *exception;
    double angle = NUM2DBL(angle_obj);

    image = rm_check_destroyed(self);
    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(RotationalBlurImage) args = { image, angle, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(RotationalBlurImage), &args);
    new_image = reinterpret_cast<decltype(new_image)>(ret);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Applies a radial blur to the selected image channels.
 *
 * @overload radial_blur_channel(angle, channel = Magick::AllChannels)
 *   @param angle [Numeric] the angle (in degrees)
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload radial_blur_channel(angle, *channels)
 *   @param angle [Numeric] the angle (in degrees)
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_radial_blur_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ExceptionInfo *exception;
    ChannelType channels;
    double angle;

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    // There must be 1 remaining argument.
    if (argc == 0)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (0 for 1 or more)");
    }
    else if (argc > 1)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    angle = NUM2DBL(argv[0]);
    exception = AcquireExceptionInfo();

#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(RotationalBlurImage) args = { image, angle, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(RotationalBlurImage), &args);
    CHANGE_RESULT_CHANNEL_MASK(new_image);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(RotationalBlurImageChannel) args = { image, channels, angle, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(RotationalBlurImageChannel), &args);
#endif
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Changes the value of individual pixels based on the intensity of each pixel compared to a random
 * threshold. The result is a low-contrast, two color image.
 *
 * @overload random_threshold_channel(geometry_str, channel = Magick::AllChannels)
 *   @param geometry_str [Magick::Geometry, String] A geometry string containing LOWxHIGH thresholds.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload random_threshold_channel(geometry_str, *channels)
 *   @param geometry_str [Magick::Geometry, String] A geometry string containing LOWxHIGH thresholds.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 * @see https://www.imagemagick.org/Magick++/Geometry.html
 */
VALUE
Image_random_threshold_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ChannelType channels;
    char *thresholds;
    VALUE geom_str;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    channels = extract_channels(&argc, argv);

    // There must be 1 remaining argument.
    if (argc == 0)
    {
        rb_raise(rb_eArgError, "missing threshold argument");
    }
    else if (argc > 1)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    // Accept any argument that has a to_s method.
    geom_str = rb_String(argv[0]);
    thresholds = StringValueCStr(geom_str);

    new_image = rm_clone_image(image);

    exception = AcquireExceptionInfo();

#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(new_image, channels);
    {
        GeometryInfo geometry_info;

        ParseGeometry(thresholds, &geometry_info);
        GVL_STRUCT_TYPE(RandomThresholdImage) args = { new_image, geometry_info.rho, geometry_info.sigma, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(RandomThresholdImage), &args);
    }
    END_CHANNEL_MASK(new_image);
#else
    GVL_STRUCT_TYPE(RandomThresholdImageChannel) args = { new_image, channels, thresholds, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(RandomThresholdImageChannel), &args);
#endif
    rm_check_exception(exception, new_image, DestroyOnError);

    DestroyExceptionInfo(exception);

    RB_GC_GUARD(geom_str);

    return rm_image_new(new_image);
}


/**
 * Create a simulated three-dimensional button-like effect by lightening and darkening the edges of
 * the image. The "width" and "height" arguments define the width of the vertical and horizontal
 * edge of the effect. If "raised" is true, creates a raised effect, otherwise a lowered effect.
 *
 * @overload raise(width = 6, height = 6, raised = true)
 *   @param width [Numeric] The width of the raised edge in pixels.
 *   @param height [Numeric] The height of the raised edge in pixels.
 *   @param raised [Boolean] If true, the image is raised, otherwise lowered.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_raise(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    RectangleInfo rect;
    MagickBooleanType raised = MagickTrue;      // default
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    memset(&rect, 0, sizeof(rect));
    rect.width = 6;         // default
    rect.height = 6;        // default

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 3:
            raised = (MagickBooleanType)RTEST(argv[2]);
        case 2:
            rect.height = NUM2ULONG(argv[1]);
        case 1:
            rect.width = NUM2ULONG(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 3)", argc);
            break;
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(RaiseImage) args = { new_image, &rect, raised, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(RaiseImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(RaiseImage) args = { new_image, &rect, raised };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(RaiseImage), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Call ReadImage.
 *
 * @param file_arg [File, String] the file containing image data or file name
 * @yield [info]
 * @yieldparam info [Magick::Image::Info]
 * @return [Array<Magick::Image>] an array of 1 or more new image objects
 */
VALUE
Image_read(VALUE klass, VALUE file_arg)
{
    return rd_image(klass, file_arg, GVL_FUNC(ReadImage));
}


/**
 * Called when `rm_obj_to_s' raised an exception.
 *
 * No Ruby usage (internal function)
 *
 * @param arg the bad arg given
 * @return 0
 */
static VALUE
file_arg_rescue(VALUE arg, VALUE raised_exc ATTRIBUTE_UNUSED)
{
    rb_raise(rb_eTypeError, "argument must be path name or open file (%s given)",
             rb_class2name(CLASS_OF(arg)));
}


// aliases for common use of structure types; PingImage, ReadImage
typedef GVL_STRUCT_TYPE(PingImage) GVL_STRUCT_TYPE(rd_image);

/**
 * Transform arguments, call either ReadImage or PingImage.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - Yields to a block to get Image::Info attributes before calling
 *     Read/PingImage
 *
 * @param klass the Ruby class for an Image
 * @param file the file containing image data
 * @param reader which image reader to use (ReadImage or PingImage)
 * @return an array of 1 or more new image objects
 * @see Image_read
 * @see Image_ping
 * @see array_from_images
 */

#if defined(__APPLE__) || defined(__FreeBSD__)
void sig_handler(int sig ATTRIBUTE_UNUSED)
{
}
#endif

static VALUE
rd_image(VALUE klass ATTRIBUTE_UNUSED, VALUE file, gvl_function_t fp)
{
    char *filename;
    size_t filename_l;
    Info *info;
    VALUE info_obj;
    Image *images;
    ExceptionInfo *exception;

    // Create a new Info structure for this read/ping
    info_obj = rm_info_new();
    TypedData_Get_Struct(info_obj, Info, &rm_info_data_type, info);

    if (TYPE(file) == T_FILE)
    {
        rb_io_t *fptr;

        // Ensure file is open - raise error if not
        GetOpenFile(file, fptr);
        rb_io_check_readable(fptr);
        SetImageInfoFile(info, rb_io_stdio_file(fptr));
    }
    else
    {
        // Convert arg to string. If an exception occurs raise an error condition.
        file = rb_rescue(RESCUE_FUNC(rb_String), file, RESCUE_EXCEPTION_HANDLER_FUNC(file_arg_rescue), file);

        filename = rm_str2cstr(file, &filename_l);
        filename_l = min(filename_l, MaxTextExtent-1);
        if (filename_l == 0)
        {
            rb_raise(rb_eArgError, "invalid path");
        }

        memcpy(info->filename, filename, (size_t)filename_l);
        info->filename[filename_l] = '\0';
        SetImageInfoFile(info, NULL);
    }

    exception = AcquireExceptionInfo();

#if defined(__APPLE__) || defined(__FreeBSD__)
    struct sigaction act, oldact;
    act.sa_handler = sig_handler;
    act.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &act, &oldact) < 0)
    {
        rb_sys_fail("sigaction");
    }
#endif

    GVL_STRUCT_TYPE(rd_image) args = { info, exception };
    images = (Image *)CALL_FUNC_WITHOUT_GVL(fp, &args);

#if defined(__APPLE__) || defined(__FreeBSD__)
    if (sigaction(SIGCHLD, &oldact, NULL) < 0)
    {
        rb_sys_fail("sigaction");
    }
#endif

    rm_check_exception(exception, images, DestroyOnError);
    DestroyExceptionInfo(exception);

    rm_set_user_artifact(images, info);
    rm_sync_image_options(images, info);

    RB_GC_GUARD(info_obj);

    return array_from_images(images);
}


/**
 * Use this method to translate, scale, shear, or rotate image colors. Although you can use variable
 * sized matrices, typically you use a 5x5 for an RGBA image and a 6x6 for CMYKA. Populate the last
 * row with normalized values to translate.
 *
 * @param color_matrix [Array<Numeric>] An array of Float values representing the recolor matrix.
 * @return [Magick::Image] a new image
 */
VALUE
Image_recolor(VALUE self, VALUE color_matrix)
{
    Image *image, *new_image;
    unsigned long order;
    long x, len;
    double *matrix;
    ExceptionInfo *exception;
    KernelInfo *kernel_info;

    image = rm_check_destroyed(self);
    color_matrix = rm_check_ary_type(color_matrix);

    // Allocate color matrix from Ruby's memory
    len = RARRAY_LEN(color_matrix);
    matrix = ALLOC_N(double, len);

    for (x = 0; x < len; x++)
    {
        VALUE element = rb_ary_entry(color_matrix, x);
        if (rm_check_num2dbl(element))
        {
            matrix[x] = NUM2DBL(element);
        }
        else
        {
            xfree(matrix);
            rb_raise(rb_eTypeError, "type mismatch: %s given", rb_class2name(CLASS_OF(element)));
        }
    }

    order = (unsigned long)sqrt((double)(len + 1.0));

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    kernel_info = AcquireKernelInfo(NULL, exception);
    if (rm_should_raise_exception(exception, RetainExceptionRetention))
    {
        if (kernel_info != (KernelInfo *) NULL)
        {
            DestroyKernelInfo(kernel_info);
        }
        xfree((void *)matrix);
        rm_raise_exception(exception);
    }
#else
    kernel_info = AcquireKernelInfo(NULL);
#endif
    if (kernel_info == (KernelInfo *) NULL)
    {
        xfree((void *) matrix);
        DestroyExceptionInfo(exception);
        return Qnil;
    }
    kernel_info->width = order;
    kernel_info->height = order;
    kernel_info->values = (double *) matrix;

    GVL_STRUCT_TYPE(ColorMatrixImage) args = { image, kernel_info, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ColorMatrixImage), &args);
    kernel_info->values = (double *) NULL;
    DestroyKernelInfo(kernel_info);
    xfree((void *) matrix);

    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Read a Base64-encoded image.
 *
 * @param content [String] the content
 * @yield [info]
 * @yieldparam info [Magick::Image::Info]
 * @return [Array<Magick::Image>] an array of new images
 */
VALUE
Image_read_inline(VALUE self ATTRIBUTE_UNUSED, VALUE content)
{
    VALUE info_obj;
    Image *images;
    ImageInfo *info;
    char *image_data;
    size_t x, image_data_l;
    unsigned char *blob;
    size_t blob_l;
    ExceptionInfo *exception;

    image_data = rm_str2cstr(content, &image_data_l);

    // Search for a comma. If found, we'll set the start of the
    // image data just following the comma. Otherwise we'll assume
    // the image data starts with the first byte.
    for (x = 0; x < image_data_l; x++)
    {
        if (image_data[x] == ',')
        {
            break;
        }
    }
    if (x < image_data_l)
    {
        image_data += x + 1;
    }

    GVL_STRUCT_TYPE(Base64Decode) args_Base64Decode = { image_data, &blob_l };
    blob = (unsigned char *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(Base64Decode), &args_Base64Decode);
    if (blob_l == 0)
    {
        rb_raise(rb_eArgError, "can't decode image");
    }

    exception = AcquireExceptionInfo();

    // Create a new Info structure for this read. About the
    // only useful attribute that can be set is `format'.
    info_obj = rm_info_new();
    TypedData_Get_Struct(info_obj, Info, &rm_info_data_type, info);

    GVL_STRUCT_TYPE(BlobToImage) args_BlobToImage = { info, blob, blob_l, exception };
    images = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(BlobToImage), &args_BlobToImage);
    magick_free((void *)blob);

    rm_check_exception(exception, images, DestroyOnError);
    DestroyExceptionInfo(exception);

    rm_set_user_artifact(images, info);
    rm_sync_image_options(images, info);

    RB_GC_GUARD(info_obj);

    return array_from_images(images);
}


/**
 * Convert a list of images to an array of Image objects.
 *
 * No Ruby usage (internal function)
 *
 * @param images the images
 * @return array of images
 */
static VALUE
array_from_images(Image *images)
{
    VALUE image_obj, image_ary;
    Image *image;

    // Orphan the image, create an Image object, add it to the array.

    image_ary = rb_ary_new();
    while (images)
    {
        image = RemoveFirstImageFromList(&images);
        image_obj = rm_image_new(image);
        rb_ary_push(image_ary, image_obj);
    }

    RB_GC_GUARD(image_obj);
    RB_GC_GUARD(image_ary);

    return image_ary;
}


/**
 * Smooth the contours of an image while still preserving edge information.
 *
 * @param radius [Numeric] A neighbor is defined by radius. Use a radius of 0 and reduce_noise
 *   selects a suitable radius for you.
 * @return [Magick::Image] a new image
 */
VALUE
Image_reduce_noise(VALUE self, VALUE radius)
{
    Image *image, *new_image;
    ExceptionInfo *exception;
    size_t radius_size = NUM2SIZET(radius);

    image = rm_check_destroyed(self);

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(StatisticImage) args = { image, NonpeakStatistic, radius_size, radius_size, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(StatisticImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);

    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Reduce the number of colors in img to the colors used by remap_image. If a dither method is
 * specified then the given colors are dithered over the image as necessary, otherwise the closest
 * color (in RGB colorspace) is selected to replace that pixel in the image.
 *
 * @overload remap(remap_image, dither_method = Magick::RiemersmaDitherMethod)
 *   @param remap_image [Magick::Image, Magick::ImageList] The reference image or imagelist. If an
 *     imagelist, uses the current image.
 *   @param dither_method [Magick::DitherMethod] this object
 *   @return self
 */
VALUE
Image_remap(int argc, VALUE *argv, VALUE self)
{
    Image *image, *remap_image;
    QuantizeInfo quantize_info;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_frozen(self);

    GetQuantizeInfo(&quantize_info);

    switch (argc)
    {
        case 2:
            VALUE_TO_ENUM(argv[1], quantize_info.dither_method, DitherMethod);
#if defined(IMAGEMAGICK_6)
            quantize_info.dither = MagickTrue;
#endif
            break;
        case 1:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or 2)", argc);
            break;
    }

    remap_image = rm_check_destroyed(rm_cur_image(argv[0]));

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(RemapImage) args = { &quantize_info, image, remap_image, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(RemapImage), &args);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(RemapImage) args = { &quantize_info, image, remap_image };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(RemapImage), &args);
    rm_check_image_exception(image, RetainOnError);
#endif

    return self;
}


/**
 * Get the type of rendering intent.
 *
 * @return [Magick::RenderingIntent] the rendering intent
 */
VALUE
Image_rendering_intent(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return RenderingIntent_find(image->rendering_intent);
}


/**
 * Set the type of rendering intent..
 *
 * @param ri [Magick::RenderingIntent] the rendering intent
 * @return [Magick::RenderingIntent] the given value
 */
VALUE
Image_rendering_intent_eq(VALUE self, VALUE ri)
{
    Image *image = rm_check_frozen(self);
    VALUE_TO_ENUM(ri, image->rendering_intent, RenderingIntent);
    return ri;
}


#if defined(IMAGEMAGICK_7)
/**
 * Create new blurred image.
 *
 * No Ruby usage (internal function)
 *
 * @param image the image
 * @param blur the blur
 * @return NULL if not apply blur, otherwise a new image
 */
static Image*
blurred_image(Image* image, double blur)
{
    ExceptionInfo *exception;
    Image *new_image;

    exception = AcquireExceptionInfo();
    if (blur > 1.0)
    {
        GVL_STRUCT_TYPE(BlurImage) args = { image, blur, blur, exception };
        new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(BlurImage), &args);
    }
    else
    {
        GVL_STRUCT_TYPE(SharpenImage) args = { image, blur, blur, exception };
        new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SharpenImage), &args);
    }
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return new_image;
}
#endif


/**
 * Resample image to specified horizontal resolution, vertical resolution,
 * filter and blur factor.
 *
 * No Ruby usage (internal function)
 *
 * @param bang whether the bang (!) version of the method was called
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @return self if bang, otherwise a new image
 * @see Image_resample
 * @see Image_resample_bang
 */
static VALUE
resample(int bang, int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    FilterType filter;
    double x_resolution, y_resolution, blur;
    double width, height;
    ExceptionInfo *exception;

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);

    // Set up defaults
    filter  = image->filter;
#if defined(IMAGEMAGICK_7)
    blur    = 1.0;
#else
    blur    = image->blur;
#endif
    x_resolution = 72.0;
    y_resolution = 72.0;

    switch (argc)
    {
        case 4:
            blur = NUM2DBL(argv[3]);
        case 3:
            VALUE_TO_ENUM(argv[2], filter, FilterType);
        case 2:
            y_resolution = NUM2DBL(argv[1]);
            if (y_resolution < 0.0)
            {
                rb_raise(rb_eArgError, "invalid y_resolution value (%lf given)", y_resolution);
            }
        case 1:
            x_resolution = NUM2DBL(argv[0]);
            if (x_resolution < 0.0)
            {
                rb_raise(rb_eArgError, "invalid x_resolution value (%lf given)", x_resolution);
            }
            if (argc == 1)
            {
                y_resolution = x_resolution;
            }
#if defined(IMAGEMAGICK_7)
            width = (x_resolution * image->columns /
                        (image->resolution.x == 0.0 ? 72.0 : image->resolution.x) + 0.5);
            height = (y_resolution * image->rows /
                         (image->resolution.y == 0.0 ? 72.0 : image->resolution.y) + 0.5);
#else
            width = (x_resolution * image->columns /
                        (image->x_resolution == 0.0 ? 72.0 : image->x_resolution) + 0.5);
            height = (y_resolution * image->rows /
                         (image->y_resolution == 0.0 ? 72.0 : image->y_resolution) + 0.5);
#endif
            if (width > (double)ULONG_MAX || height > (double)ULONG_MAX)
            {
                rb_raise(rb_eRangeError, "resampled image too big");
            }
            break;
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 4)", argc);
            break;
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    Image *preprocess = blurred_image(image, blur);
    GVL_STRUCT_TYPE(ResampleImage) args = { preprocess, x_resolution, y_resolution, filter, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ResampleImage), &args);
    DestroyImage(preprocess);
#else
    GVL_STRUCT_TYPE(ResampleImage) args = { image, x_resolution, y_resolution, filter, blur, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ResampleImage), &args);
#endif
    rm_check_exception(exception, new_image, DestroyOnError);

    DestroyExceptionInfo(exception);

    if (bang)
    {
        rm_ensure_result(new_image);
        UPDATE_DATA_PTR(self, new_image);
        rm_image_destroy(image);
        return self;
    }
    return rm_image_new(new_image);
}

/**
 * Resample image to specified horizontal resolution, vertical resolution, filter and blur factor.
 *
 * Resize the image so that its rendered size remains the same as the original at the specified
 * target resolution. For example, if a 300 DPI image renders at 3 inches by 2 inches on a 300 DPI
 * device, when the image has been resampled to 72 DPI, it will render at 3 inches by 2 inches on a
 * 72 DPI device. Note that only a small number of image formats (e.g. JPEG, PNG, and TIFF) are
 * capable of storing the image resolution. For formats which do not support an image resolution,
 * the original resolution of the image must be specified via the density attribute prior to
 * specifying the resample resolution.
 *
 * @overload resample(x_resolution = 72.0, y_resolution = 72.0, filter = self.filter, blur = self.blur)
 *   @param x_resolution [Numeric] the target horizontal resolution.
 *   @param y_resolution [Numeric] the target vertical resolution.
 *   @param filter [Magick::FilterType] the filter type
 *   @param blur [Numeric] the blur size
 *   @return [Magick] a new image
 *   @see Image#resample!
 */
VALUE
Image_resample(int argc, VALUE *argv, VALUE self)
{
    rm_check_destroyed(self);
    return resample(False, argc, argv, self);
}


/**
 * Resample image to specified horizontal resolution, vertical resolution, filter and blur factor.
 * In-place form of {Image#resample}.
 *
 * @overload resample!(x_resolution = 72.0, y_resolution = 72.0, filter = self.filter, blur = self.blur)
 *   @param x_resolution [Numeric] the target horizontal resolution.
 *   @param y_resolution [Numeric] the target vertical resolution.
 *   @param filter [Magick::FilterType] the filter type
 *   @param blur [Numeric] the blur size
 *   @return [Magick] a new image
 *   @see Image#resample
 */
VALUE
Image_resample_bang(int argc, VALUE *argv, VALUE self)
{
    rm_check_frozen(self);
    return resample(True, argc, argv, self);
}


/**
 * Scale an image to the desired dimensions using the specified filter and blur
 * factor.
 *
 * No Ruby usage (internal function)
 *
 * @param bang whether the bang (!) version of the method was called
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @return self if bang, otherwise a new image
 * @see Image_resize
 * @see Image_resize_bang
 */
static VALUE
resize(int bang, int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double scale_arg;
    FilterType filter;
    unsigned long rows, columns;
    double blur, drows, dcols;
    ExceptionInfo *exception;

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);

    // Set up defaults
    filter  = image->filter;
#if defined(IMAGEMAGICK_7)
    blur    = 1.0;
#else
    blur    = image->blur;
#endif
    rows    = image->rows;
    columns = image->columns;

    switch (argc)
    {
        case 4:
            blur = NUM2DBL(argv[3]);
        case 3:
            VALUE_TO_ENUM(argv[2], filter, FilterType);
        case 2:
            rows = NUM2ULONG(argv[1]);
            columns = NUM2ULONG(argv[0]);
            if (columns == 0 || rows == 0)
            {
                rb_raise(rb_eArgError, "invalid result dimension (%lu, %lu given)", columns, rows);
            }
            break;
        case 1:
            scale_arg = NUM2DBL(argv[0]);
            if (scale_arg < 0.0)
            {
                rb_raise(rb_eArgError, "invalid scale_arg value (%g given)", scale_arg);
            }
            drows = scale_arg * image->rows + 0.5;
            dcols = scale_arg * image->columns + 0.5;
            if (drows > (double)ULONG_MAX || dcols > (double)ULONG_MAX)
            {
                rb_raise(rb_eRangeError, "resized image too big");
            }
            rows = (unsigned long) drows;
            columns = (unsigned long) dcols;
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 to 4)", argc);
            break;
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    Image *preprocess = (argc == 4) ? blurred_image(image, blur) : image;
    GVL_STRUCT_TYPE(ResizeImage) args = { preprocess, columns, rows, filter, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ResizeImage), &args);
    if (argc == 4)
    {
        DestroyImage(preprocess);
    }
#else
    GVL_STRUCT_TYPE(ResizeImage) args = { image, columns, rows, filter, blur, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ResizeImage), &args);
#endif
    rm_check_exception(exception, new_image, DestroyOnError);

    DestroyExceptionInfo(exception);

    if (bang)
    {
        rm_ensure_result(new_image);
        UPDATE_DATA_PTR(self, new_image);
        rm_image_destroy(image);
        return self;
    }
    return rm_image_new(new_image);
}


/**
 * Scale an image to the desired dimensions using the specified filter and blur factor.
 *
 * @overload resize(scale)
 *   @param scale [Numeric] You can use this argument instead of specifying the desired width and
 *     height. The percentage size change. For example, 1.25 makes the new image 125% of the size of
 *     the receiver. The scale factor 0.5 makes the new image 50% of the size of the receiver.
 *
 * @overload resize(cols, rows, filter, blur)
 *   @param cols [Numeric] The desired width
 *   @param rows [Numeric] The desired height.
 *   @param filter [Magick::FilterType] the filter type
 *   @param blur [Numeric] the blur size
 *
 * @return [Magick::Image] a new image
 * @see Image#resize!
 */
VALUE
Image_resize(int argc, VALUE *argv, VALUE self)
{
    rm_check_destroyed(self);
    return resize(False, argc, argv, self);
}


/**
 * Scale an image to the desired dimensions using the specified filter and blur factor.
 * In-place form of {Image#resize}.
 *
 * @overload resize!(scale)
 *   @param scale [Numeric] You can use this argument instead of specifying the desired width and
 *     height. The percentage size change. For example, 1.25 makes the new image 125% of the size of
 *     the receiver. The scale factor 0.5 makes the new image 50% of the size of the receiver.
 *
 * @overload resize!(cols, rows, filter, blur)
 *   @param cols [Numeric] The desired width
 *   @param rows [Numeric] The desired height.
 *   @param filter [Magick::FilterType] the filter type
 *   @param blur [Numeric] the blur size
 *
 * @return [Magick::Image] a new image
 * @see Image#resize!
 */
VALUE
Image_resize_bang(int argc, VALUE *argv, VALUE self)
{
    rm_check_frozen(self);
    return resize(True, argc, argv, self);
}


/**
 * Offset an image as defined by x_offset and y_offset.
 *
 * @param x_offset [Numeric] the x offset
 * @param y_offset [Numeric] the y offset
 * @return [Magick::Image] a new image
 */
VALUE
Image_roll(VALUE self, VALUE x_offset, VALUE y_offset)
{
    Image *image, *new_image;
    ExceptionInfo *exception;
    ssize_t x = NUM2LONG(x_offset);
    ssize_t y = NUM2LONG(y_offset);

    image = rm_check_destroyed(self);

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(RollImage) args = { image, x, y, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(RollImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Rotate the image.
 *
 * No Ruby usage (internal function)
 *
 * @param bang whether the bang (!) version of the method was called
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @return self if bang, otherwise a new image
 * @see Image_rotate
 * @see Image_rotate_bang
 */
static VALUE
rotate(int bang, int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double degrees;
    char *arrow;
    size_t arrow_l;
    ExceptionInfo *exception;

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);

    switch (argc)
    {
        case 2:
            arrow = rm_str2cstr(argv[1], &arrow_l);
            if (arrow_l != 1 || (*arrow != '<' && *arrow != '>'))
            {
                rb_raise(rb_eArgError, "second argument must be '<' or '>', '%s' given", arrow);
            }
            if (*arrow == '>' && image->columns <= image->rows)
            {
                return Qnil;
            }
            if (*arrow == '<' && image->columns >= image->rows)
            {
                return Qnil;
            }
        case 1:
            degrees = NUM2DBL(argv[0]);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or 2)", argc);
            break;
    }

    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(RotateImage) args = { image, degrees, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(RotateImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    if (bang)
    {
        rm_ensure_result(new_image);
        UPDATE_DATA_PTR(self, new_image);
        rm_image_destroy(image);
        return self;
    }
    return rm_image_new(new_image);
}


/**
 * Rotate the receiver by the specified angle. Positive angles rotate clockwise while negative
 * angles rotate counter-clockwise. New pixels introduced by the rotation are the same color as the
 * current background color. Set the background color to "none" to make the new pixels transparent
 * black.
 *
 * @overload rotate(degrees)
 *   @param degrees [Numeric] The number of degrees to rotate the image.
 *
 * @overload rotate(degrees, qualifier)
 *   @param degrees [Numeric] The number of degrees to rotate the image.
 *   @param qualifier [String] If present, either ">" or "<". If ">", rotates the image only if the
 *     image's width exceeds its height. If "<" rotates the image only if its height exceeds its
 *     width. If this argument is omitted the image is always rotated.
 *
 * @return [Magick::Image] a new image
 * @see Image#rotate!
 */
VALUE
Image_rotate(int argc, VALUE *argv, VALUE self)
{
    rm_check_destroyed(self);
    return rotate(False, argc, argv, self);
}


/**
 * Rotate the image.
 * In-place form of {Image#rotate}.
 *
 * @overload rotate!(degrees)
 *   @param degrees [Numeric] The number of degrees to rotate the image.
 *
 * @overload rotate!(degrees, qualifier)
 *   @param degrees [Numeric] The number of degrees to rotate the image.
 *   @param qualifier [String] If present, either ">" or "<". If ">", rotates the image only if the
 *     image's width exceeds its height. If "<" rotates the image only if its height exceeds its
 *     width. If this argument is omitted the image is always rotated.
 *
 * @return [Magick::Image] a new image
 * @see Image#rotate!
 */
VALUE
Image_rotate_bang(int argc, VALUE *argv, VALUE self)
{
    rm_check_frozen(self);
    return rotate(True, argc, argv, self);
}


/**
 * Return image rows.
 *
 * @return [Integer] the image rows
 */
VALUE
Image_rows(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, rows, int, &rm_image_data_type);
}


/**
 * Scale an image to the desired dimensions with pixel sampling. Unlike other scaling methods, this
 * method does not introduce any additional color into the scaled image.
 *
 * @overload sample(scale)
 *   @param scale [Numeric] You can use this argument instead of specifying the desired width and
 *     height. The percentage size change. For example, 1.25 makes the new image 125% of the size of
 *     the receiver. The scale factor 0.5 makes the new image 50% of the size of the receiver.
 *
 * @overload sample(cols, rows)
 *   @param cols [Numeric] The desired width.
 *   @param rows [Numeric] The desired height.
 *
 * @return [Magick::Image] a new image
 * @see Image#sample!
 */
VALUE
Image_sample(int argc, VALUE *argv, VALUE self)
{
    rm_check_destroyed(self);
    return scale(False, argc, argv, self, GVL_FUNC(SampleImage));
}


/**
 * Scale an image to the desired dimensions with pixel sampling.
 * In-place form of {Image#sample}.
 *
 * @overload sample!(scale)
 *   @param scale [Numeric] You can use this argument instead of specifying the desired width and
 *     height. The percentage size change. For example, 1.25 makes the new image 125% of the size of
 *     the receiver. The scale factor 0.5 makes the new image 50% of the size of the receiver.
 *
 * @overload sample!(cols, rows)
 *   @param cols [Numeric] The desired width.
 *   @param rows [Numeric] The desired height.
 *
 * @return [Magick::Image] a new image
 * @see Image#sample
 */
VALUE
Image_sample_bang(int argc, VALUE *argv, VALUE self)
{
    rm_check_frozen(self);
    return scale(True, argc, argv, self, GVL_FUNC(SampleImage));
}


/**
 * Change the size of an image to the given dimensions. Alias of {Image#sample}.
 *
 * @overload scale(scale)
 *   @param scale [Float] You can use this argument instead of specifying the desired width and
 *     height. The percentage size change. For example, 1.25 makes the new image 125% of the size of
 *     the receiver. The scale factor 0.5 makes the new image 50% of the size of the receiver.
 *
 * @overload scale(cols, rows)
 *   @param cols [Numeric] The desired width.
 *   @param rows [Numeric] The desired height.
 *
 * @return [Magick::Image] a new image
 * @see Image#sample
 * @see Image#scale!
 */
VALUE
Image_scale(int argc, VALUE *argv, VALUE self)
{
    rm_check_destroyed(self);
    return scale(False, argc, argv, self, GVL_FUNC(ScaleImage));
}


/**
 * Change the size of an image to the given dimensions. Alias of {Image#sample!}.
 *
 * @overload scale!(scale)
 *   @param scale [Float] You can use this argument instead of specifying the desired width and
 *     height. The percentage size change. For example, 1.25 makes the new image 125% of the size of
 *     the receiver. The scale factor 0.5 makes the new image 50% of the size of the receiver.
 *
 * @overload scale!(cols, rows)
 *   @param cols [Numeric] The desired width.
 *   @param rows [Numeric] The desired height.
 *
 * @return [Magick::Image] a new image
 * @see Image#sample
 * @see Image#scale!
 */
VALUE
Image_scale_bang(int argc, VALUE *argv, VALUE self)
{
    rm_check_frozen(self);
    return scale(True, argc, argv, self, GVL_FUNC(ScaleImage));
}


// aliases for common use of structure types; SampleImage, ScaleImage,
typedef GVL_STRUCT_TYPE(SampleImage) GVL_STRUCT_TYPE(scale);

/**
 * Call ScaleImage or SampleImage
 *
 * Notes:
 *   - If 1 argument > 0, multiply current size by this much.
 *   - If 2 arguments, (cols, rows).
 *
 * No Ruby usage (internal function)
 *
 * @param bang whether the bang (!) version of the method was called
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @param scaler which scalar to use (ScaleImage or SampleImage)
 * @return self if bang, otherwise a new image
 * @see Image_sample
 * @see Image_sample_bang
 * @see Image_scale
 * @see Image_scale_bang
 */
static VALUE
scale(int bang, int argc, VALUE *argv, VALUE self, gvl_function_t fp)
{
    Image *image, *new_image;
    unsigned long columns, rows;
    double scale_arg, drows, dcols;
    ExceptionInfo *exception;

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);

    switch (argc)
    {
        case 2:
            columns = NUM2ULONG(argv[0]);
            rows    = NUM2ULONG(argv[1]);
            if (columns == 0 || rows == 0)
            {
                rb_raise(rb_eArgError, "invalid result dimension (%lu, %lu given)", columns, rows);
            }
            break;
        case 1:
            scale_arg = NUM2DBL(argv[0]);
            if (scale_arg <= 0)
            {
                rb_raise(rb_eArgError, "invalid scale value (%g given)", scale_arg);
            }
            drows = scale_arg * image->rows + 0.5;
            dcols = scale_arg * image->columns + 0.5;
            if (drows > (double)ULONG_MAX || dcols > (double)ULONG_MAX)
            {
                rb_raise(rb_eRangeError, "resized image too big");
            }
            rows = (unsigned long) drows;
            columns = (unsigned long) dcols;
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or 2)", argc);
            break;
    }

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(scale) args = { image, columns, rows, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(fp, &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    if (bang)
    {
        rm_ensure_result(new_image);
        UPDATE_DATA_PTR(self, new_image);
        rm_image_destroy(image);
        return self;
    }

    return rm_image_new(new_image);
}


/**
 * Return the scene number assigned to the image the last time the image was written to a
 * multi-image image file.
 *
 * @return [Integer] the image scene
 */
VALUE
Image_scene(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, scene, ulong, &rm_image_data_type);
}


/**
 * Selectively blur pixels within a contrast threshold.
 *
 * @overload selective_blur_channel(radius, sigma, threshold, channel = Magick::AllChannels)
 *   @param radius [Numeric] the radius value
 *   @param sigma [Numeric] the sigma value
 *   @param threshold [Numeric, String] Either a number between 0.0 and 1.0 or a string in the form
 *     "NN%"
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload selective_blur_channel(radius, sigma, threshold, *channels)
 *   @param radius [Numeric] the radius value
 *   @param sigma [Numeric] the sigma value
 *   @param threshold [Numeric, String] Either a number between 0.0 and 1.0 or a string in the form
 *     "NN%"
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_selective_blur_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double radius, sigma, threshold;
    ExceptionInfo *exception;
    ChannelType channels;

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);
    if (argc > 3)
    {
        raise_ChannelType_error(argv[argc-1]);
    }
    if (argc != 3)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 3 or more)", argc);
    }
    radius = NUM2DBL(argv[0]);
    sigma = NUM2DBL(argv[1]);

    // threshold is either a floating-point number or a string in the form "NN%".
    // Either way it's supposed to represent a percentage of the QuantumRange.
    threshold = rm_percentage(argv[2], 1.0) * QuantumRange;

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(SelectiveBlurImage) args = { image, radius, sigma, threshold, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SelectiveBlurImage), &args);
    CHANGE_RESULT_CHANNEL_MASK(new_image);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(SelectiveBlurImageChannel) args = { image, channels, radius, sigma, threshold, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SelectiveBlurImageChannel), &args);
#endif
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Sets the depth of the image channel.
 *
 * @param channel_arg [Magick::ChannelType] the channel
 * @param depth [Numeric] the depth
 * @return self
 */
VALUE
Image_set_channel_depth(VALUE self, VALUE channel_arg, VALUE depth)
{
    Image *image;
    ChannelType channel;
    unsigned long channel_depth;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_frozen(self);

    VALUE_TO_ENUM(channel_arg, channel, ChannelType);
    channel_depth = NUM2ULONG(depth);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(image, channel);
    GVL_STRUCT_TYPE(SetImageDepth) args = { image, channel_depth, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageDepth), &args);
    END_CHANNEL_MASK(image);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(SetImageChannelDepth) args = { image, channel, channel_depth };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageChannelDepth), &args);
    rm_check_image_exception(image, RetainOnError);
#endif

    return self;
}


/**
 * Constructs a grayscale image for each channel specified.
 *
 * @overload separate(channel = Magick::AllChannels)
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload separate(*channels)
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::ImageList] a new ImageList
 */
VALUE
Image_separate(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_images;
    ChannelType channels = UndefinedChannel;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    // All arguments are ChannelType enums
    if (argc > 0)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(SeparateImages) args = { image, exception };
    new_images = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SeparateImages), &args);
    CHANGE_RESULT_CHANNEL_MASK(new_images);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(SeparateImages) args = { image, channels, exception };
    new_images = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SeparateImages), &args);
#endif
    rm_check_exception(exception, new_images, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_imagelist_from_images(new_images);
}


/**
 * Applies a special effect to the image, similar to the effect achieved in a photo darkroom by
 * sepia toning.
 *
 * @overload sepiatone(threshold = Magick::QuantumRange)
 *   @param threshold [Numeric] Threshold ranges from 0 to QuantumRange and is a measure of the extent
 *     of the sepia toning. A threshold of 80% is a good starting point for a reasonable tone.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_sepiatone(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double threshold = (double) QuantumRange;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 1:
            threshold = NUM2DBL(argv[0]);
            break;
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 or 1)", argc);
    }

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(SepiaToneImage) args = { image, threshold, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SepiaToneImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Segments an image by analyzing the histograms of the color components and identifying units that
 * are homogeneous with the fuzzy c-means technique.
 *
 * @overload segment(colorspace = Magick::RGBColorspace, cluster_threshold = 1.0, smoothing_threshold = 1.5, verbose = false)
 *   @param colorspace [Magick::ColorspaceType] A ColorspaceType value. Empirical evidence suggests
 *     that distances in YUV or YIQ correspond to perceptual color differences more closely than do
 *     distances in RGB space. The image is then returned to RGB colorspace after color reduction.
 *   @param cluster_threshold [Numeric] The number of pixels in each cluster must exceed the the
 *     cluster threshold to be considered valid.
 *   @param smoothing_threshold [Numeric] The smoothing threshold eliminates noise in the second
 *     derivative of the histogram. As the value is increased, you can expect a smoother second
 *     derivative.
 *   @param verbose [Boolean] If true, segment prints detailed information about the identified classes.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_segment(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ColorspaceType colorspace   = RGBColorspace;    // These are the Magick++ defaults
    MagickBooleanType verbose   = MagickFalse;
    double cluster_threshold    = 1.0;
    double smoothing_threshold  = 1.5;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 4:
            verbose = (MagickBooleanType)RTEST(argv[3]);
        case 3:
            smoothing_threshold = NUM2DBL(argv[2]);
        case 2:
            cluster_threshold = NUM2DBL(argv[1]);
        case 1:
            VALUE_TO_ENUM(argv[0], colorspace, ColorspaceType);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 4)", argc);
            break;
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(SegmentImage) args = { new_image, colorspace, verbose, cluster_threshold, smoothing_threshold, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SegmentImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(SegmentImage) args = { new_image, colorspace, verbose, cluster_threshold, smoothing_threshold };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SegmentImage), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * If called with an associated block, properties runs the block once for each property defined for
 * the image. The block arguments are the property name and its value. If there is no block,
 * properties returns a hash with one element for each property. The hash key is the property name
 * and the associated value is the property value.
 *
 * @overload properties
 *   @return [Hash<String, String>] the properties
 *
 * @overload properties
 *   @yield [property, value]
 *   @yieldparam property [String] property key
 *   @yieldparam value [String] property value
 *   @return [Magick::Image] self
 */
VALUE
Image_properties(VALUE self)
{
    Image *image;
    VALUE attr_hash, ary;
    const char *property, *value;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
#endif

    if (rb_block_given_p())
    {
        ary = rb_ary_new2(2);

        ResetImagePropertyIterator(image);
        property = GetNextImageProperty(image);
        while (property)
        {
#if defined(IMAGEMAGICK_7)
            value = GetImageProperty(image, property, exception);
#else
            value = GetImageProperty(image, property);
#endif
            rb_ary_store(ary, 0, rb_str_new2(property));
            rb_ary_store(ary, 1, rb_str_new2(value));
            rb_yield(ary);
            property = GetNextImageProperty(image);
        }
#if defined(IMAGEMAGICK_7)
        CHECK_EXCEPTION();
        DestroyExceptionInfo(exception);
#else
        rm_check_image_exception(image, RetainOnError);
#endif

        RB_GC_GUARD(ary);

        return self;
    }

    // otherwise return properties hash
    else
    {
        attr_hash = rb_hash_new();
        ResetImagePropertyIterator(image);
        property = GetNextImageProperty(image);
        while (property)
        {
#if defined(IMAGEMAGICK_7)
            value = GetImageProperty(image, property, exception);
#else
            value = GetImageProperty(image, property);
#endif
            rb_hash_aset(attr_hash, rb_str_new2(property), rb_str_new2(value));
            property = GetNextImageProperty(image);
        }
#if defined(IMAGEMAGICK_7)
        CHECK_EXCEPTION();
        DestroyExceptionInfo(exception);
#else
        rm_check_image_exception(image, RetainOnError);
#endif

        RB_GC_GUARD(attr_hash);

        return attr_hash;
    }

}


/**
 * Shine a distant light on an image to create a three-dimensional effect. You control the
 * positioning of the light with azimuth and elevation; azimuth is measured in degrees off the x
 * axis and elevation is measured in pixels above the Z axis.
 *
 * @overload shade(shading = false, azimuth = 30.0, elevation = 30.0)
 *   @param shading [Boolean] If true, shade shades the intensity of each pixel.
 *   @param azimuth [Numeric] The light source direction. The azimuth is measured in degrees. 0 is at
 *     9 o'clock. Increasing values move the light source counter-clockwise.
 *   @param elevation [Numeric] The light source direction. The azimuth is measured in degrees. 0 is
 *     at 9 o'clock. Increasing values move the light source counter-clockwise.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_shade(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double azimuth = 30.0, elevation = 30.0;
    MagickBooleanType shading = MagickFalse;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 3:
            elevation = NUM2DBL(argv[2]);
        case 2:
            azimuth = NUM2DBL(argv[1]);
        case 1:
            shading = (MagickBooleanType)RTEST(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 3)", argc);
            break;
    }

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(ShadeImage) args = { image, shading, azimuth, elevation, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ShadeImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Call ShadowImage. X- and y-offsets are the pixel offset. Alpha is either a number between 0 and 1
 * or a string "NN%". Sigma is the std. dev. of the Gaussian, in pixels.
 *
 * @overload Image#shadow(x_offset = 4, y_offset = 4, sigma = 4.0, alpha = 1.0)
 *   @param x_offset [Numeric] The shadow x-offset
 *   @param y_offset [Numeric] The shadow y-offset
 *   @param sigma [Numeric] The standard deviation of the Gaussian operator used to produce the
 *     shadow. The higher the number, the "blurrier" the shadow, but the longer it takes to produce
 *     the shadow. Must be > 0.0.
 *   @param alpha [Numeric, String] The percent alpha of the shadow. The argument may be a
 *     floating-point numeric value or a string in the form "NN%".
 *   @return [Magick::Image] a new image
 */
VALUE
Image_shadow(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double alpha = 100.0;
    double sigma = 4.0;
    long x_offset = 4L;
    long y_offset = 4L;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 4:
            alpha = rm_percentage(argv[3], 1.0);   // Clamp to 1.0 < x <= 100.0
            if (fabs(alpha) < 0.01)
            {
                rb_warning("shadow will be transparent - alpha %g very small", alpha);
            }
            alpha = FMIN(alpha, 1.0);
            alpha = FMAX(alpha, 0.01);
            alpha *= 100.0;
        case 3:
            sigma = NUM2DBL(argv[2]);
        case 2:
            y_offset = NUM2LONG(argv[1]);
        case 1:
            x_offset = NUM2LONG(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 4)", argc);
            break;
    }

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(ShadowImage) args = { image, alpha, sigma, x_offset, y_offset, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ShadowImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Sharpen an image.
 *
 * @overload sharpen(radius = 0.0, sigma = 1.0)
 *   @param radius [Numeric] The radius of the Gaussian operator.
 *   @param sigma [Numeric] The sigma (standard deviation) of the Gaussian operator.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_sharpen(int argc, VALUE *argv, VALUE self)
{
    return effect_image(self, argc, argv, GVL_FUNC(SharpenImage));
}


/**
 * Sharpen image on a channel.
 *
 * @overload sharpen_channel(radius = 0.0, sigma = 1.0, channel = Magick::AllChannels)
 *   @param radius [Numeric] The radius of the Gaussian operator.
 *   @param sigma [Numeric] The sigma (standard deviation) of the Gaussian operator.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload sharpen_channel(radius = 0.0, sigma = 1.0, *channels)
 *   @param radius [Numeric] The radius of the Gaussian operator.
 *   @param sigma [Numeric] The sigma (standard deviation) of the Gaussian operator.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_sharpen_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ChannelType channels;
    ExceptionInfo *exception;
    double radius = 0.0, sigma = 1.0;

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    // There must be 0, 1, or 2 remaining arguments.
    switch (argc)
    {
        case 2:
            sigma = NUM2DBL(argv[1]);
            /* Fall thru */
        case 1:
            radius = NUM2DBL(argv[0]);
            /* Fall thru */
        case 0:
            break;
        default:
            raise_ChannelType_error(argv[argc-1]);
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(SharpenImage) args = { image, radius, sigma, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SharpenImage), &args);
    CHANGE_RESULT_CHANNEL_MASK(new_image);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(SharpenImageChannel) args = { image, channels, radius, sigma, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SharpenImageChannel), &args);
#endif

    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Shave pixels from the image edges, leaving a rectangle of the specified width & height in the
 * center.
 *
 * @param width [Numeric] the width to leave
 * @param height [Numeric] the hight to leave
 * @return [Magick::Image] a new image
 * @see Image#shave!
 */
VALUE
Image_shave(VALUE self, VALUE width, VALUE height)
{
    rm_check_destroyed(self);
    return xform_image(False, self, INT2FIX(0), INT2FIX(0), width, height, GVL_FUNC(ShaveImage));
}


/**
 * Shave pixels from the image edges, leaving a rectangle of the specified width & height in the
 * center.
 * In-place form of {Image#shave}.
 *
 * @param width [Numeric] the width to leave
 * @param height [Numeric] the hight to leave
 * @return [Magick::Image] a new image
 * @see Image#shave
 */
VALUE
Image_shave_bang(VALUE self, VALUE width, VALUE height)
{
    rm_check_frozen(self);
    return xform_image(True, self, INT2FIX(0), INT2FIX(0), width, height, GVL_FUNC(ShaveImage));
}


/**
 * Shearing slides one edge of an image along the X or Y axis, creating a parallelogram. An X
 * direction shear slides an edge along the X axis, while a Y direction shear slides an edge along
 * the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears,
 * x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is
 * measured relative to the X axis. Empty triangles left over from shearing the image are filled
 * with the background color.
 *
 * @param x_shear [Numeric] the x shear (in degrees)
 * @param y_shear [Numeric] the y shear (in degrees)
 * @return [Magick::Image] a new image
 */
VALUE
Image_shear(VALUE self, VALUE x_shear, VALUE y_shear)
{
    Image *image, *new_image;
    ExceptionInfo *exception;
    double x = NUM2DBL(x_shear);
    double y = NUM2DBL(y_shear);

    image = rm_check_destroyed(self);

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(ShearImage) args = { image, x, y, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ShearImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Adjusts the contrast of an image channel with a non-linear sigmoidal contrast
 * algorithm. Increases the contrast of the image using a sigmoidal transfer function without
 * saturating highlights or shadows.
 *
 * @overload sigmoidal_contrast_channel(contrast = 3.0, midpoint = 50.0, sharpen = false, channel = Magick::AllChannels)
 *   @param contrast [Numeric] indicates how much to increase the contrast
 *     (0 is none; 3 is typical; 20 is pushing it)
 *   @param midpoint [Numeric] indicates where midtones fall in the resultant image (0 is white; 50%
 *     is middle-gray; 100% is black). Note that "50%" means "50% of the quantum range." This argument
 *     is a number between 0 and QuantumRange. To specify "50%" use QuantumRange * 0.50.
 *   @param sharpen [Boolean] Set sharpen to true to increase the image contrast otherwise the
 *     contrast is reduced.
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload sigmoidal_contrast_channel(contrast = 3.0, midpoint = 50.0, sharpen = false, *channels)
 *   @param contrast [Numeric] indicates how much to increase the contrast
 *     (0 is none; 3 is typical; 20 is pushing it)
 *   @param midpoint [Numeric] indicates where midtones fall in the resultant image (0 is white; 50%
 *     is middle-gray; 100% is black). Note that "50%" means "50% of the quantum range." This argument
 *     is a number between 0 and QuantumRange. To specify "50%" use QuantumRange * 0.50.
 *   @param sharpen [Boolean] Set sharpen to true to increase the image contrast otherwise the
 *     contrast is reduced.
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_sigmoidal_contrast_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    MagickBooleanType sharpen = MagickFalse;
    double contrast = 3.0;
    double midpoint = 50.0;
    ChannelType channels;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);

    switch (argc)
    {
        case 3:
            sharpen  = (MagickBooleanType) RTEST(argv[2]);
        case 2:
            midpoint = NUM2DBL(argv[1]);
        case 1:
            contrast = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            raise_ChannelType_error(argv[argc-1]);
            break;
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    BEGIN_CHANNEL_MASK(new_image, channels);
    GVL_STRUCT_TYPE(SigmoidalContrastImage) args = { new_image, sharpen, contrast, midpoint, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SigmoidalContrastImage), &args);
    END_CHANNEL_MASK(new_image);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(SigmoidalContrastImageChannel) args = { new_image, channels, sharpen, contrast, midpoint };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SigmoidalContrastImageChannel), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Compute a message digest from an image pixel stream with an implementation of the NIST SHA-256
 * Message Digest algorithm.
 *
 * @return [String, nil] the message digest
 */
VALUE
Image_signature(VALUE self)
{
    Image *image;
    const char *signature;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(SignatureImage) args = { image, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SignatureImage), &args);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(SignatureImage) args = { image };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SignatureImage), &args);
    rm_check_image_exception(image, RetainOnError);
#endif
    signature = rm_get_property(image, "signature");
    if (!signature)
    {
        return Qnil;
    }
    return rb_str_new(signature, 64);
}


/**
 * Simulates a pencil sketch. For best results start with a grayscale image.
 *
 * @overload sketch(radius = 0.0, sigma = 1.0, angle = 0.0)
 *   @param radius [Numeric] The radius
 *   @param sigma [Numeric] The standard deviation
 *   @param angle [Numeric] The angle (in degrees)
 *   @return [Magick::Image] a new image
 *   @see motion_blur
 */
VALUE
Image_sketch(int argc, VALUE *argv, VALUE self)
{
    rm_check_destroyed(self);
    return motion_blur(argc, argv, self, GVL_FUNC(SketchImage));
}


/**
 * Apply a special effect to the image, similar to the effect achieved in a photo darkroom by
 * selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to
 * QuantumRange and is a measure of the extent of the solarization.
 *
 * @overload solarize(threshold = 50.0)
 *   @param threshold [Numeric] Ranges from 0 to QuantumRange and is a measure of the extent of the
 *   solarization.
 *   @return a new image
 */
VALUE
Image_solarize(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double threshold = 50.0;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 1:
            threshold = NUM2DBL(argv[0]);
            if (threshold < 0.0 || threshold > QuantumRange)
            {
                rb_raise(rb_eArgError, "threshold out of range, must be >= 0.0 and < QuantumRange");
            }
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 or 1)", argc);
            break;
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(SolarizeImage) args = { new_image, threshold, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SolarizeImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(SolarizeImage) args = { new_image, threshold };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SolarizeImage), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Compare two images.
 *
 * @param other [Object] other image
 * @return [-1, 0, 1, nil] the result of compare
 */
VALUE
Image_spaceship(VALUE self, VALUE other)
{
    Image *imageA, *imageB;
    const char *sigA, *sigB;
    int res;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    imageA = rm_check_destroyed(self);

    // If the other object isn't a Image object, then they can't be equal.
    if (!rb_obj_is_kind_of(other, Class_Image))
    {
        return Qnil;
    }

    imageB = rm_check_destroyed(other);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(SignatureImage) args1 = { imageA, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SignatureImage), &args1);
    CHECK_EXCEPTION();
    GVL_STRUCT_TYPE(SignatureImage) args2 = { imageB, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SignatureImage), &args2);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(SignatureImage) args1 = { imageA };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SignatureImage), &args1);
    GVL_STRUCT_TYPE(SignatureImage) args2 = { imageB };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SignatureImage), &args2);
#endif
    sigA = rm_get_property(imageA, "signature");
    sigB = rm_get_property(imageB, "signature");
    if (!sigA || !sigB)
    {
        rb_raise(Class_ImageMagickError, "can't get image signature");
    }

    res = memcmp(sigA, sigB, 64);
    res = res > 0 ? 1 : (res < 0 ? -1 :  0);    // reduce to 1, -1, 0

    return INT2FIX(res);
}


/**
 * Count the number of channels from the specified list are in an image. Note
 * that this method also removes invalid channels based on the image.
 *
 * No Ruby usage (internal function)
 *
 * @param image the image
 * @param channels the channels
 * @return number of channels
 */
static unsigned long
count_channels(Image *image, ChannelType *channels)
{
    unsigned long ncolors = 0UL;

    if (image->colorspace != CMYKColorspace)
    {
        *channels = (ChannelType) (*channels & ~IndexChannel);  /* remove index channels from count */
    }
#if defined(IMAGEMAGICK_7)
    if ( image->alpha_trait == UndefinedPixelTrait )
#else
    if ( image->matte == MagickFalse )
#endif
    {
        *channels = (ChannelType) (*channels & ~OpacityChannel);  /* remove matte/alpha *channels from count */
    }

    if (*channels & RedChannel)
    {
        ncolors += 1;
    }
    if (*channels & GreenChannel)
    {
        ncolors += 1;
    }
    if (*channels & BlueChannel)
    {
        ncolors += 1;
    }
    if (*channels & IndexChannel)
    {
        ncolors += 1;
    }
    if (*channels & OpacityChannel)
    {
        ncolors += 1;
    }

    return ncolors;
}


/**
 * Fills the image with the specified color or colors, starting at the x,y coordinates associated
 * with the color and using the specified interpolation method.
 *
 * @overload sparse_color(method, x1, y1, color)
 * @overload sparse_color(method, x1, y1, color, x2, y2, color)
 * @overload sparse_color(method, x1, y1, color, x2, y2, color, ...)
 * @overload sparse_color(method, x1, y1, color, channel)
 * @overload sparse_color(method, x1, y1, color, x2, y2, color, channel)
 * @overload sparse_color(method, x1, y1, color, x2, y2, color, ..., channel)
 * @overload sparse_color(method, x1, y1, color, channel, ...)
 * @overload sparse_color(method, x1, y1, color, x2, y2, color, channel, ...)
 * @overload sparse_color(method, x1, y1, color, x2, y2, color, ..., channel, ...)
 *   @param method [Magick::SparseColorMethod] the method
 *   @param x1 [Float] One or more x.
 *   @param y1 [Float] One or more y.
 *   @param color [Magick::Pixel, String] One or more color
 *   @param channel [Magick::ChannelType] one or more ChannelType arguments
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_sparse_color(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    unsigned long x, nargs, ncolors;
    SparseColorMethod method;
    int n, exp;
    double * volatile args;
    ChannelType channels;
    MagickPixel pp;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    n = argc;
    channels = extract_channels(&argc, argv);
    n -= argc;  // n is now the number of channel arguments

    // After the channel arguments have been removed, and not counting the first
    // (method) argument, the number of arguments should be a multiple of 3.
    if (argc < 4 || argc % 3 != 1)
    {
        exp = (argc + 2) / 3 * 3;
        exp = max(exp, 3);
        rb_raise(rb_eArgError, "wrong number of arguments (expected at least %d, got %d)", n+exp+1,  n+argc);
    }

    // Get the method from the argument list
    VALUE_TO_ENUM(argv[0], method, SparseColorMethod);
    argv += 1;
    argc -= 1;

    // A lot of the following code is based on SparseColorOption, in wand/mogrify.c
    ncolors = count_channels(image, &channels);
    nargs = (argc / 3) * (2 + ncolors);

    // Allocate args from Ruby's memory so that GC will collect it if one of
    // the type conversions below raises an exception.
    args = ALLOC_N(double, nargs);
    memset(args, 0, nargs * sizeof(double));

    x = 0;
    n = 0;
    while (n < argc)
    {
        VALUE elem1 = argv[n++];
        VALUE elem2 = argv[n++];
        if (rm_check_num2dbl(elem1) && rm_check_num2dbl(elem2))
        {
            args[x++] = NUM2DBL(elem1);
            args[x++] = NUM2DBL(elem2);
        }
        else
        {
            xfree((void *) args);
            rb_raise(rb_eTypeError, "type mismatch: %s and %s given", rb_class2name(CLASS_OF(elem1)), rb_class2name(CLASS_OF(elem2)));
        }
        Color_to_MagickPixel(NULL, &pp, argv[n++]);
        if (channels & RedChannel)
        {
            args[x++] = pp.red / QuantumRange;
        }
        if (channels & GreenChannel)
        {
            args[x++] = pp.green / QuantumRange;
        }
        if (channels & BlueChannel)
        {
            args[x++] = pp.blue / QuantumRange;
        }
        if (channels & IndexChannel)
        {
            args[x++] = pp.index / QuantumRange;
        }
        if (channels & OpacityChannel)
        {
#if defined(IMAGEMAGICK_7)
            args[x++] = pp.alpha / QuantumRange;
#else
            args[x++] = pp.opacity / QuantumRange;
#endif
        }
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(SparseColorImage) args_SparseColorImage = { image, method, nargs, args, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SparseColorImage), &args_SparseColorImage);
    CHANGE_RESULT_CHANNEL_MASK(new_image);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(SparseColorImage) args_SparseColorImage = { image, channels, method, nargs, args, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SparseColorImage), &args_SparseColorImage);
#endif
    xfree((void *) args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Splice a solid color into the part of the image specified by the x, y, width,
 * and height arguments. If the color argument is specified it must be a color
 * name or Pixel.
 *
 * @overload splice(x, y, width, height, color = self.background_color)
 *   @param x [Numeric] Describe the rectangle to be spliced.
 *   @param y [Numeric] Describe the rectangle to be spliced.
 *   @param width [Numeric] Describe the rectangle to be spliced.
 *   @param height [Numeric] Describe the rectangle to be spliced.
 *   @param color [Magick::Pixel, String] The color to be spliced.
 *   @return [Magick::Image] a new image
 *   @see Image#chop
 */
VALUE
Image_splice(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    PixelColor color, old_color;
    RectangleInfo rectangle;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 4:
            // use background color
            color = image->background_color;
            break;
        case 5:
            // Convert color argument to PixelColor
            Color_to_PixelColor(&color, argv[4]);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 4 or 5)", argc);
            break;
    }

    rectangle.x      = NUM2LONG(argv[0]);
    rectangle.y      = NUM2LONG(argv[1]);
    rectangle.width  = NUM2ULONG(argv[2]);
    rectangle.height = NUM2ULONG(argv[3]);

    exception = AcquireExceptionInfo();

    // Swap in color for the duration of this call.
    old_color = image->background_color;
    image->background_color = color;
    GVL_STRUCT_TYPE(SpliceImage) args = { image, &rectangle, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SpliceImage), &args);
    image->background_color = old_color;

    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Randomly displace each pixel in a block defined by "radius".
 *
 * @overload spread(radius = 3.0)
 *   @param radius [Numeric] The radius
 *   @return [Magick::Image] a new image
 */
VALUE
Image_spread(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double radius = 3.0;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 1:
            radius = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 or 1)", argc);
            break;
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(SpreadImage) args = { image, image->interpolate, radius, exception };
#else
    GVL_STRUCT_TYPE(SpreadImage) args = { image, radius, exception };
#endif
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SpreadImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Get the Boolean value that indicates the first image in an animation.
 *
 * @return [Boolean] true or false
 */
VALUE
Image_start_loop(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, start_loop, boolean, &rm_image_data_type);
}

/**
 * Set the Boolean value that indicates the first image in an animation.
 *
 * @param val [Boolean] true or false
 * @return [Boolean] the given value
 */
VALUE
Image_start_loop_eq(VALUE self, VALUE val)
{
    IMPLEMENT_TYPED_ATTR_WRITER(Image, start_loop, boolean, &rm_image_data_type);
}


/**
 * Hides a digital watermark in the receiver. You can retrieve the watermark by reading the file
 * with the stegano: prefix, thereby proving the authenticity of the file.
 *
 * The watermarked image must be saved in a lossless RGB format such as MIFF, or PNG. You cannot
 * save a watermarked image in a lossy format such as JPEG or a pseudocolor format such as GIF. Once
 * written, the file must not be modified or processed in any way.
 *
 * @param watermark_image [Magick::Image, Magick::ImageList] Either an imagelist or an image
 * @param offset [Numeric] the start position within the image to hide the watermark.
 * @return [Magick::Image] a new image
 */
VALUE
Image_stegano(VALUE self, VALUE watermark_image, VALUE offset)
{
    Image *image, *new_image;
    VALUE wm_image;
    Image *watermark;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    wm_image = rm_cur_image(watermark_image);
    watermark = rm_check_destroyed(wm_image);

    image->offset = NUM2LONG(offset);

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(SteganoImage) args = { image, watermark, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SteganoImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);

    DestroyExceptionInfo(exception);

    RB_GC_GUARD(wm_image);

    return rm_image_new(new_image);
}


/**
 * Combine two images and produces a single image that is the composite of a left and right image of
 * a stereo pair. Special red-green stereo glasses are required to view this effect.
 *
 * @param offset_image_arg [Magick::Image, Magick::ImageList] Either an imagelist or an image.
 * @return [Magick::Image] a new image
 */
VALUE
Image_stereo(VALUE self, VALUE offset_image_arg)
{
    Image *image, *new_image;
    VALUE offset_image;
    Image *offset;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    offset_image = rm_cur_image(offset_image_arg);
    offset = rm_check_destroyed(offset_image);

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(StereoImage) args = { image, offset, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(StereoImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);

    DestroyExceptionInfo(exception);

    RB_GC_GUARD(offset_image);

    return rm_image_new(new_image);
}


/**
 * Return the image's storage class (a.k.a. storage type, class type). If DirectClass then the
 * pixels contain valid RGB or CMYK colors.  If PseudoClass then the image has a colormap referenced
 * by the pixel's index member.
 *
 * @return [Magick::ClassType] the storage class
 */
VALUE
Image_class_type(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return ClassType_find(image->storage_class);
}


/**
 * Change the image's storage class.
 *
 * @param new_class_type [Magick::ClassType] the storage class
 * @return [Magick::ClassType] the given value
 */
VALUE
Image_class_type_eq(VALUE self, VALUE new_class_type)
{
    Image *image;
    ClassType class_type;
    QuantizeInfo qinfo;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_frozen(self);

    VALUE_TO_ENUM(new_class_type, class_type, ClassType);

    if (class_type == UndefinedClass)
    {
        rb_raise(rb_eArgError, "Invalid class type specified.");
    }

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
#endif

    if (image->storage_class == PseudoClass && class_type == DirectClass)
    {
#if defined(IMAGEMAGICK_7)
        GVL_STRUCT_TYPE(SyncImage) args = { image, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SyncImage), &args);
        CHECK_EXCEPTION();
#else
        GVL_STRUCT_TYPE(SyncImage) args = { image };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SyncImage), &args);
#endif
        magick_free(image->colormap);
        image->colormap = NULL;
    }
    else if (image->storage_class == DirectClass && class_type == PseudoClass)
    {
        GetQuantizeInfo(&qinfo);
        qinfo.number_colors = QuantumRange+1;
#if defined(IMAGEMAGICK_7)
        GVL_STRUCT_TYPE(QuantizeImage) args = { &qinfo, image, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(QuantizeImage), &args);
        CHECK_EXCEPTION();
#else
        GVL_STRUCT_TYPE(QuantizeImage) args = { &qinfo, image };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(QuantizeImage), &args);
#endif
    }

#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(SetImageStorageClass) args = { image, class_type, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageStorageClass), &args);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(SetImageStorageClass) args = { image, class_type };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageStorageClass), &args);
#endif
    return new_class_type;
}


/**
 * Replace the pixels in the specified rectangle with the pixels in the pixels array.
 *
 * - This is the complement of get_pixels. The array object returned by get_pixels is suitable for
 *   use as the "new_pixels" argument.
 *
 * @param x_arg [Numeric] x position of start of region
 * @param y_arg [Numeric] y position of start of region
 * @param cols_arg [Numeric] width of region
 * @param rows_arg [Numeric] height of region
 * @param new_pixels [Array<Magick::Pixel>] the replacing pixels
 * @return [Magick::Image] self
 */
VALUE
Image_store_pixels(VALUE self, VALUE x_arg, VALUE y_arg, VALUE cols_arg,
                   VALUE rows_arg, VALUE new_pixels)
{
    Image *image;
    Pixel *pixel;
    VALUE new_pixel;
    long n, size;
    long x, y;
    unsigned long cols, rows;
    MagickBooleanType okay;
    ExceptionInfo *exception;
#if defined(IMAGEMAGICK_7)
    Quantum *pixels;
#else
    PixelPacket *pixels;
#endif

    image = rm_check_destroyed(self);

    x = NUM2LONG(x_arg);
    y = NUM2LONG(y_arg);
    cols = NUM2ULONG(cols_arg);
    rows = NUM2ULONG(rows_arg);
    if (x < 0 || y < 0 || x+cols > image->columns || y+rows > image->rows)
    {
        rb_raise(rb_eRangeError, "geometry (%lux%lu%+ld%+ld) exceeds image bounds",
                 cols, rows, x, y);
    }

    size = (long)(cols * rows);
    new_pixels = rb_Array(new_pixels);
    rm_check_ary_len(new_pixels, size);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(SetImageStorageClass) args = { image, DirectClass, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageStorageClass), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    CHECK_EXCEPTION();
    if (!okay)
    {
        DestroyExceptionInfo(exception);
        rb_raise(Class_ImageMagickError, "SetImageStorageClass failed. Can't store pixels.");
    }
#else
    GVL_STRUCT_TYPE(SetImageStorageClass) args = { image, DirectClass };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageStorageClass), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    rm_check_image_exception(image, RetainOnError);
    if (!okay)
    {
        rb_raise(Class_ImageMagickError, "SetImageStorageClass failed. Can't store pixels.");
    }
    exception = AcquireExceptionInfo();
#endif

    // Get a pointer to the pixels. Replace the values with the PixelPackets
    // from the pixels argument.
    {
        GVL_STRUCT_TYPE(GetAuthenticPixels) args = { image, x, y, cols, rows, exception };
        void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetAuthenticPixels), &args);
        pixels = reinterpret_cast<decltype(pixels)>(ret);
        CHECK_EXCEPTION();

        if (pixels)
        {
#if defined(IMAGEMAGICK_6)
            IndexPacket *indexes = GetAuthenticIndexQueue(image);
#endif
            for (n = 0; n < size; n++)
            {
                new_pixel = rb_ary_entry(new_pixels, n);
                if (CLASS_OF(new_pixel) != Class_Pixel)
                {
                    DestroyExceptionInfo(exception);
                    rb_raise(rb_eTypeError, "Item in array should be a Pixel.");
                }
                TypedData_Get_Struct(new_pixel, Pixel, &rm_pixel_data_type, pixel);
#if defined(IMAGEMAGICK_7)
                SetPixelRed(image,   pixel->red,   pixels);
                SetPixelGreen(image, pixel->green, pixels);
                SetPixelBlue(image,  pixel->blue,  pixels);
                SetPixelAlpha(image, pixel->alpha, pixels);
                SetPixelBlack(image, pixel->black, pixels);
                pixels += GetPixelChannels(image);
#else
                SetPixelRed(pixels, pixel->red);
                SetPixelGreen(pixels, pixel->green);
                SetPixelBlue(pixels, pixel->blue);
                SetPixelOpacity(pixels, pixel->opacity);
                if (indexes)
                {
                    SetPixelIndex(indexes + n, pixel->black);
                }
                pixels++;
#endif
            }
            GVL_STRUCT_TYPE(SyncAuthenticPixels) args = { image, exception };
            CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SyncAuthenticPixels), &args);
            CHECK_EXCEPTION();
        }

        DestroyExceptionInfo(exception);
    }

    RB_GC_GUARD(new_pixel);

    return self;
}


/**
 * Strips an image of all profiles and comments.
 *
 * @return [Magick::Image] self
 */
VALUE
Image_strip_bang(VALUE self)
{
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    Image *image = rm_check_frozen(self);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    StripImage(image, exception);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    StripImage(image);
    rm_check_image_exception(image, RetainOnError);
#endif
    return self;
}


/**
 * Swirl the pixels about the center of the image, where degrees indicates the sweep of the arc
 * through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to
 * 360.
 *
 * @param degrees_obj [Numeric] the degrees
 * @return [Magick::Image] a new image
 */
VALUE
Image_swirl(VALUE self, VALUE degrees_obj)
{
    Image *image, *new_image;
    ExceptionInfo *exception;
    double degrees = NUM2DBL(degrees_obj);

    image = rm_check_destroyed(self);

    exception = AcquireExceptionInfo();

#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(SwirlImage) args = { image, degrees, image->interpolate, exception };
#else
    GVL_STRUCT_TYPE(SwirlImage) args = { image, degrees, exception };
#endif
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SwirlImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Emulates Magick++'s floodFillTexture.
 *
 * If the FloodfillMethod method is specified, flood-fills texture across pixels starting at the
 * target pixel and matching the specified color.
 *
 * If the FillToBorderMethod method is specified, flood-fills 'texture across pixels starting at the
 * target pixel and stopping at pixels matching the specified color.'
 *
 * @param color_obj [Magick::Pixel, String] the color
 * @param texture_obj [Magick::Image, Magick::ImageList] the texture to fill
 * @param x_obj [Numeric] the x position
 * @param y_obj [Numeric] the y position
 * @param method_obj [Magick::PaintMethod] the method to call (FloodfillMethod or FillToBorderMethod)
 * @return [Magick::Image] a new image
 */
VALUE
Image_texture_flood_fill(VALUE self, VALUE color_obj, VALUE texture_obj,
                         VALUE x_obj, VALUE y_obj, VALUE method_obj)
{
    Image *image, *new_image;
    Image *texture_image;
    PixelColor color;
    VALUE texture;
    DrawInfo *draw_info;
    long x, y;
    PaintMethod method;
    MagickPixel color_mpp;
    MagickBooleanType invert;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

    Color_to_PixelColor(&color, color_obj);
    texture = rm_cur_image(texture_obj);
    texture_image = rm_check_destroyed(texture);

    x = NUM2LONG(x_obj);
    y = NUM2LONG(y_obj);

    if ((unsigned long)x > image->columns || (unsigned long)y > image->rows)
    {
        rb_raise(rb_eArgError, "target out of range. %ldx%ld given, image is %" RMIuSIZE "x%" RMIuSIZE "",
                 x, y, image->columns, image->rows);
    }

    VALUE_TO_ENUM(method_obj, method, PaintMethod);
    if (method != FillToBorderMethod && method != FloodfillMethod)
    {
        rb_raise(rb_eArgError, "paint method must be FloodfillMethod or "
                 "FillToBorderMethod (%d given)", (int)method);
    }

    draw_info = CloneDrawInfo(NULL, NULL);
    if (!draw_info)
    {
        rb_raise(rb_eNoMemError, "not enough memory to continue");
    }

    draw_info->fill_pattern = rm_clone_image(texture_image);
    new_image = rm_clone_image(image);


    rm_init_magickpixel(new_image, &color_mpp);
    if (method == FillToBorderMethod)
    {
        invert = MagickTrue;
        color_mpp.red   = (MagickRealType) image->border_color.red;
        color_mpp.green = (MagickRealType) image->border_color.green;
        color_mpp.blue  = (MagickRealType) image->border_color.blue;
    }
    else
    {
        invert = MagickFalse;
        color_mpp.red   = (MagickRealType) color.red;
        color_mpp.green = (MagickRealType) color.green;
        color_mpp.blue  = (MagickRealType) color.blue;
    }

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(FloodfillPaintImage) args = { new_image, draw_info, &color_mpp, x, y, invert, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(FloodfillPaintImage), &args);
    DestroyDrawInfo(draw_info);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(FloodfillPaintImage) args = { new_image, DefaultChannels, draw_info, &color_mpp, x, y, invert };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(FloodfillPaintImage), &args);

    DestroyDrawInfo(draw_info);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    RB_GC_GUARD(texture);

    return rm_image_new(new_image);
}


/**
 * Change the value of individual pixels based on the intensity of each pixel compared to
 * threshold. The result is a high-contrast, two color image.
 *
 * @param threshold_obj [Numeric] the threshold
 * @return [Magick::Image] a new image
 */
VALUE
Image_threshold(VALUE self, VALUE threshold_obj)
{
    Image *image, *new_image;
    double threshold = NUM2DBL(threshold_obj);
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(BilevelImage) args = { new_image, threshold, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(BilevelImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(BilevelImageChannel) args = { new_image, DefaultChannels, threshold };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(BilevelImageChannel), &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


// aliases for common use of structure types; WhiteThresholdImage
typedef GVL_STRUCT_TYPE(WhiteThresholdImage) GVL_STRUCT_TYPE(threshold_image);

/**
 * Call one of the xxxxThresholdImage methods.
 *
 * No Ruby usage (internal function)
 *
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @param thresholder which xxxxThresholdImage method to call
 * @return a new image
 */
static VALUE
threshold_image(int argc, VALUE *argv, VALUE self, gvl_function_t fp)
{
    Image *image, *new_image;
    double red, green, blue, alpha;
    char ctarg[200];
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 4:
            red     = NUM2DBL(argv[0]);
            green   = NUM2DBL(argv[1]);
            blue    = NUM2DBL(argv[2]);
            alpha   = get_named_alpha_value(argv[3]);
            snprintf(ctarg, sizeof(ctarg), "%f,%f,%f,%f", red, green, blue, QuantumRange - alpha);
            break;
        case 3:
            red     = NUM2DBL(argv[0]);
            green   = NUM2DBL(argv[1]);
            blue    = NUM2DBL(argv[2]);
            snprintf(ctarg, sizeof(ctarg), "%f,%f,%f", red, green, blue);
            break;
        case 2:
            red     = NUM2DBL(argv[0]);
            green   = NUM2DBL(argv[1]);
            snprintf(ctarg, sizeof(ctarg), "%f,%f", red, green);
            break;
        case 1:
            red     = NUM2DBL(argv[0]);
            snprintf(ctarg, sizeof(ctarg), "%f", red);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 to 4)", argc);
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(threshold_image) args = { new_image, ctarg, exception };
    CALL_FUNC_WITHOUT_GVL(fp, &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(threshold_image) args = { new_image, ctarg };
    CALL_FUNC_WITHOUT_GVL(fp, &args);
    rm_check_image_exception(new_image, DestroyOnError);
#endif

    return rm_image_new(new_image);
}


/**
 * Fast resize for thumbnail images.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - Uses BoxFilter, blur attribute of input image
 *
 * @param bang whether the bang (!) version of the method was called
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @return self if bang, otherwise a new image
 * @see Image_thumbnail
 * @see Image_thumbnail_bang
 */
static VALUE
thumbnail(int bang, int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    unsigned long columns, rows;
    double scale_arg, drows, dcols;
    char image_geometry[MaxTextExtent];
    RectangleInfo geometry;
    ExceptionInfo *exception;

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);

    switch (argc)
    {
        case 2:
            columns = NUM2ULONG(argv[0]);
            rows = NUM2ULONG(argv[1]);
            if (columns == 0 || rows == 0)
            {
                rb_raise(rb_eArgError, "invalid result dimension (%lu, %lu given)", columns, rows);
            }
            break;
        case 1:
            scale_arg = NUM2DBL(argv[0]);
            if (scale_arg < 0.0)
            {
                rb_raise(rb_eArgError, "invalid scale value (%g given)", scale_arg);
            }
            drows = scale_arg * image->rows + 0.5;
            dcols = scale_arg * image->columns + 0.5;
            if (drows > (double)ULONG_MAX || dcols > (double)ULONG_MAX)
            {
                rb_raise(rb_eRangeError, "resized image too big");
            }
            rows = (unsigned long) drows;
            columns = (unsigned long) dcols;
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or 2)", argc);
            break;
    }

    snprintf(image_geometry, sizeof(image_geometry), "%lux%lu", columns, rows);

    exception = AcquireExceptionInfo();
    ParseRegionGeometry(image, image_geometry, &geometry, exception);
    rm_check_exception(exception, image, RetainOnError);

    GVL_STRUCT_TYPE(ThumbnailImage) args = { image, geometry.width, geometry.height, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ThumbnailImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    if (bang)
    {
        rm_ensure_result(new_image);
        UPDATE_DATA_PTR(self, new_image);
        rm_image_destroy(image);
        return self;
    }

    return rm_image_new(new_image);
}


/**
 * The thumbnail method is a fast resizing method suitable for use when the size of the resulting
 * image is < 10% of the original.
 *
 * @overload thumbnail(scale)
 *   @param scale [Numeric] The desired size represented as a floating-point number. For example, to
 *     make a thumbnail that is 9.5% of the size of the original image, use 0.095.
 *
 * @overload thumbnail(cols, rows)
 *   @param cols [Numeric] The desired width in pixels.
 *   @param rows [Numeric] The desired height.
 *
 * @return [Magick::Image] a new image
 * @see Image#thumbnail!
 */
VALUE
Image_thumbnail(int argc, VALUE *argv, VALUE self)
{
    rm_check_destroyed(self);
    return thumbnail(False, argc, argv, self);
}


/**
 * The thumbnail method is a fast resizing method suitable for use when the size of the resulting
 * image is < 10% of the original.  In-place form of {Image#thumbnail}.
 *
 * @overload thumbnail!(scale)
 *   @param scale [Numeric] The desired size represented as a floating-point number. For example, to
 *     make a thumbnail that is 9.5% of the size of the original image, use 0.095.
 *
 * @overload thumbnail!(cols, rows)
 *   @param cols [Numeric] The desired width in pixels.
 *   @param rows [Numeric] The desired height.
 *
 * @return [Magick::Image] a new image
 * @see Image#thumbnail
 */
VALUE
Image_thumbnail_bang(int argc, VALUE *argv, VALUE self)
{
    rm_check_frozen(self);
    return thumbnail(True, argc, argv, self);
}


/**
 * Get the number of ticks per second.
 * This attribute is used in conjunction with the delay attribute to establish the amount of time
 * that must elapse between frames in an animation.The default is 100.
 *
 * @return [Integer] ticks per second
 */
VALUE
Image_ticks_per_second(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return INT2FIX(image->ticks_per_second);
}


/**
 * Set the number of ticks per second.
 * This attribute is used in conjunction with the delay attribute to establish the amount of time
 * that must elapse between frames in an animation.The default is 100.
 *
 * @param tps [Numeric] ticks per second
 * @return [Numeric] the given value
 */
VALUE
Image_ticks_per_second_eq(VALUE self, VALUE tps)
{
    Image *image = rm_check_frozen(self);
    image->ticks_per_second = NUM2ULONG(tps);
    return tps;
}


/**
 * Applies a color vector to each pixel in the image.
 *
 * - Alpha values are percentages: 0.10 -> 10%.
 *
 * @overload tint(tint, red_alpha, green_alpha = red_alpha, blue_alpha = red_alpha, alpha_alpha = 1.0)
 *   @param tint [Magick::Pixel, String] the color name
 *   @param red_alpha [Numeric] the red value
 *   @param green_alpha [Numeric] the green value
 *   @param blue_alpha [Numeric] the blue value
 *   @param alpha_alpha [Numeric] the alpha value
 *   @return a new image
 */
VALUE
Image_tint(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    PixelColor tint;
    double red_pct_opaque, green_pct_opaque, blue_pct_opaque;
    double alpha_pct_opaque = 1.0;
    char alpha[50];
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 2:
            red_pct_opaque   = NUM2DBL(argv[1]);
            green_pct_opaque = blue_pct_opaque = red_pct_opaque;
            break;
        case 3:
            red_pct_opaque   = NUM2DBL(argv[1]);
            green_pct_opaque = NUM2DBL(argv[2]);
            blue_pct_opaque  = red_pct_opaque;
            break;
        case 4:
            red_pct_opaque     = NUM2DBL(argv[1]);
            green_pct_opaque   = NUM2DBL(argv[2]);
            blue_pct_opaque    = NUM2DBL(argv[3]);
            break;
        case 5:
            red_pct_opaque     = NUM2DBL(argv[1]);
            green_pct_opaque   = NUM2DBL(argv[2]);
            blue_pct_opaque    = NUM2DBL(argv[3]);
            alpha_pct_opaque   = NUM2DBL(argv[4]);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 to 5)", argc);
            break;
    }

    if (red_pct_opaque < 0.0 || green_pct_opaque < 0.0
        || blue_pct_opaque < 0.0 || alpha_pct_opaque < 0.0)
    {
        rb_raise(rb_eArgError, "alpha percentages must be non-negative.");
    }

    snprintf(alpha, sizeof(alpha),
            "%g,%g,%g,%g", red_pct_opaque*100.0, green_pct_opaque*100.0,
            blue_pct_opaque*100.0, alpha_pct_opaque*100.0);

    Color_to_PixelColor(&tint, argv[0]);
    exception = AcquireExceptionInfo();

#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(TintImage) args = { image, alpha, &tint, exception };
#else
    GVL_STRUCT_TYPE(TintImage) args = { image, alpha, tint, exception };
#endif
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(TintImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Return a "blob" (a String) from the image.
 *
 * - The magick member of the Image structure determines the format of the
 *   returned blob (GIG, JPEG,  PNG, etc.)
 *
 * @yield [info]
 * @yieldparam info [Magick::Image::Info]
 * @return [String] the blob
 * @see Image#from_blob
 */
VALUE
Image_to_blob(VALUE self)
{
    Image *image;
    Info *info;
    const MagickInfo *magick_info;
    VALUE info_obj;
    VALUE blob_str;
    void *blob = NULL;
    size_t length = 2048;       // Do what Magick++ does
    ExceptionInfo *exception;

    // The user can specify the depth (8 or 16, if the format supports
    // both) and the image format by setting the depth and format
    // values in the info parm block.
    info_obj = rm_info_new();
    TypedData_Get_Struct(info_obj, Info, &rm_info_data_type, info);

    image = rm_check_destroyed(self);

    exception = AcquireExceptionInfo();

    // Copy the depth and magick fields to the Image
    if (info->depth != 0)
    {
#if defined(IMAGEMAGICK_7)
        GVL_STRUCT_TYPE(SetImageDepth) args = { image, info->depth, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageDepth), &args);
        CHECK_EXCEPTION();
#else
        GVL_STRUCT_TYPE(SetImageDepth) args = { image, info->depth };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageDepth), &args);
        rm_check_image_exception(image, RetainOnError);
#endif
    }

    if (*info->magick)
    {
        SetImageInfo(info, MagickTrue, exception);
        CHECK_EXCEPTION();

        if (*info->magick == '\0')
        {
            return Qnil;
        }
        strlcpy(image->magick, info->magick, sizeof(image->magick));
    }

    // Fix #2844 - libjpeg exits when image is 0x0
    magick_info = GetMagickInfo(image->magick, exception);
    CHECK_EXCEPTION();

    if (magick_info)
    {
        if (  (!rm_strcasecmp(magick_info->name, "JPEG")
               || !rm_strcasecmp(magick_info->name, "JPG"))
              && (image->rows == 0 || image->columns == 0))
        {
            rb_raise(rb_eRuntimeError, "Can't convert %" RMIuSIZE "x%" RMIuSIZE " %.4s image to a blob",
                     image->columns, image->rows, magick_info->name);
        }
    }

    rm_sync_image_options(image, info);

    GVL_STRUCT_TYPE(ImageToBlob) args = { info, image, &length, exception };
    blob = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(ImageToBlob), &args);
    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    if (length == 0 || !blob)
    {
        return Qnil;
    }

    blob_str = rb_str_new((const char *)blob, length);

    magick_free((void*)blob);

    RB_GC_GUARD(info_obj);
    RB_GC_GUARD(blob_str);

    return blob_str;
}


/**
 * Return a color name for the color intensity specified by the Magick::Pixel argument.
 *
 * @param pixel_arg [Magick::Pixel, String] the pixel
 * @return [String] the color name
 */
VALUE
Image_to_color(VALUE self, VALUE pixel_arg)
{
    Image *image;
    PixelColor pixel;
    ExceptionInfo *exception;
    char name[MaxTextExtent];

    image = rm_check_destroyed(self);
    Color_to_PixelColor(&pixel, pixel_arg);
    exception = AcquireExceptionInfo();

#if defined(IMAGEMAGICK_7)
    pixel.depth = MAGICKCORE_QUANTUM_DEPTH;
    pixel.colorspace = image->colorspace;
#endif

    // QueryColorname returns False if the color represented by the PixelPacket
    // doesn't have a "real" name, just a sequence of hex digits. We don't care
    // about that.

    QueryColorname(image, &pixel, AllCompliance, name, exception);
    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);

    return rb_str_new2(name);

}


/**
 * Alias for {Image#number_colors}.
 *
 * @return [Integer] number of unique colors
 * @see Image#number_colors
 */
VALUE
Image_total_colors(VALUE self)
{
    return Image_number_colors(self);
}


/**
 * Return the total ink density for a CMYK image.
 *
 * @return [Float] the total ink density
 */
VALUE
Image_total_ink_density(VALUE self)
{
    Image *image;
    double density;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    density = GetImageTotalInkDensity(image, exception);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    density = GetImageTotalInkDensity(image);
    rm_check_image_exception(image, RetainOnError);
#endif

    return rb_float_new(density);
}


/**
 * Changes the opacity value of all the pixels that match color to the value specified by
 * opacity. By default the pixel must match exactly, but you can specify a tolerance level by
 * setting the fuzz attribute on the image.
 *
 * - Default alpha is Magick::TransparentAlpha.
 * - Can use Magick::OpaqueAlpha or Magick::TransparentAlpha, or any
 *   value >= 0 && <= QuantumRange.
 * - Use Image#fuzz= to define the tolerance level.
 *
 * @overload transparent(color, alpha: Magick::TransparentAlpha)
 *   @param color [Magick::Pixel, String] The color
 *   @param alpha alpha [Numeric] the alpha
 *   @return [Magick::Image] a new image
 */
VALUE
Image_transparent(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    MagickPixel color;
    Quantum alpha = TransparentAlpha;
    MagickBooleanType okay;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif


    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 2:
            alpha = get_named_alpha_value(argv[1]);
        case 1:
            Color_to_MagickPixel(image, &color, argv[0]);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or 2)", argc);
            break;
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(TransparentPaintImage) args = { new_image, &color, alpha, MagickFalse, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(TransparentPaintImage), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(TransparentPaintImage) args = { new_image, &color, (Quantum)(QuantumRange - alpha), MagickFalse };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(TransparentPaintImage), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    rm_check_image_exception(new_image, DestroyOnError);
#endif
    if (!okay)
    {
        // Force exception
        DestroyImage(new_image);
        rm_magick_error("TransparentPaintImage failed with no explanation");
    }

    return rm_image_new(new_image);
}


/**
 * Changes the opacity value associated with any pixel between low and high to the value defined by
 * opacity.
 *
 * As there is one fuzz value for the all the channels, the transparent method is not suitable for
 * the operations like chroma, where the tolerance for similarity of two color components (RGB) can
 * be different, Thus we define this method take two target pixels (one low and one high) and all
 * the pixels of an image which are lying between these two pixels are made transparent.
 *
 * @overload transparent_chroma(low, high, invert, alpha: Magick::TransparentAlpha)
 *   @param low [Magick::Pixel, String] The low ends of the pixel range
 *   @param high [Magick::Pixel, String] The high ends of the pixel range
 *   @param invert [Boolean] If true, all pixels outside the range are set to opacity.
 *   @param alpha [Numeric] The desired alpha.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_transparent_chroma(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    Quantum alpha = TransparentAlpha;
    MagickPixel low, high;
    MagickBooleanType invert = MagickFalse;
    MagickBooleanType okay;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

    switch (argc)
    {
        case 4:
            if (TYPE(argv[argc - 1]) == T_HASH)
            {
                invert = (MagickBooleanType)RTEST(argv[3]);
            }
            else
            {
                invert = (MagickBooleanType)RTEST(argv[2]);
            }
        case 3:
            alpha = get_named_alpha_value(argv[argc - 1]);
        case 2:
            Color_to_MagickPixel(image, &high, argv[1]);
            Color_to_MagickPixel(image, &low, argv[0]);
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 2, 3 or 4)", argc);
            break;
    }

    new_image = rm_clone_image(image);

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(TransparentPaintImageChroma) args = { new_image, &low, &high, alpha, invert, exception };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(TransparentPaintImageChroma), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(TransparentPaintImageChroma) args = { new_image, &low, &high, (Quantum)(QuantumRange - alpha), invert };
    void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(TransparentPaintImageChroma), &args);
    okay = static_cast<MagickBooleanType>(reinterpret_cast<intptr_t &>(ret));
    rm_check_image_exception(new_image, DestroyOnError);
#endif
    if (!okay)
    {
        // Force exception
        DestroyImage(new_image);
        rm_magick_error("TransparentPaintImageChroma failed with no explanation");
    }

    return rm_image_new(new_image);
}


/**
 * Return the name of the transparent color as a String.
 *
 * @return [String] the name of the transparent color
 */
VALUE
Image_transparent_color(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return rm_pixelcolor_to_color_name(image, &image->transparent_color);
}


/**
 * Set the the transparent color to the specified color spec.
 *
 * @param color [Magick::Pixel, String] the transparent color
 * @return [Magick::Pixel, String] the given color
 */
VALUE
Image_transparent_color_eq(VALUE self, VALUE color)
{
    Image *image = rm_check_frozen(self);
    Color_to_PixelColor(&image->transparent_color, color);
    return color;
}


/**
 * Creates a horizontal mirror image by reflecting the pixels around the central y-axis while
 * rotating them by 90 degrees.
 *
 * @return [Magick::Image] a new image
 * @see Image#transpose!
 */
VALUE
Image_transpose(VALUE self)
{
    rm_check_destroyed(self);
    return crisscross(False, self, GVL_FUNC(TransposeImage));
}


/**
 * Creates a horizontal mirror image by reflecting the pixels around the central y-axis while
 * rotating them by 90 degrees.
 * In-place form of {Image#transpose}.
 *
 * @return [Magick::Image] self
 * @see Image#transpose
 */
VALUE
Image_transpose_bang(VALUE self)
{
    rm_check_frozen(self);
    return crisscross(True, self, GVL_FUNC(TransposeImage));
}


/**
 * Creates a vertical mirror image by reflecting the pixels around the central x-axis while rotating
 * them by 270 degrees
 *
 * @return [Magick::Image] a new image
 * @see Image#transverse!
 */
VALUE
Image_transverse(VALUE self)
{
    rm_check_destroyed(self);
    return crisscross(False, self, GVL_FUNC(TransverseImage));
}

/**
 * Creates a vertical mirror image by reflecting the pixels around the central x-axis while rotating
 * them by 270 degrees
 * In-place form of {Image#transverse}.
 *
 * @return [Magick::Image] self
 * @see Image#transverse
 */
VALUE
Image_transverse_bang(VALUE self)
{
    rm_check_frozen(self);
    return crisscross(True, self, GVL_FUNC(TransverseImage));
}


/**
 * Convenient front-end to CropImage.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - Respects fuzz attribute.
 *
 * @param bang whether the bang (!) version of the method was called
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @return self if bang, otherwise a new image
 * @see Image_trim
 * @see Image_trim_bang
 */
static VALUE
trimmer(int bang, int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ExceptionInfo *exception;
    int reset_page = 0;

    switch (argc)
    {
        case 1:
            reset_page = RTEST(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (expecting 0 or 1, got %d)", argc);
            break;
    }

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(TrimImage) args = { image, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(TrimImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    rm_ensure_result(new_image);

    if (reset_page)
    {
        ResetImagePage(new_image, "0x0+0+0");
    }

    if (bang)
    {
        UPDATE_DATA_PTR(self, new_image);
        rm_image_destroy(image);
        return self;
    }

    return rm_image_new(new_image);
}


/**
 * Removes the edges that are exactly the same color as the corner pixels. Use the fuzz attribute to
 * make trim remove edges that are nearly the same color as the corner pixels.
 *
 * @overload trim(reset = false)
 *   @param reset [Boolean] The trim method retains the offset information in the cropped
 *     image. This may cause the image to appear to be surrounded by blank or black space when viewed
 *     with an external viewer. This only occurs when the image is saved in a format (such as GIF)
 *     that saves offset information. To reset the offset data, use true as the argument to trim.
 *   @return [Magick::Image] a new image
 *   @see Image#trim!
 */
VALUE
Image_trim(int argc, VALUE *argv, VALUE self)
{
    rm_check_destroyed(self);
    return trimmer(False, argc, argv, self);
}


/**
 * Removes the edges that are exactly the same color as the corner pixels. Use the fuzz attribute to
 * make trim remove edges that are nearly the same color as the corner pixels.
 *
 * @overload trim!(reset = false)
 *   @param reset [Boolean] The trim method retains the offset information in the cropped
 *     image. This may cause the image to appear to be surrounded by blank or black space when viewed
 *     with an external viewer. This only occurs when the image is saved in a format (such as GIF)
 *     that saves offset information. To reset the offset data, use true as the argument to trim.
 *   @return [Magick::Image] self
 *   @see Image#trim
 */
VALUE
Image_trim_bang(int argc, VALUE *argv, VALUE self)
{
    rm_check_frozen(self);
    return trimmer(True, argc, argv, self);
}


/**
 * Get the direction that the image gravitates within the composite.
 *
 * @return [Magick::GravityType] the image gravity
 */
VALUE Image_gravity(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return GravityType_find(image->gravity);
}


/**
 * Set the direction that the image gravitates within the composite.
 *
 * @param gravity [Magick::GravityType] the image gravity
 * @return [Magick::GravityType] the given value
 */
VALUE Image_gravity_eq(VALUE self, VALUE gravity)
{
    Image *image = rm_check_frozen(self);
    VALUE_TO_ENUM(gravity, image->gravity, GravityType);
    return gravity;
}


/**
 * Get the image type classification.
 * For example, GrayscaleType.
 * Don't confuse this attribute with the format, that is "GIF" or "JPG".
 *
 * @return [Magick::ImageType] the image type
 */
VALUE Image_image_type(VALUE self)
{
    Image *image;
    ImageType type;
#if defined(IMAGEMAGICK_6)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);
#if defined(IMAGEMAGICK_7)
    type = GetImageType(image);
#else
    exception = AcquireExceptionInfo();
    type = GetImageType(image, exception);
    CHECK_EXCEPTION();

    DestroyExceptionInfo(exception);
#endif

    return ImageType_find(type);
}


/**
 * Set the image type classification.
 *
 * @param image_type [Magick::ImageType] the image type
 * @return [Magick::ImageType] the given type
 */
VALUE Image_image_type_eq(VALUE self, VALUE image_type)
{
    Image *image;
    ImageType type;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_frozen(self);
    VALUE_TO_ENUM(image_type, type, ImageType);
#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    SetImageType(image, type, exception);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    SetImageType(image, type);
#endif
    return image_type;
}


/**
 * Removes an artifact from the image and returns its value.
 *
 * @param artifact [String] the artifact
 * @return [Magick::Image] self
 * @see Image#define
 */
VALUE
Image_undefine(VALUE self, VALUE artifact)
{
    Image *image;
    char *key;

    image = rm_check_frozen(self);
    key = StringValueCStr(artifact);
    DeleteImageArtifact(image, key);
    return self;
}


/**
 * Constructs a new image with one pixel for each unique color in the image. The new image has 1
 * row. The row has 1 column for each unique pixel in the image.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_unique_colors(VALUE self)
{
    Image *image, *new_image;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(UniqueImageColors) args = { image, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(UniqueImageColors), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Get the units of image resolution.
 *
 * @return [Magick::ResolutionType] the resolution type
 */
VALUE
Image_units(VALUE self)
{
    Image *image = rm_check_destroyed(self);
    return ResolutionType_find(image->units);
}


/**
 * Set the units of image resolution.
 *
 * @param restype [Magick::ResolutionType] the resolution type
 * @return [Magick::ResolutionType] the given value
 */
VALUE
Image_units_eq(VALUE self, VALUE restype)
{
    ResolutionType units;
    Image *image = rm_check_frozen(self);

    VALUE_TO_ENUM(restype, units, ResolutionType);

    if (image->units != units)
    {
        switch (image->units)
        {
            case PixelsPerInchResolution:
                if (units == PixelsPerCentimeterResolution)
                {
#if defined(IMAGEMAGICK_7)
                    image->resolution.x /= 2.54;
                    image->resolution.y /= 2.54;
#else
                    image->x_resolution /= 2.54;
                    image->y_resolution /= 2.54;
#endif
                }
                break;

            case PixelsPerCentimeterResolution:
                if (units == PixelsPerInchResolution)
                {
#if defined(IMAGEMAGICK_7)
                    image->resolution.x *= 2.54;
                    image->resolution.y *= 2.54;
#else
                    image->x_resolution *= 2.54;
                    image->y_resolution *= 2.54;
#endif
                }
                break;

            default:
                // UndefinedResolution
#if defined(IMAGEMAGICK_7)
                image->resolution.x = 0.0;
                image->resolution.y = 0.0;
#else
                image->x_resolution = 0.0;
                image->y_resolution = 0.0;
#endif
                break;
        }

        image->units = units;
    }

    return restype;
}


/**
 * Sharpen an image. "amount" is the percentage of the difference between the original and the blur
 * image that is added back into the original. "threshold" is the threshold in pixels needed to
 * apply the diffence amount.
 *
 * No Ruby usage (internal function)
 *
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param radious the radious
 * @param sigma the sigma
 * @param amount the amount
 * @param threshold the threshold
 * @see Image_unsharp_mask
 */
static void
unsharp_mask_args(int argc, VALUE *argv, double *radius, double *sigma,
                  double *amount, double *threshold)
{
    switch (argc)
    {
        case 4:
            *threshold = NUM2DBL(argv[3]);
            if (*threshold < 0.0)
            {
                rb_raise(rb_eArgError, "threshold must be >= 0.0");
            }
        case 3:
            *amount = NUM2DBL(argv[2]);
            if (*amount <= 0.0)
            {
                rb_raise(rb_eArgError, "amount must be > 0.0");
            }
        case 2:
            *sigma = NUM2DBL(argv[1]);
            if (*sigma == 0.0)
            {
                rb_raise(rb_eArgError, "sigma must be != 0.0");
            }
        case 1:
            *radius = NUM2DBL(argv[0]);
            if (*radius < 0.0)
            {
                rb_raise(rb_eArgError, "radius must be >= 0.0");
            }
        case 0:
            break;

            // This case can't occur if we're called from Image_unsharp_mask_channel
            // because it has already raised an exception for the the argc > 4 case.
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 4)", argc);
    }
}


/**
 * Sharpen an image. "amount" is the percentage of the difference between the original and the blur
 * image that is added back into the original. "threshold" is the threshold in pixels needed to
 * apply the diffence amount.
 *
 * @overload unsharp_mask(radius = 0.0, sigma = 1.0, amount = 1.0, threshold = 0.05)
 *   @param radius [Numeric] The radius of the Gaussian operator.
 *   @param sigma [Numeric] The standard deviation of the Gaussian operator.
 *   @param amount [Numeric] The percentage of the blurred image to be added to the receiver,
 *     specified as a fraction between 0 and 1.0
 *   @param threshold [Numeric] The threshold needed to apply the amount, specified as a fraction
 *     between 0 and 1.0
 *   @return [Magick::Image] a new image
 */
VALUE
Image_unsharp_mask(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double radius = 0.0, sigma = 1.0, amount = 1.0, threshold = 0.05;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    unsharp_mask_args(argc, argv, &radius, &sigma, &amount, &threshold);

    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(UnsharpMaskImage) args = { image, radius, sigma, amount, threshold, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(UnsharpMaskImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Sharpen an image. "amount" is the percentage of the difference between the original and the blur
 * image that is added back into the original. "threshold" is the threshold in pixels needed to
 * apply the diffence amount.
 *
 * Only the specified channels are sharpened.
 *
 * @overload unsharp_mask(radius = 0.0, sigma = 1.0, amount = 1.0, threshold = 0.05, channel = Magick::AllChannels)
 *   @param radius [Numeric] The radius of the Gaussian operator.
 *   @param sigma [Numeric] The standard deviation of the Gaussian operator.
 *   @param amount [Numeric] The percentage of the blurred image to be added to the receiver,
 *     specified as a fraction between 0 and 1.0
 *   @param threshold [Numeric] The threshold needed to apply the amount, specified as a fraction
 *     between 0 and 1.0
 *   @param channel [Magick::ChannelType] a ChannelType arguments.
 *
 * @overload unsharp_mask(radius = 0.0, sigma = 1.0, amount = 1.0, threshold = 0.05, *channels)
 *   @param radius [Numeric] The radius of the Gaussian operator.
 *   @param sigma [Numeric] The standard deviation of the Gaussian operator.
 *   @param amount [Numeric] The percentage of the blurred image to be added to the receiver,
 *     specified as a fraction between 0 and 1.0
 *   @param threshold [Numeric] The threshold needed to apply the amount, specified as a fraction
 *     between 0 and 1.0
 *   @param *channels [Magick::ChannelType] one or more ChannelType arguments.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_unsharp_mask_channel(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    ChannelType channels;
    double radius = 0.0, sigma = 1.0, amount = 1.0, threshold = 0.05;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    channels = extract_channels(&argc, argv);
    if (argc > 4)
    {
        raise_ChannelType_error(argv[argc-1]);
    }

    unsharp_mask_args(argc, argv, &radius, &sigma, &amount, &threshold);

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    BEGIN_CHANNEL_MASK(image, channels);
    GVL_STRUCT_TYPE(UnsharpMaskImage) args = { image, radius, sigma, amount, threshold, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(UnsharpMaskImage), &args);
    CHANGE_RESULT_CHANNEL_MASK(new_image);
    END_CHANNEL_MASK(image);
#else
    GVL_STRUCT_TYPE(UnsharpMaskImageChannel) args = { image, channels, radius, sigma, amount, threshold, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(UnsharpMaskImageChannel), &args);
#endif
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Soften the edges of an image.
 *
 * @overload vignette(horz_radius = self.columns*0.1+0.5, vert_radius = self.rows*0.1+0.5, radius = 0.0, sigma = 1.0)
 *   @param horz_radius [Numeric] Influences the amount of background color in the horizontal dimension.
 *   @param vert_radius [Numeric] Influences the amount of background color in the vertical dimension.
 *   @param radius [Numeric] Controls the amount of blurring.
 *   @param sigma [Numeric] Controls the amount of blurring.
 *   @return [Magick::Image] a new image
 */
VALUE
Image_vignette(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    long horz_radius, vert_radius;
    double radius = 0.0, sigma = 10.0;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);

    horz_radius = (long)(image->columns * 0.10 + 0.5);
    vert_radius = (long)(image->rows * 0.10 + 0.5);

    switch (argc)
    {
        case 4:
            sigma = NUM2DBL(argv[3]);
        case 3:
            radius = NUM2DBL(argv[2]);
        case 2:
            vert_radius = NUM2INT(argv[1]);
        case 1:
            horz_radius = NUM2INT(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 4)", argc);
            break;
    }

    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(VignetteImage) args = { image, radius, sigma, horz_radius, vert_radius, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(VignetteImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Get the "virtual pixels" behave.
 * Virtual pixels are pixels that are outside the boundaries of the image.
 *
 * @return [Magick::VirtualPixelMethod] the VirtualPixelMethod
 */
VALUE
Image_virtual_pixel_method(VALUE self)
{
    Image *image;
    VirtualPixelMethod vpm;

    image = rm_check_destroyed(self);
    vpm = GetImageVirtualPixelMethod(image);
    return VirtualPixelMethod_find(vpm);
}


/**
 * Specify how "virtual pixels" behave.
 * Virtual pixels are pixels that are outside the boundaries of the image.
 *
 * @param method [Magick::VirtualPixelMethod] the VirtualPixelMethod
 * @return [Magick::VirtualPixelMethod] the given method
 */
VALUE
Image_virtual_pixel_method_eq(VALUE self, VALUE method)
{
    Image *image;
    VirtualPixelMethod vpm;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_frozen(self);
    VALUE_TO_ENUM(method, vpm, VirtualPixelMethod);
#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    SetImageVirtualPixelMethod(image, vpm, exception);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    SetImageVirtualPixelMethod(image, vpm);
    rm_check_image_exception(image, RetainOnError);
#endif
    return method;
}


/**
 * Composites a watermark image on the target image using the Modulate composite operator. This
 * composite operation operates in the HSL colorspace and combines part of the lightness, part of
 * the saturation, and all of the hue of each pixel in the watermark with the corresponding pixel in
 * the target image
 *
 * @overload watermark(mark, brightness = 1.0, saturation = 1.0, x_off = 0, y_off = 0)
 *   @param mark [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param brightness [Numeric, String] The fraction of the lightness component of the watermark pixels to be
 *     composited onto the target image. Must be a non-negative number or a string in the form
 *     "NN%". If lightness is a number it is interpreted as a percentage. Both 0.25 and "25%" mean
 *     25%. The default is 100%.
 *   @param saturation [Numeric, String] The fraction of the saturation component of the watermark pixels to
 *     be composited onto the target image. Must be a non-negative number or a string in the form
 *     "NN%". If lightness is a number it is interpreted as a percentage. Both 0.25 and "25%" mean
 *     25%. The default is 100%.
 *   @param x_off [Numeric] The offset of the watermark, measured from the left-hand side of the
 *     target image.
 *   @param y_off [Numeri] The offset of the watermark, measured from the top of the target image.
 *
 * @overload watermark(mark, brightness, saturation, gravity, x_off = 0, y_off = 0)
 *   @param mark [Magick::Image, Magick::ImageList] Either an imagelist or an image. If an
 *     imagelist, uses the current image.
 *   @param brightness [Numeric, String] The fraction of the lightness component of the watermark pixels to be
 *     composited onto the target image. Must be a non-negative number or a string in the form
 *     "NN%". If lightness is a number it is interpreted as a percentage. Both 0.25 and "25%" mean
 *     25%. The default is 100%.
 *   @param saturation [Numeric, String] The fraction of the saturation component of the watermark pixels to
 *     be composited onto the target image. Must be a non-negative number or a string in the form
 *     "NN%". If lightness is a number it is interpreted as a percentage. Both 0.25 and "25%" mean
 *     25%. The default is 100%.
 *   @param gravity [Magick::GravityType] the gravity for offset. the offsets are measured from the
 *     NorthWest corner by default.
 *   @param x_off [Numeric] The offset of the watermark, measured from the left-hand side of the
 *     target image.
 *   @param y_off [Numeri] The offset of the watermark, measured from the top of the target image.
 *
 * @return [Magick::Image] a new image
 */
VALUE
Image_watermark(int argc, VALUE *argv, VALUE self)
{
    Image *image, *overlay, *new_image;
    double src_percent = 100.0, dst_percent = 100.0;
    long x_offset = 0L, y_offset = 0L;
    char geometry[20];
    VALUE ovly;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

    if (argc < 1)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 to 6)", argc);
    }

    ovly = rm_cur_image(argv[0]);
    overlay = rm_check_destroyed(ovly);

    if (argc > 3)
    {
        get_composite_offsets(argc-3, &argv[3], image, overlay, &x_offset, &y_offset);
        // There must be 3 arguments left
        argc = 3;
    }

    switch (argc)
    {
        case 3:
            dst_percent = rm_percentage(argv[2], 1.0) * 100.0;
        case 2:
            src_percent = rm_percentage(argv[1], 1.0) * 100.0;
        case 1:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 to 6)", argc);
            break;
    }

    blend_geometry(geometry, sizeof(geometry), src_percent, dst_percent);
    CloneString(&overlay->geometry, geometry);
    SetImageArtifact(overlay, "compose:args", geometry);

    new_image = rm_clone_image(image);
#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(CompositeImage) args = { new_image, overlay, ModulateCompositeOp, MagickTrue, x_offset, y_offset, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompositeImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(CompositeImage) args = { new_image, ModulateCompositeOp, overlay, x_offset, y_offset };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CompositeImage), &args);

    rm_check_image_exception(new_image, DestroyOnError);
#endif

    RB_GC_GUARD(ovly);

    return rm_image_new(new_image);
}


/**
 * Create a "ripple" effect in the image by shifting the pixels vertically along a sine wave whose
 * amplitude and wavelength is specified by the given parameters.
 *
 * @overload wave(amplitude = 25.0, wavelength = 150.0)
 *   @param amplitude [Numeric] the amplitude
 *   @param wavelength [Numeric] the wave length
 *   @return [Magick::Image] a new image
 */
VALUE
Image_wave(int argc, VALUE *argv, VALUE self)
{
    Image *image, *new_image;
    double amplitude = 25.0, wavelength = 150.0;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 2:
            wavelength = NUM2DBL(argv[1]);
        case 1:
            amplitude = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 2)", argc);
            break;
    }

    exception = AcquireExceptionInfo();
#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(WaveImage) args = { image, amplitude, wavelength, image->interpolate, exception };
#else
    GVL_STRUCT_TYPE(WaveImage) args = { image, amplitude, wavelength, exception };
#endif
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(WaveImage), &args);
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

    return rm_image_new(new_image);
}


/**
 * Creates a "wet floor" reflection. The reflection is an inverted copy of the image that changes
 * from partially transparent to entirely transparent. By default only the bottom third of the image
 * appears in the reflection.
 *
 * @overload wet_floor(initial = 0.5, rate = 1.0)
 *   @param initial [Numeric] A value between 0.0 and 1.0 that specifies the initial percentage of
 *     transparency. Higher values cause the top of the reflection to be more transparent, lower
 *     values less transparent. The default is 0.5, which means that the top of the reflection is 50%
 *     transparent.
 *   @param rate [Numeric] A non-negative value that specifies how rapidly the reflection transitions
 *     from the initial level of transparency to entirely transparent. The default value is 1.0, which
 *     means that the transition occurs in 1/3 the image height. Values greater than 1.0 speed up the
 *     transition (the reflection will have fewer rows), values lower than 1.0 slow down the
 *     transition (the reflection will have more rows). A value of 0.0 means that the level of
 *     transparency will not change.
 *   @return [Magick::Image] a new image
 *   @see http://en.wikipedia.org/wiki/Wet_floor_effect
 */
VALUE
Image_wet_floor(int argc, VALUE *argv, VALUE self)
{
    Image *image, *reflection, *flip_image;
#if defined(IMAGEMAGICK_7)
    const Quantum *p;
    Quantum *q;
#else
    const PixelPacket *p;
    PixelPacket *q;
#endif
    RectangleInfo geometry;
    long x, y, max_rows;
    double initial = 0.5;
    double rate = 1.0;
    double opacity, step;
    const char *func;
    ExceptionInfo *exception;

    image = rm_check_destroyed(self);
    switch (argc)
    {
        case 2:
            rate = NUM2DBL(argv[1]);
        case 1:
            initial = NUM2DBL(argv[0]);
        case 0:
            break;
        default:
            rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 to 2)", argc);
            break;
    }


    if (initial < 0.0 || initial > 1.0)
    {
        rb_raise(rb_eArgError, "Initial transparency must be in the range 0.0-1.0 (%g)", initial);
    }
    if (rate < 0.0)
    {
        rb_raise(rb_eArgError, "Transparency change rate must be >= 0.0 (%g)", rate);
    }

#if defined(IMAGEMAGICK_7)
    initial *= QuantumRange;
#else
    initial *= TransparentOpacity;
#endif

    // The number of rows in which to transition from the initial level of
    // transparency to complete transparency. rate == 0.0 -> no change.
    if (rate > 0.0)
    {
        max_rows = (long)((double)image->rows) / (3.0 * rate);
        max_rows = (long)min((unsigned long)max_rows, image->rows);
#if defined(IMAGEMAGICK_7)
        step =  (QuantumRange - initial) / max_rows;
#else
        step =  (TransparentOpacity - initial) / max_rows;
#endif
    }
    else
    {
        max_rows = (long)image->rows;
        step = 0.0;
    }


    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(FlipImage) args_FlipImage = { image, exception };
    flip_image = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(FlipImage), &args_FlipImage);
    CHECK_EXCEPTION();


    geometry.x = 0;
    geometry.y = 0;
    geometry.width = image->columns;
    geometry.height = max_rows;
    GVL_STRUCT_TYPE(CropImage) args_CropImage = { flip_image, &geometry, exception };
    reflection = (Image *)CALL_FUNC_WITHOUT_GVL(GVL_FUNC(CropImage), &args_CropImage);
    DestroyImage(flip_image);
    CHECK_EXCEPTION();


#if defined(IMAGEMAGICK_7)
    GVL_STRUCT_TYPE(SetImageStorageClass) args_SetImageStorageClass = { reflection, DirectClass, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageStorageClass), &args_SetImageStorageClass);
    rm_check_exception(exception, reflection, DestroyOnError);
    GVL_STRUCT_TYPE(SetImageAlphaChannel) args_SetImageAlphaChannel = { reflection, ActivateAlphaChannel, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageAlphaChannel), &args_SetImageAlphaChannel);
    rm_check_exception(exception, reflection, DestroyOnError);
#else
    GVL_STRUCT_TYPE(SetImageStorageClass) args_SetImageStorageClass = { reflection, DirectClass };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SetImageStorageClass), &args_SetImageStorageClass);
    rm_check_image_exception(reflection, DestroyOnError);


    reflection->matte = MagickTrue;
#endif
    opacity = initial;

    for (y = 0; y < max_rows; y++)
    {
#if defined(IMAGEMAGICK_7)
        if (opacity > QuantumRange)
        {
            opacity = QuantumRange;
        }
#else
        if (opacity > TransparentOpacity)
        {
            opacity = TransparentOpacity;
        }
#endif

        GVL_STRUCT_TYPE(GetVirtualPixels) args_GetVirtualPixels = { reflection, 0, y, image->columns, 1, exception };
        void *ret = CALL_FUNC_WITHOUT_GVL(GVL_FUNC(GetVirtualPixels), &args_GetVirtualPixels);
        p = reinterpret_cast<decltype(p)>(ret);
        rm_check_exception(exception, reflection, DestroyOnError);
        if (!p)
        {
            func = "AcquireImagePixels";
            goto error;
        }

        q = QueueAuthenticPixels(reflection, 0, y, image->columns, 1, exception);

        rm_check_exception(exception, reflection, DestroyOnError);
        if (!q)
        {
            func = "SetImagePixels";
            goto error;
        }

        for (x = 0; x < (long) image->columns; x++)
        {
            // Never make a pixel *less* transparent than it already is.
#if defined(IMAGEMAGICK_7)
            *q = *p;
            SetPixelAlpha(reflection, min(GetPixelAlpha(image, q), QuantumRange - (Quantum)opacity), q);

            p += GetPixelChannels(reflection);
            q += GetPixelChannels(reflection);
#else
            q[x] = p[x];
            q[x].opacity = max(q[x].opacity, (Quantum)opacity);
#endif
        }

        GVL_STRUCT_TYPE(SyncAuthenticPixels) args_SyncAuthenticPixels = { reflection, exception };
        CALL_FUNC_WITHOUT_GVL(GVL_FUNC(SyncAuthenticPixels), &args_SyncAuthenticPixels);
        rm_check_exception(exception, reflection, DestroyOnError);

        opacity += step;
    }


    DestroyExceptionInfo(exception);
    return rm_image_new(reflection);

    error:
    DestroyExceptionInfo(exception);
    DestroyImage(reflection);
    rb_raise(rb_eRuntimeError, "%s failed on row %lu", func, y);
    return(VALUE)0;
}


/**
 * Forces all pixels above the threshold into white while leaving all pixels below the threshold
 * unchanged.
 *
 * @overload white_threshold(red, green, blue, alpha: alpha)
 *  @param red [Numeric] the number for red channel
 *  @param green [Numeric] the number for green channel
 *  @param blue [Numeric] the number for blue channel
 *  @param alpha [Numeric] the number for alpha channel
 *  @return [Magick::Image] a new image
 *  @see Image#black_threshold
 */
VALUE
Image_white_threshold(int argc, VALUE *argv, VALUE self)
{
    return threshold_image(argc, argv, self, GVL_FUNC(WhiteThresholdImage));
}


/**
 * Copy the filename to the Info and to the Image. Add format prefix if necessary. This complicated
 * code is necessary to handle filenames like the kind Tempfile.new produces, which have an
 * "extension" in the form ".n", which confuses SetMagickInfo. So we don't use SetMagickInfo any
 * longer.
 *
 * No Ruby usage (internal function)
 *
 * @param info the Info
 * @param file the file
 */
void add_format_prefix(Info *info, VALUE file)
{
    char *filename;
    size_t filename_l;
    const MagickInfo *magick_info, *magick_info2;
    ExceptionInfo *exception;
    char magic[MaxTextExtent];
    size_t magic_l;
    size_t prefix_l;
    char *p;

    // Convert arg to string. If an exception occurs raise an error condition.
    if (rb_respond_to(file, rb_intern("path")))
    {
        FilePathStringValue(file);
    }
    file = rb_rescue(RESCUE_FUNC(rb_String), file, RESCUE_EXCEPTION_HANDLER_FUNC(file_arg_rescue), file);

    filename = rm_str2cstr(file, &filename_l);

    if (*info->magick == '\0')
    {
        memset(info->filename, 0, sizeof(info->filename));
        memcpy(info->filename, filename, (size_t)min(filename_l, MaxTextExtent-1));
        return;
    }

    // If the filename starts with a prefix, and it's a valid image format
    // prefix, then check for a conflict. If it's not a valid format prefix,
    // ignore it.
    p = (char *)memchr(filename, ':', (size_t)filename_l);
    if (p)
    {
        memset(magic, '\0', sizeof(magic));
        magic_l = p - filename;
        memcpy(magic, filename, magic_l);

        exception = AcquireExceptionInfo();
        magick_info = GetMagickInfo(magic, exception);
        CHECK_EXCEPTION();
        DestroyExceptionInfo(exception);

        if (magick_info && magick_info->magick_module)
        {
            // We have to compare the module names because some formats have
            // more than one name. JPG and JPEG, for example.
            exception = AcquireExceptionInfo();
            magick_info2 = GetMagickInfo(info->magick, exception);
            CHECK_EXCEPTION();
            DestroyExceptionInfo(exception);

            if (magick_info2->magick_module && strcmp(magick_info->magick_module, magick_info2->magick_module) != 0)
            {
                rb_raise(rb_eRuntimeError,
                         "filename prefix `%s' conflicts with output format `%s'",
                         magick_info->name, info->magick);
            }

            // The filename prefix already matches the specified format.
            // Just copy the filename as-is.
            memset(info->filename, 0, sizeof(info->filename));
            filename_l = min((size_t)filename_l, sizeof(info->filename));
            memcpy(info->filename, filename, (size_t)filename_l);
            return;
        }
    }

    // The filename doesn't start with a format prefix. Add the format from
    // the image info as the filename prefix.

    memset(info->filename, 0, sizeof(info->filename));
    prefix_l = min(sizeof(info->filename)-1, rm_strnlen_s(info->magick, sizeof(info->magick)));
    memcpy(info->filename, info->magick, prefix_l);
    info->filename[prefix_l++] = ':';

    filename_l = min(sizeof(info->filename) - prefix_l - 1, (size_t)filename_l);
    memcpy(info->filename+prefix_l, filename, (size_t)filename_l);
    info->filename[prefix_l+filename_l] = '\0';

    return;
}


/**
 * Write the image to the file.
 *
 * @param file [File, String] the file
 * @yield [info]
 * @yieldparam info [Magick::Image::Info]
 * @return [Magick::Image] self
 */
VALUE
Image_write(VALUE self, VALUE file)
{
    Image *image;
    Info *info;
    VALUE info_obj;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image = rm_check_destroyed(self);

    info_obj = rm_info_new();
    TypedData_Get_Struct(info_obj, Info, &rm_info_data_type, info);

    if (TYPE(file) == T_FILE)
    {
        rb_io_t *fptr;

        // Ensure file is open - raise error if not
        GetOpenFile(file, fptr);
        rb_io_check_writable(fptr);

        add_format_prefix(info, rm_io_path(file));
#if defined(_WIN32)
        SetImageInfoFile(info, NULL);
#else
        SetImageInfoFile(info, rb_io_stdio_file(fptr));
#endif
    }
    else
    {
        add_format_prefix(info, file);
        SetImageInfoFile(info, NULL);
    }
    strlcpy(image->filename, info->filename, sizeof(image->filename));

    rm_sync_image_options(image, info);

    info->adjoin = MagickFalse;
#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(WriteImage) args = { info, image, exception };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(WriteImage), &args);
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    GVL_STRUCT_TYPE(WriteImage) args = { info, image };
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(WriteImage), &args);
    rm_check_image_exception(image, RetainOnError);
#endif

    RB_GC_GUARD(info_obj);

    return self;
}

#if defined(IMAGEMAGICK_7)
/**
 * Get the horizontal resolution of the image.
 *
 * @return [Float] the resolution
 */
VALUE
Image_x_resolution(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READERF(Image, x_resolution, resolution.x, dbl, &rm_image_data_type);
}

/**
 * Set the horizontal resolution of the image.
 *
 * @param val [Numeric] the resolution
 * @return [Numeric] the given resolution
 */
VALUE
Image_x_resolution_eq(VALUE self, VALUE val)
{
    IMPLEMENT_TYPED_ATTR_WRITERF(Image, x_resolution, resolution.x, dbl, &rm_image_data_type);
}

/**
 * Get the vertical resolution of the image.
 *
 * @return [Float] the resolution
 */
VALUE
Image_y_resolution(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READERF(Image, y_resolution, resolution.y, dbl, &rm_image_data_type);
}

/**
 * Set the vertical resolution of the image.
 *
 * @param val [Numeric] the resolution
 * @return [Numeric] the given resolution
 */
VALUE
Image_y_resolution_eq(VALUE self, VALUE val)
{
    IMPLEMENT_TYPED_ATTR_WRITERF(Image, y_resolution, resolution.y, dbl, &rm_image_data_type);
}
#else
/**
 * Get the horizontal resolution of the image.
 *
 * @return [Float] the resolution
 */
VALUE
Image_x_resolution(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, x_resolution, dbl, &rm_image_data_type);
}

/**
 * Set the horizontal resolution of the image.
 *
 * @param val [Numeric] the resolution
 * @return [Numeric] the given resolution
 */
VALUE
Image_x_resolution_eq(VALUE self, VALUE val)
{
    IMPLEMENT_TYPED_ATTR_WRITER(Image, x_resolution, dbl, &rm_image_data_type);
}

/**
 * Get the vertical resolution of the image.
 *
 * @return [Float] the resolution
 */
VALUE
Image_y_resolution(VALUE self)
{
    IMPLEMENT_TYPED_ATTR_READER(Image, y_resolution, dbl, &rm_image_data_type);
}

/**
 * Set the vertical resolution of the image.
 *
 * @param val [Numeric] the resolution
 * @return [Numeric] the given resolution
 */
VALUE
Image_y_resolution_eq(VALUE self, VALUE val)
{
    IMPLEMENT_TYPED_ATTR_WRITER(Image, y_resolution, dbl, &rm_image_data_type);
}
#endif


/**
 * Determine if the argument list is x, y, width, height
 * or
 * gravity, width, height
 * or
 * gravity, x, y, width, height
 *
 * If the 2nd or 3rd, compute new x, y values.
 *
 * The argument list can have a trailing true, false, or nil argument. If
 * present and true, after cropping reset the page fields in the image.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - Call xform_image to do the cropping.
 *
 * @param bang whether the bang (!) version of the method was called
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @param self this object
 * @return self if bang, otherwise a new image
 * @see xform_image
 */
static VALUE
cropper(int bang, int argc, VALUE *argv, VALUE self)
{
    VALUE x, y, width, height;
    unsigned long nx = 0, ny = 0;
    unsigned long columns, rows;
    int reset_page = 0;
    GravityType gravity;
    Image *image;
    VALUE cropped;

    // Check for a "reset page" trailing argument.
    if (argc >= 1)
    {
        switch (TYPE(argv[argc-1]))
        {
            case T_TRUE:
                reset_page = 1;
                // fall thru
            case T_FALSE:
            case T_NIL:
                argc -= 1;
            default:
                break;
        }
    }

    switch (argc)
    {
        case 5:
            TypedData_Get_Struct(self, Image, &rm_image_data_type, image);

            VALUE_TO_ENUM(argv[0], gravity, GravityType);

            x      = argv[1];
            y      = argv[2];
            width  = argv[3];
            height = argv[4];

            nx      = NUM2ULONG(x);
            ny      = NUM2ULONG(y);
            columns = NUM2ULONG(width);
            rows    = NUM2ULONG(height);

            switch (gravity)
            {
                case NorthEastGravity:
                case EastGravity:
                case SouthEastGravity:
                    nx = image->columns - columns - nx;
                    break;
                case NorthGravity:
                case SouthGravity:
                case CenterGravity:
                    nx += image->columns/2 - columns/2;
                    break;
                default:
                    break;
            }
            switch (gravity)
            {
                case SouthWestGravity:
                case SouthGravity:
                case SouthEastGravity:
                    ny = image->rows - rows - ny;
                    break;
                case EastGravity:
                case WestGravity:
                case CenterGravity:
                    ny += image->rows/2 - rows/2;
                    break;
                case NorthEastGravity:
                case NorthGravity:
                default:
                    break;
            }

            x = ULONG2NUM(nx);
            y = ULONG2NUM(ny);
            break;
        case 4:
            x      = argv[0];
            y      = argv[1];
            width  = argv[2];
            height = argv[3];
            break;
        case 3:

            // Convert the width & height arguments to unsigned longs.
            // Compute the x & y offsets from the gravity and then
            // convert them to VALUEs.
            VALUE_TO_ENUM(argv[0], gravity, GravityType);
            width   = argv[1];
            height  = argv[2];
            columns = NUM2ULONG(width);
            rows    = NUM2ULONG(height);

            TypedData_Get_Struct(self, Image, &rm_image_data_type, image);

            switch (gravity)
            {
                case ForgetGravity:
                case NorthWestGravity:
                    nx = 0;
                    ny = 0;
                    break;
                case NorthGravity:
                    nx = (image->columns - columns) / 2;
                    ny = 0;
                    break;
                case NorthEastGravity:
                    nx = image->columns - columns;
                    ny = 0;
                    break;
                case WestGravity:
                    nx = 0;
                    ny = (image->rows - rows) / 2;
                    break;
                case EastGravity:
                    nx = image->columns - columns;
                    ny = (image->rows - rows) / 2;
                    break;
                case SouthWestGravity:
                    nx = 0;
                    ny = image->rows - rows;
                    break;
                case SouthGravity:
                    nx = (image->columns - columns) / 2;
                    ny = image->rows - rows;
                    break;
                case SouthEastGravity:
                    nx = image->columns - columns;
                    ny = image->rows - rows;
                    break;
                case CenterGravity:
                    nx = (image->columns - columns) / 2;
                    ny = (image->rows - rows) / 2;
                    break;
#if defined(IMAGEMAGICK_6)
                case StaticGravity:
                    rb_raise(rb_eNotImpError, "`StaticGravity' is not supported");
                    break;
#endif
            }

            x = ULONG2NUM(nx);
            y = ULONG2NUM(ny);
            break;
        default:
            if (reset_page)
            {
                rb_raise(rb_eArgError, "wrong number of arguments (%d for 4, 5, or 6)", argc);
            }
            else
            {
                rb_raise(rb_eArgError, "wrong number of arguments (%d for 3, 4, or 5)", argc);
            }
            break;
    }

    cropped = xform_image(bang, self, x, y, width, height, GVL_FUNC(CropImage));
    if (reset_page)
    {
        TypedData_Get_Struct(cropped, Image, &rm_image_data_type, image);
        ResetImagePage(image, "0x0+0+0");
    }

    RB_GC_GUARD(x);
    RB_GC_GUARD(y);
    RB_GC_GUARD(width);
    RB_GC_GUARD(height);

    return cropped;
}


// aliases for common use of structure types; ChopImage, CropImage, ShaveImage
typedef GVL_STRUCT_TYPE(ChopImage) GVL_STRUCT_TYPE(xform_image);

/**
 * Call one of the image transformation functions.
 *
 * No Ruby usage (internal function)
 *
 * @param bang whether the bang (!) version of the method was called
 * @param self this object
 * @param x x position of start of region
 * @param y y position of start of region
 * @param width width of region
 * @param height height of region
 * @param xformer the transformation function
 * @return self if bang, otherwise a new image
 */
static VALUE
xform_image(int bang, VALUE self, VALUE x, VALUE y, VALUE width, VALUE height, gvl_function_t fp)
{
    Image *image, *new_image;
    RectangleInfo rect;
    ExceptionInfo *exception;

    TypedData_Get_Struct(self, Image, &rm_image_data_type, image);
    rect.x      = NUM2LONG(x);
    rect.y      = NUM2LONG(y);
    rect.width  = NUM2ULONG(width);
    rect.height = NUM2ULONG(height);

    exception = AcquireExceptionInfo();

    GVL_STRUCT_TYPE(xform_image) args = { image, &rect, exception };
    new_image = (Image *)CALL_FUNC_WITHOUT_GVL(fp, &args);

    // An exception can occur in either the old or the new images
    rm_check_exception(exception, new_image, DestroyOnError);
    DestroyExceptionInfo(exception);

#if defined(IMAGEMAGICK_6)
    if (rm_should_raise_exception(&image->exception, RetainExceptionRetention))
    {
        DestroyImage(new_image);
        rm_check_image_exception(image, RetainOnError);
    }
#endif

    if (bang)
    {
        rm_ensure_result(new_image);
        UPDATE_DATA_PTR(self, new_image);
        rm_image_destroy(image);
        return self;
    }

    return rm_image_new(new_image);

}


/**
 * Remove all the ChannelType arguments from the end of the argument list.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - Returns DefaultChannels if no channel arguments were found.
 *   - Returns the number of remaining arguments.
 *
 * @param argc number of input arguments
 * @param argv array of input arguments
 * @return A ChannelType value suitable for passing into an xMagick function.
 */
ChannelType extract_channels(int *argc, VALUE *argv)
{
    VALUE arg;
    ChannelType channels, ch_arg;

    channels = UndefinedChannel;
    while (*argc > 0)
    {
        arg = argv[(*argc)-1];

        // Stop when you find a non-ChannelType argument
        if (CLASS_OF(arg) != Class_ChannelType)
        {
            break;
        }
        VALUE_TO_ENUM(arg, ch_arg, ChannelType);
        channels = (ChannelType)(channels | ch_arg);
        *argc -= 1;
    }

    if (channels == 0)
    {
        channels = DefaultChannels;
    }

    RB_GC_GUARD(arg);

    return channels;
}


/**
 * Raise TypeError when an non-ChannelType object is unexpectedly encountered.
 *
 * No Ruby usage (internal function)
 *
 * @param arg the argument
 */
void
raise_ChannelType_error(VALUE arg)
{
    rb_raise(rb_eTypeError, "argument must be a ChannelType value (%s given)",
             rb_class2name(CLASS_OF(arg)));
}


/**
 * Destroy an image. Called from GC when all references to the image have gone
 * out of scope.
 *
 * No Ruby usage (internal function)
 *
 * Notes:
 *   - A NULL Image pointer indicates that the image has already been destroyed
 *     by Image#destroy!
 *
 * @param img the image
 */
void rm_image_destroy(void *img)
{
    Image *image = (Image *)img;

    if (img != NULL)
    {
        DestroyImage(image);
    }
}

/**
  * Get Image object size.
  *
  * No Ruby usage (internal function)
  *
  * @param ptr pointer to the Image object
  */
static size_t
rm_image_memsize(const void *ptr)
{
    return sizeof(Image);
}