File: astcenccli_image_load_store.cpp

package info (click to toggle)
astc-encoder 2.1%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 36,948 kB
  • sloc: cpp: 20,204; python: 2,598; makefile: 156; sh: 15
file content (2313 lines) | stat: -rw-r--r-- 65,923 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
// SPDX-License-Identifier: Apache-2.0
// ----------------------------------------------------------------------------
// Copyright 2011-2020 Arm Limited
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at:
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
// ----------------------------------------------------------------------------

/**
 * @brief Functions for loading/storing ASTC compressed images.
 */

#include <array>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>

#include "astcenccli_internal.h"

// on windows/msvc, compile stb and tinyexr together with this file;
// on other systems, use makefile to compile them separately.
#ifdef _MSC_VER
	#define STB_IMAGE_IMPLEMENTATION
	#define STB_IMAGE_WRITE_IMPLEMENTATION
	#define STBI_MSC_SECURE_CRT
	#define TINYEXR_IMPLEMENTATION
	#define STBI_NO_GIF
	#define STBI_NO_PIC
	#define STBI_NO_PNM
	#define STBI_NO_PSD
#else
	#define STBI_HEADER_FILE_ONLY
#endif

#include "stb_image.h"
#include "stb_image_write.h"
#include "tinyexr.h"

/*******************************************************************
Image load and store through the stb_iamge and tinyexr libraries
*******************************************************************/

static astcenc_image* load_image_with_tinyexr(
	const char* filename,
	unsigned int dim_pad,
	bool y_flip,
	bool& is_hdr,
	unsigned int& num_components
) {
	int dim_x, dim_y;
	float* image;
	const char* err;

	int load_res = LoadEXR(&image, &dim_x, &dim_y, filename, &err);
	if (load_res != TINYEXR_SUCCESS)
	{
		printf("ERROR: Failed to load image %s (%s)\n", filename, err);
		free((void*)err);
		return nullptr;
	}

	astcenc_image* res_img = astc_img_from_floatx4_array(image, dim_x, dim_y, dim_pad, y_flip);
	free(image);

	is_hdr = true;
	num_components = 4;
	return res_img;
}

static astcenc_image* load_image_with_stb(
	const char* filename,
	unsigned int dim_pad,
	bool y_flip,
	bool& is_hdr,
	unsigned int& num_components
) {
	int dim_x, dim_y;

	if (stbi_is_hdr(filename))
	{
		float* data = stbi_loadf(filename, &dim_x, &dim_y, nullptr, STBI_rgb_alpha);
		if (data)
		{
			astcenc_image* img = astc_img_from_floatx4_array(data, dim_x, dim_y, dim_pad, y_flip);
			stbi_image_free(data);
			is_hdr = true;
			num_components = 4;
			return img;
		}
	}
	else
	{
		uint8_t* data = stbi_load(filename, &dim_x, &dim_y, nullptr, STBI_rgb_alpha);
		if (data)
		{
			astcenc_image* img = astc_img_from_unorm8x4_array(data, dim_x, dim_y, dim_pad, y_flip);
			stbi_image_free(data);
			is_hdr = false;
			num_components = 4;
			return img;
		}
	}

	printf("ERROR: Failed to load image %s (%s)\n", filename, stbi_failure_reason());
	return nullptr;
}

static int store_exr_image_with_tinyexr(
	const astcenc_image* img,
	const char* filename,
	int y_flip
) {
	float *buf = floatx4_array_from_astc_img(img, y_flip);
	int res = SaveEXR(buf, img->dim_x, img->dim_y, 4, 1, filename, nullptr);
	delete[] buf;
	return (res == 0) ? 4 : res;
}

static int store_png_image_with_stb(
	const astcenc_image* img,
	const char* filename,
	int y_flip
) {
	uint8_t* buf = unorm8x4_array_from_astc_img(img, y_flip);
	int res = stbi_write_png(filename, img->dim_x, img->dim_y, 4, buf, img->dim_x * 4);
	delete[] buf;
	return (res == 0) ? -1 : 4;
}

static int store_tga_image_with_stb(
	const astcenc_image* img,
	const char* filename,
	int y_flip
) {
	uint8_t* buf = unorm8x4_array_from_astc_img(img, y_flip);
	int res = stbi_write_tga(filename, img->dim_x, img->dim_y, 4, buf);
	delete[] buf;
	return (res == 0) ? -1 : 4;
}

static int store_bmp_image_with_stb(
	const astcenc_image* img,
	const char* filename,
	int y_flip
) {
	uint8_t* buf = unorm8x4_array_from_astc_img(img, y_flip);
	int res = stbi_write_bmp(filename, img->dim_x, img->dim_y, 4, buf);
	delete[] buf;
	return (res == 0) ? -1 : 4;
}

static int store_hdr_image_with_stb(
	const astcenc_image* img,
	const char* filename,
	int y_flip
) {
	float* buf = floatx4_array_from_astc_img(img, y_flip);
	int res = stbi_write_hdr(filename, img->dim_x, img->dim_y, 4, buf);
	delete[] buf;
	return (res == 0) ? -1 : 4;
}

/*********************************************************************
Native Load and store of KTX and DDS file formats.

Unlike "regular" 2D image formats, which are mostly supported
through stb_image and tinyexr, these formats are supported directly;
this involves a relatively large number of pixel formats.

The following restrictions apply to loading of these file formats:
 * Only uncompressed data supported
 * Only first mipmap in mipmap pyramid supported
 * KTX: Cube-map arrays are not supported
*********************************************************************/
enum scanline_copy_method
{
	R8_TO_RGBA8,
	RG8_TO_RGBA8,
	RGB8_TO_RGBA8,
	RGBA8_TO_RGBA8,
	BGR8_TO_RGBA8,
	BGRA8_TO_RGBA8,
	L8_TO_RGBA8,
	LA8_TO_RGBA8,

	RGBX8_TO_RGBA8,
	BGRX8_TO_RGBA8,

	R16_TO_RGBA16F,
	RG16_TO_RGBA16F,
	RGB16_TO_RGBA16F,
	RGBA16_TO_RGBA16F,
	BGR16_TO_RGBA16F,
	BGRA16_TO_RGBA16F,
	L16_TO_RGBA16F,
	LA16_TO_RGBA16F,

	R16F_TO_RGBA16F,
	RG16F_TO_RGBA16F,
	RGB16F_TO_RGBA16F,
	RGBA16F_TO_RGBA16F,
	BGR16F_TO_RGBA16F,
	BGRA16F_TO_RGBA16F,
	L16F_TO_RGBA16F,
	LA16F_TO_RGBA16F,

	R32F_TO_RGBA16F,
	RG32F_TO_RGBA16F,
	RGB32F_TO_RGBA16F,
	RGBA32F_TO_RGBA16F,
	BGR32F_TO_RGBA16F,
	BGRA32F_TO_RGBA16F,
	L32F_TO_RGBA16F,
	LA32F_TO_RGBA16F
};

// scanline copying function: this function expands data to RGBA, either U8 or FP16.
static void copy_scanline(
	void* dst,
	const void* src,
	int pixels,
	int method
) {

#define id(x) (x)
#define u16_sf16(x) float_to_sf16(x * (1.0f/65535.0f), SF_NEARESTEVEN)
#define f32_sf16(x) sf32_to_sf16(x, SF_NEARESTEVEN)

#define COPY_R(dsttype, srctype, convfunc, oneval) \
	do { \
		srctype *s = (srctype *)src; \
		dsttype *d = (dsttype *)dst; \
		for (int i = 0; i < pixels; i++)\
		{\
			d[4*i] = convfunc(s[i]); \
			d[4*i+1] = 0; \
			d[4*i+2] = 0; \
			d[4*i+3] = oneval; \
		} \
	} while (0); \
	break;

#define COPY_RG(dsttype, srctype, convfunc, oneval) \
	do { \
		srctype *s = (srctype *)src; \
		dsttype *d = (dsttype *)dst; \
		for (int i = 0; i < pixels; i++)\
		{\
			d[4*i] = convfunc(s[2*i]); \
			d[4*i+1] = convfunc(s[2*i+1]); \
			d[4*i+2] = 0; \
			d[4*i+3] = oneval; \
		} \
	} while (0); \
	break;

#define COPY_RGB(dsttype, srctype, convfunc, oneval) \
	do { \
		srctype *s = (srctype *)src; \
		dsttype *d = (dsttype *)dst; \
		for (int i = 0; i < pixels; i++)\
		{\
			d[4*i] = convfunc(s[3*i]); \
			d[4*i+1] = convfunc(s[3*i+1]); \
			d[4*i+2] = convfunc(s[3*i+2]); \
			d[4*i+3] = oneval; \
		} \
	} while (0); \
	break;

#define COPY_BGR(dsttype, srctype, convfunc, oneval) \
	do { \
		srctype *s = (srctype *)src; \
		dsttype *d = (dsttype *)dst; \
		for (int i = 0; i < pixels; i++)\
		{\
			d[4*i] = convfunc(s[3*i+2]); \
			d[4*i+1] = convfunc(s[3*i+1]); \
			d[4*i+2] = convfunc(s[3*i]); \
			d[4*i+3] = oneval; \
		} \
	} while (0); \
	break;

#define COPY_RGBX(dsttype, srctype, convfunc, oneval) \
	do { \
		srctype *s = (srctype *)src; \
		dsttype *d = (dsttype *)dst; \
		for (int i = 0; i < pixels; i++)\
		{\
			d[4*i] = convfunc(s[4*i]); \
			d[4*i+1] = convfunc(s[4*i+1]); \
			d[4*i+2] = convfunc(s[4*i+2]); \
			d[4*i+3] = oneval; \
		} \
	} while (0); \
	break;

#define COPY_BGRX(dsttype, srctype, convfunc, oneval) \
	do { \
		srctype *s = (srctype *)src; \
		dsttype *d = (dsttype *)dst; \
		for (int i = 0; i < pixels; i++)\
		{\
			d[4*i] = convfunc(s[4*i+2]); \
			d[4*i+1] = convfunc(s[4*i+1]); \
			d[4*i+2] = convfunc(s[4*i]); \
			d[4*i+3] = oneval; \
		} \
	} while (0); \
	break;

#define COPY_RGBA(dsttype, srctype, convfunc, oneval) \
	do { \
		srctype *s = (srctype *)src; \
		dsttype *d = (dsttype *)dst; \
		for (int i = 0; i < pixels; i++)\
		{\
			d[4*i] = convfunc(s[4*i]); \
			d[4*i+1] = convfunc(s[4*i+1]); \
			d[4*i+2] = convfunc(s[4*i+2]); \
			d[4*i+3] = convfunc(s[4*i+3]); \
		} \
	} while (0); \
	break;

#define COPY_BGRA(dsttype, srctype, convfunc, oneval) \
	do { \
		srctype *s = (srctype *)src; \
		dsttype *d = (dsttype *)dst; \
		for (int i = 0; i < pixels; i++)\
		{\
			d[4*i] = convfunc(s[4*i+2]); \
			d[4*i+1] = convfunc(s[4*i+1]); \
			d[4*i+2] = convfunc(s[4*i]); \
			d[4*i+3] = convfunc(s[4*i+3]); \
		} \
	} while (0); \
	break;

#define COPY_L(dsttype, srctype, convfunc, oneval) \
	do { \
		srctype *s = (srctype *)src; \
		dsttype *d = (dsttype *)dst; \
		for (int i = 0; i < pixels; i++)\
		{\
			d[4*i] = convfunc(s[i]); \
			d[4*i+1] = convfunc(s[i]); \
			d[4*i+2] = convfunc(s[i]); \
			d[4*i+3] = oneval; \
		} \
	} while (0); \
	break;

#define COPY_LA(dsttype, srctype, convfunc, oneval) \
	do { \
		srctype *s = (srctype *)src; \
		dsttype *d = (dsttype *)dst; \
		for (int i = 0; i < pixels; i++)\
		{\
			d[4*i] = convfunc(s[2*i]); \
			d[4*i+1] = convfunc(s[2*i]); \
			d[4*i+2] = convfunc(s[2*i]); \
			d[4*i+3] = convfunc(s[2*i+1]); \
		} \
	} while (0); \
	break;

	switch (method)
	{
	case R8_TO_RGBA8:
		COPY_R(uint8_t, uint8_t, id, 0xFF);
	case RG8_TO_RGBA8:
		COPY_RG(uint8_t, uint8_t, id, 0xFF);
	case RGB8_TO_RGBA8:
		COPY_RGB(uint8_t, uint8_t, id, 0xFF);
	case RGBA8_TO_RGBA8:
		COPY_RGBA(uint8_t, uint8_t, id, 0xFF);
	case BGR8_TO_RGBA8:
		COPY_BGR(uint8_t, uint8_t, id, 0xFF);
	case BGRA8_TO_RGBA8:
		COPY_BGRA(uint8_t, uint8_t, id, 0xFF);
	case RGBX8_TO_RGBA8:
		COPY_RGBX(uint8_t, uint8_t, id, 0xFF);
	case BGRX8_TO_RGBA8:
		COPY_BGRX(uint8_t, uint8_t, id, 0xFF);
	case L8_TO_RGBA8:
		COPY_L(uint8_t, uint8_t, id, 0xFF);
	case LA8_TO_RGBA8:
		COPY_LA(uint8_t, uint8_t, id, 0xFF);

	case R16F_TO_RGBA16F:
		COPY_R(uint16_t, uint16_t, id, 0x3C00);
	case RG16F_TO_RGBA16F:
		COPY_RG(uint16_t, uint16_t, id, 0x3C00);
	case RGB16F_TO_RGBA16F:
		COPY_RGB(uint16_t, uint16_t, id, 0x3C00);
	case RGBA16F_TO_RGBA16F:
		COPY_RGBA(uint16_t, uint16_t, id, 0x3C00);
	case BGR16F_TO_RGBA16F:
		COPY_BGR(uint16_t, uint16_t, id, 0x3C00);
	case BGRA16F_TO_RGBA16F:
		COPY_BGRA(uint16_t, uint16_t, id, 0x3C00);
	case L16F_TO_RGBA16F:
		COPY_L(uint16_t, uint16_t, id, 0x3C00);
	case LA16F_TO_RGBA16F:
		COPY_LA(uint16_t, uint16_t, id, 0x3C00);

	case R16_TO_RGBA16F:
		COPY_R(uint16_t, uint16_t, u16_sf16, 0x3C00);
	case RG16_TO_RGBA16F:
		COPY_RG(uint16_t, uint16_t, u16_sf16, 0x3C00);
	case RGB16_TO_RGBA16F:
		COPY_RGB(uint16_t, uint16_t, u16_sf16, 0x3C00);
	case RGBA16_TO_RGBA16F:
		COPY_RGBA(uint16_t, uint16_t, u16_sf16, 0x3C00);
	case BGR16_TO_RGBA16F:
		COPY_BGR(uint16_t, uint16_t, u16_sf16, 0x3C00);
	case BGRA16_TO_RGBA16F:
		COPY_BGRA(uint16_t, uint16_t, u16_sf16, 0x3C00);
	case L16_TO_RGBA16F:
		COPY_L(uint16_t, uint16_t, u16_sf16, 0x3C00);
	case LA16_TO_RGBA16F:
		COPY_LA(uint16_t, uint16_t, u16_sf16, 0x3C00);

	case R32F_TO_RGBA16F:
		COPY_R(uint16_t, uint32_t, f32_sf16, 0x3C00);
	case RG32F_TO_RGBA16F:
		COPY_RG(uint16_t, uint32_t, f32_sf16, 0x3C00);
	case RGB32F_TO_RGBA16F:
		COPY_RGB(uint16_t, uint32_t, f32_sf16, 0x3C00);
	case RGBA32F_TO_RGBA16F:
		COPY_RGBA(uint16_t, uint32_t, f32_sf16, 0x3C00);
	case BGR32F_TO_RGBA16F:
		COPY_BGR(uint16_t, uint32_t, f32_sf16, 0x3C00);
	case BGRA32F_TO_RGBA16F:
		COPY_BGRA(uint16_t, uint32_t, f32_sf16, 0x3C00);
	case L32F_TO_RGBA16F:
		COPY_L(uint16_t, uint32_t, f32_sf16, 0x3C00);
	case LA32F_TO_RGBA16F:
		COPY_LA(uint16_t, uint32_t, f32_sf16, 0x3C00);
	};
}

// perform endianness switch on raw data
static void switch_endianness2(
	void* dataptr,
	int bytes
) {
	uint8_t *data = (uint8_t *) dataptr;
	for (int i = 0; i < bytes / 2; i++)
	{
		uint8_t d0 = data[0];
		uint8_t d1 = data[1];
		data[0] = d1;
		data[1] = d0;
		data += 2;
	}
}

static void switch_endianness4(
	void* dataptr,
	int bytes
) {
	uint8_t *data = (uint8_t *) dataptr;
	for (int i = 0; i < bytes / 4; i++)
	{
		uint8_t d0 = data[0];
		uint8_t d1 = data[1];
		uint8_t d2 = data[2];
		uint8_t d3 = data[3];
		data[0] = d3;
		data[1] = d2;
		data[2] = d1;
		data[3] = d0;
		data += 4;
	}
}

static uint32_t u32_byterev(uint32_t v)
{
	return (v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24);
}

/*
	Notes about KTX:

	After the header and the key/value data area, the actual image data follows.
	Each image starts with a 4-byte "imageSize" value indicating the number of bytes of image data follow.
	(For cube-maps, this value appears only after first image; the remaining 5 images are all of equal size.)
	If the size of an image is not a multiple of 4, then it is padded to the next multiple of 4.
	Note that this padding is NOT included in the "imageSize" field.
	In a cubemap, the padding appears after each face note that in a 2D/3D texture, padding does
	NOT appear between the lines/planes of the texture!

	In a KTX file, there may be multiple images; they are organized as follows:

	For each mipmap_level in numberOfMipmapLevels
		UInt32 imageSize;
		For each array_element in numberOfArrayElements
		* for each face in numberOfFaces
			* for each z_slice in pixelDepth
				* for each row or row_of_blocks in pixelHeight
					* for each pixel or block_of_pixels in pixelWidth
						Byte data[format-specific-number-of-bytes]
					* end
				* end
			*end
			Byte cubePadding[0-3]
		*end
		Byte mipPadding[3 - ((imageSize+ 3) % 4)]
	*end

	In the ASTC codec, we will, for the time being only harvest the first image,
	and we will support only a limited set of formats:

	gl_type: UNSIGNED_BYTE UNSIGNED_SHORT HALF_FLOAT FLOAT UNSIGNED_INT_8_8_8_8 UNSIGNED_INT_8_8_8_8_REV
	gl_format: RED, RG. RGB, RGBA BGR, BGRA
	gl_internal_format: used for upload to OpenGL; we can ignore it on uncompressed-load, but
		need to provide a reasonable value on store: RGB8 RGBA8 RGB16F RGBA16F
	gl_base_internal_format: same as gl_format unless texture is compressed (well, BGR is turned into RGB)
		RED, RG, RGB, RGBA
 */

// enums copied from GL/GL.h
#define GL_RED    0x1903
#define GL_RG     0x8227
#define GL_RGB    0x1907
#define GL_RGBA   0x1908
#define GL_BGR    0x80E0
#define GL_BGRA   0x80E1
#define GL_LUMINANCE        0x1909
#define GL_LUMINANCE_ALPHA  0x190A

#define GL_UNSIGNED_BYTE   0x1401
#define GL_UNSIGNED_SHORT  0x1403
#define GL_HALF_FLOAT      0x140B
#define GL_FLOAT           0x1406

#define GL_COMPRESSED_RGBA_ASTC_4x4                0x93B0
#define GL_COMPRESSED_RGBA_ASTC_5x4                0x93B1
#define GL_COMPRESSED_RGBA_ASTC_5x5                0x93B2
#define GL_COMPRESSED_RGBA_ASTC_6x5                0x93B3
#define GL_COMPRESSED_RGBA_ASTC_6x6                0x93B4
#define GL_COMPRESSED_RGBA_ASTC_8x5                0x93B5
#define GL_COMPRESSED_RGBA_ASTC_8x6                0x93B6
#define GL_COMPRESSED_RGBA_ASTC_8x8                0x93B7
#define GL_COMPRESSED_RGBA_ASTC_10x5               0x93B8
#define GL_COMPRESSED_RGBA_ASTC_10x6               0x93B9
#define GL_COMPRESSED_RGBA_ASTC_10x8               0x93BA
#define GL_COMPRESSED_RGBA_ASTC_10x10              0x93BB
#define GL_COMPRESSED_RGBA_ASTC_12x10              0x93BC
#define GL_COMPRESSED_RGBA_ASTC_12x12              0x93BD

#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4        0x93D0
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4        0x93D1
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5        0x93D2
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5        0x93D3
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6        0x93D4
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5        0x93D5
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6        0x93D6
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8        0x93D7
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5       0x93D8
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6       0x93D9
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8       0x93DA
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10      0x93DB
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10      0x93DC
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12      0x93DD

#define GL_COMPRESSED_RGBA_ASTC_3x3x3_OES          0x93C0
#define GL_COMPRESSED_RGBA_ASTC_4x3x3_OES          0x93C1
#define GL_COMPRESSED_RGBA_ASTC_4x4x3_OES          0x93C2
#define GL_COMPRESSED_RGBA_ASTC_4x4x4_OES          0x93C3
#define GL_COMPRESSED_RGBA_ASTC_5x4x4_OES          0x93C4
#define GL_COMPRESSED_RGBA_ASTC_5x5x4_OES          0x93C5
#define GL_COMPRESSED_RGBA_ASTC_5x5x5_OES          0x93C6
#define GL_COMPRESSED_RGBA_ASTC_6x5x5_OES          0x93C7
#define GL_COMPRESSED_RGBA_ASTC_6x6x5_OES          0x93C8
#define GL_COMPRESSED_RGBA_ASTC_6x6x6_OES          0x93C9

#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_3x3x3_OES   0x93E0
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x3x3_OES   0x93E1
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4x3_OES   0x93E2
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4x4_OES   0x93E3
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4x4_OES   0x93E4
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5x4_OES   0x93E5
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5x5_OES   0x93E6
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5x5_OES   0x93E7
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6x5_OES   0x93E8
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6x6_OES   0x93E9

struct format_entry {
	unsigned int x;
	unsigned int y;
	unsigned int z;
	bool srgb;
	unsigned int format;
};

static const std::array<format_entry, 48> ASTC_FORMATS =
{{
	// 2D Linear RGB
	{ 4,  4,  1, false, GL_COMPRESSED_RGBA_ASTC_4x4},
	{ 5,  4,  1, false, GL_COMPRESSED_RGBA_ASTC_5x4},
	{ 5,  5,  1, false, GL_COMPRESSED_RGBA_ASTC_5x5},
	{ 6,  5,  1, false, GL_COMPRESSED_RGBA_ASTC_6x5},
	{ 6,  6,  1, false, GL_COMPRESSED_RGBA_ASTC_6x6},
	{ 8,  5,  1, false, GL_COMPRESSED_RGBA_ASTC_8x5},
	{ 8,  6,  1, false, GL_COMPRESSED_RGBA_ASTC_8x6},
	{ 8,  8,  1, false, GL_COMPRESSED_RGBA_ASTC_8x8},
	{10,  5,  1, false, GL_COMPRESSED_RGBA_ASTC_10x5},
	{10,  6,  1, false, GL_COMPRESSED_RGBA_ASTC_10x6},
	{10,  8,  1, false, GL_COMPRESSED_RGBA_ASTC_10x8},
	{10, 10,  1, false, GL_COMPRESSED_RGBA_ASTC_10x10},
	{12, 10,  1, false, GL_COMPRESSED_RGBA_ASTC_12x10},
	{12, 12,  1, false, GL_COMPRESSED_RGBA_ASTC_12x12},
	// 2D SRGB
	{ 4,  4,  1,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4},
	{ 5,  4,  1,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4},
	{ 5,  5,  1,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5},
	{ 6,  5,  1,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5},
	{ 6,  6,  1,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6},
	{ 8,  5,  1,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5},
	{ 8,  6,  1,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6},
	{ 8,  8,  1,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8},
	{10,  5,  1,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5},
	{10,  6,  1,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6},
	{10,  8,  1,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8},
	{10, 10,  1,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10},
	{12, 10,  1,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10},
	{12, 12,  1,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12},
	// 3D Linear RGB
	{ 3,  3,  3, false, GL_COMPRESSED_RGBA_ASTC_3x3x3_OES},
	{ 4,  3,  3, false, GL_COMPRESSED_RGBA_ASTC_4x3x3_OES},
	{ 4,  4,  3, false, GL_COMPRESSED_RGBA_ASTC_4x4x3_OES},
	{ 4,  4,  4, false, GL_COMPRESSED_RGBA_ASTC_4x4x4_OES},
	{ 5,  4,  4, false, GL_COMPRESSED_RGBA_ASTC_5x4x4_OES},
	{ 5,  5,  4, false, GL_COMPRESSED_RGBA_ASTC_5x5x4_OES},
	{ 5,  5,  5, false, GL_COMPRESSED_RGBA_ASTC_5x5x5_OES},
	{ 6,  5,  5, false, GL_COMPRESSED_RGBA_ASTC_6x5x5_OES},
	{ 6,  6,  5, false, GL_COMPRESSED_RGBA_ASTC_6x6x5_OES},
	{ 6,  6,  6, false, GL_COMPRESSED_RGBA_ASTC_6x6x6_OES},
	// 3D SRGB
	{ 3,  3,  3,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_3x3x3_OES},
	{ 4,  3,  3,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x3x3_OES},
	{ 4,  4,  3,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4x3_OES},
	{ 4,  4,  4,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4x4_OES},
	{ 5,  4,  4,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4x4_OES},
	{ 5,  5,  4,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5x4_OES},
	{ 5,  5,  5,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5x5_OES},
	{ 6,  5,  5,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5x5_OES},
	{ 6,  6,  5,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6x5_OES},
	{ 6,  6,  6,  true, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6x6_OES}
}};

static const format_entry* get_format(
	unsigned int format
) {
	for (auto& it : ASTC_FORMATS)
	{
		if (it.format == format)
		{
			return &it;
		}
	}
	return nullptr;
}

static unsigned int get_format(
	unsigned int x,
	unsigned int y,
	unsigned int z,
	bool srgb
) {
	for (auto& it : ASTC_FORMATS)
	{
		if ((it.x == x) && (it.y == y) && (it.z == z)  && (it.srgb == srgb))
		{
			return it.format;
		}
	}
	return 0;
}

struct ktx_header
{
	uint8_t magic[12];
	uint32_t endianness;		// should be 0x04030201; if it is instead 0x01020304, then the endianness of everything must be switched.
	uint32_t gl_type;			// 0 for compressed textures, otherwise value from table 3.2 (page 162) of OpenGL 4.0 spec
	uint32_t gl_type_size;		// size of data elements to do endianness swap on (1=endian-neutral data)
	uint32_t gl_format;			// 0 for compressed textures, otherwise value from table 3.3 (page 163) of OpenGLl spec
	uint32_t gl_internal_format;	// sized-internal-format, corresponding to table 3.12 to 3.14 (pages 182-185) of OpenGL spec
	uint32_t gl_base_internal_format;	// unsized-internal-format: corresponding to table 3.11 (page 179) of OpenGL spec
	uint32_t pixel_width;		// texture dimensions; not rounded up to block size for compressed.
	uint32_t pixel_height;		// must be 0 for 1D textures.
	uint32_t pixel_depth;		// must be 0 for 1D, 2D and cubemap textures.
	uint32_t number_of_array_elements;	// 0 if not a texture array
	uint32_t number_of_faces;	// 6 for cubemaps, 1 for non-cubemaps
	uint32_t number_of_mipmap_levels;	// 0 or 1 for non-mipmapped textures; 0 indicates that auto-mipmap-gen should be done at load time.
	uint32_t bytes_of_key_value_data;	// size in bytes of the key-and-value area immediately following the header.
};

// magic 12-byte sequence that must appear at the beginning of every KTX file.
uint8_t ktx_magic[12] = {
	0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
};

static void ktx_header_switch_endianness(ktx_header * kt)
{
	#define REV(x) kt->x = u32_byterev(kt->x)
	REV(endianness);
	REV(gl_type);
	REV(gl_type_size);
	REV(gl_format);
	REV(gl_internal_format);
	REV(gl_base_internal_format);
	REV(pixel_width);
	REV(pixel_height);
	REV(pixel_depth);
	REV(number_of_array_elements);
	REV(number_of_faces);
	REV(number_of_mipmap_levels);
	REV(bytes_of_key_value_data);
	#undef REV
}

static astcenc_image* load_ktx_uncompressed_image(
	const char* filename,
	unsigned int dim_pad,
	bool y_flip,
	bool& is_hdr,
	unsigned int& num_components
) {
	FILE *f = fopen(filename, "rb");
	if (!f)
	{
		printf("Failed to open file %s\n", filename);
		return nullptr;
	}

	ktx_header hdr;
	size_t header_bytes_read = fread(&hdr, 1, sizeof(hdr), f);

	if (header_bytes_read != sizeof(hdr))
	{
		printf("Failed to read header of KTX file %s\n", filename);
		fclose(f);
		return nullptr;
	}

	if (memcmp(hdr.magic, ktx_magic, 12) != 0 || (hdr.endianness != 0x04030201 && hdr.endianness != 0x01020304))
	{
		printf("File %s does not have a valid KTX header\n", filename);
		fclose(f);
		return nullptr;
	}

	int switch_endianness = 0;
	if (hdr.endianness == 0x01020304)
	{
		ktx_header_switch_endianness(&hdr);
		switch_endianness = 1;
	}

	if (hdr.gl_type == 0 || hdr.gl_format == 0)
	{
		printf("File %s appears to be compressed, not supported as input\n", filename);
		fclose(f);
		return nullptr;
	}

	// the formats we support are:

	// Cartesian product of gl_type=(UNSIGNED_BYTE, UNSIGNED_SHORT, HALF_FLOAT, FLOAT) x gl_format=(RED, RG, RGB, RGBA, BGR, BGRA)

	int components;
	switch (hdr.gl_format)
	{
	case GL_RED:
		components = 1;
		break;
	case GL_RG:
		components = 2;
		break;
	case GL_RGB:
		components = 3;
		break;
	case GL_RGBA:
		components = 4;
		break;
	case GL_BGR:
		components = 3;
		break;
	case GL_BGRA:
		components = 4;
		break;
	case GL_LUMINANCE:
		components = 1;
		break;
	case GL_LUMINANCE_ALPHA:
		components = 2;
		break;
	default:
		printf("KTX file %s has unsupported GL type\n", filename);
		fclose(f);
		return nullptr;
	};

	// Although these are set up later, we include a default initializer to remove warnings
	int bytes_per_component = 1;	// bytes per component in the KTX file.
	int bitness = 8;			// internal precision we will use in the codec.
	scanline_copy_method cm = R8_TO_RGBA8;

	switch (hdr.gl_type)
	{
	case GL_UNSIGNED_BYTE:
		{
			bitness = 8;
			bytes_per_component = 1;
			switch (hdr.gl_format)
			{
			case GL_RED:
				cm = R8_TO_RGBA8;
				break;
			case GL_RG:
				cm = RG8_TO_RGBA8;
				break;
			case GL_RGB:
				cm = RGB8_TO_RGBA8;
				break;
			case GL_RGBA:
				cm = RGBA8_TO_RGBA8;
				break;
			case GL_BGR:
				cm = BGR8_TO_RGBA8;
				break;
			case GL_BGRA:
				cm = BGRA8_TO_RGBA8;
				break;
			case GL_LUMINANCE:
				cm = L8_TO_RGBA8;
				break;
			case GL_LUMINANCE_ALPHA:
				cm = LA8_TO_RGBA8;
				break;
			}
			break;
		}
	case GL_UNSIGNED_SHORT:
		{
			bitness = 16;
			bytes_per_component = 2;
			switch (hdr.gl_format)
			{
			case GL_RED:
				cm = R16_TO_RGBA16F;
				break;
			case GL_RG:
				cm = RG16_TO_RGBA16F;
				break;
			case GL_RGB:
				cm = RGB16_TO_RGBA16F;
				break;
			case GL_RGBA:
				cm = RGBA16_TO_RGBA16F;
				break;
			case GL_BGR:
				cm = BGR16_TO_RGBA16F;
				break;
			case GL_BGRA:
				cm = BGRA16_TO_RGBA16F;
				break;
			case GL_LUMINANCE:
				cm = L16_TO_RGBA16F;
				break;
			case GL_LUMINANCE_ALPHA:
				cm = LA16_TO_RGBA16F;
				break;
			}
			break;
		}
	case GL_HALF_FLOAT:
		{
			bitness = 16;
			bytes_per_component = 2;
			switch (hdr.gl_format)
			{
			case GL_RED:
				cm = R16F_TO_RGBA16F;
				break;
			case GL_RG:
				cm = RG16F_TO_RGBA16F;
				break;
			case GL_RGB:
				cm = RGB16F_TO_RGBA16F;
				break;
			case GL_RGBA:
				cm = RGBA16F_TO_RGBA16F;
				break;
			case GL_BGR:
				cm = BGR16F_TO_RGBA16F;
				break;
			case GL_BGRA:
				cm = BGRA16F_TO_RGBA16F;
				break;
			case GL_LUMINANCE:
				cm = L16F_TO_RGBA16F;
				break;
			case GL_LUMINANCE_ALPHA:
				cm = LA16F_TO_RGBA16F;
				break;
			}
			break;
		}
	case GL_FLOAT:
		{
			bitness = 32;
			bytes_per_component = 4;
			switch (hdr.gl_format)
			{
			case GL_RED:
				cm = R32F_TO_RGBA16F;
				break;
			case GL_RG:
				cm = RG32F_TO_RGBA16F;
				break;
			case GL_RGB:
				cm = RGB32F_TO_RGBA16F;
				break;
			case GL_RGBA:
				cm = RGBA32F_TO_RGBA16F;
				break;
			case GL_BGR:
				cm = BGR32F_TO_RGBA16F;
				break;
			case GL_BGRA:
				cm = BGRA32F_TO_RGBA16F;
				break;
			case GL_LUMINANCE:
				cm = L32F_TO_RGBA16F;
				break;
			case GL_LUMINANCE_ALPHA:
				cm = LA32F_TO_RGBA16F;
				break;
			}
			break;
		}
	default:
		printf("KTX file %s has unsupported GL format\n", filename);
		fclose(f);
		return nullptr;
	}

	if (hdr.number_of_mipmap_levels > 1)
		printf("WARNING: KTX file %s has %d mipmap levels; only the first one will be encoded.\n", filename, hdr.number_of_mipmap_levels);

	if (hdr.number_of_array_elements > 1)
		printf("WARNING: KTX file %s contains a texture array with %d layers; only the first one will be encoded.\n", filename, hdr.number_of_array_elements);

	if (hdr.number_of_faces > 1)
		printf("WARNING: KTX file %s contains a cubemap with 6 faces; only the first one will be encoded.\n", filename);


	unsigned int dim_x = hdr.pixel_width;
	unsigned int dim_y = MAX(hdr.pixel_height, 1);
	unsigned int dim_z = MAX(hdr.pixel_depth, 1);

	// ignore the key/value data
	fseek(f, hdr.bytes_of_key_value_data, SEEK_CUR);

	uint32_t specified_bytes_of_surface = 0;
	size_t sb_read = fread(&specified_bytes_of_surface, 1, 4, f);
	if (sb_read != 4)
	{
		printf("Failed to read header of KTX file %s\n", filename);
		fclose(f);
		return nullptr;
	}

	if (switch_endianness)
	{
		specified_bytes_of_surface = u32_byterev(specified_bytes_of_surface);
	}

	// read the surface
	uint32_t xstride = bytes_per_component * components * dim_x;
	uint32_t ystride = xstride * dim_y;
	uint32_t computed_bytes_of_surface = dim_z * ystride;
	if (computed_bytes_of_surface != specified_bytes_of_surface)
	{
		fclose(f);
		printf("%s: KTX file inconsistency: computed surface size is %d bytes, but specified size is %d bytes\n", filename, computed_bytes_of_surface, specified_bytes_of_surface);
		return nullptr;
	}

	uint8_t *buf = new uint8_t[specified_bytes_of_surface];
	size_t bytes_read = fread(buf, 1, specified_bytes_of_surface, f);
	fclose(f);
	if (bytes_read != specified_bytes_of_surface)
	{
		delete[] buf;
		printf("Failed to read file %s\n", filename);
		return nullptr;
	}

	// perform an endianness swap on the surface if needed.
	if (switch_endianness)
	{
		if (hdr.gl_type_size == 2)
		{
			switch_endianness2(buf, specified_bytes_of_surface);
		}

		if (hdr.gl_type_size == 4)
		{
			switch_endianness4(buf, specified_bytes_of_surface);
		}
	}

	// then transfer data from the surface to our own image-data-structure.
	astcenc_image *astc_img = alloc_image(bitness, dim_x, dim_y, dim_z, dim_pad);

	for (unsigned int z = 0; z < dim_z; z++)
	{
		unsigned int zdst = (dim_z == 1) ? z : z + dim_pad;

		for (unsigned int y = 0; y < dim_y; y++)
		{
			unsigned int ymod = y_flip ? dim_y - y - 1 : y;
			unsigned int ydst = ymod + dim_pad;
			void *dst;

			if (astc_img->data_type == ASTCENC_TYPE_U8)
			{
				uint8_t*** data8 = static_cast<uint8_t***>(astc_img->data);
				dst = static_cast<void*>(data8[zdst][ydst] + 4 * dim_pad);
			}
			else // if (astc_img->data_type == ASTCENC_TYPE_F16)
			{
				assert(astc_img->data_type == ASTCENC_TYPE_F16);
				uint16_t*** data16 = static_cast<uint16_t***>(astc_img->data);
				dst = static_cast<void*>(data16[zdst][ydst] + 4 * dim_pad);
			}

			uint8_t *src = buf + (z * ystride) + (y * xstride);
			copy_scanline(dst, src, dim_x, cm);
		}
	}

	delete[] buf;
	fill_image_padding_area(astc_img);
	is_hdr = bitness == 32;
	num_components = components;
	return astc_img;
}

bool load_ktx_compressed_image(
	const char* filename,
	bool& is_srgb,
	astc_compressed_image& img
) {
	FILE *f = fopen(filename, "rb");
	if (!f)
	{
		printf("Failed to open file %s\n", filename);
		return true;
	}

	ktx_header hdr;
	size_t actual = fread(&hdr, 1, sizeof(hdr), f);
	if (actual != sizeof(hdr))
	{
		printf("Failed to read header from %s\n", filename);
		fclose(f);
		return true;
	}

	if (memcmp(hdr.magic, ktx_magic, 12) != 0 ||
	    (hdr.endianness != 0x04030201 && hdr.endianness != 0x01020304))
	{
		printf("File %s does not have a valid KTX header\n", filename);
		fclose(f);
		return true;
	}

	bool switch_endianness = false;
	if (hdr.endianness == 0x01020304)
	{
		switch_endianness = true;
		ktx_header_switch_endianness(&hdr);
	}

	if (hdr.gl_type != 0 || hdr.gl_format != 0 || hdr.gl_type_size != 1 ||
	    hdr.gl_base_internal_format != GL_RGBA)
	{
		printf("File %s is not a compressed ASTC file\n", filename);
		fclose(f);
		return true;
	}

	const format_entry* fmt = get_format(hdr.gl_internal_format);
	if (!fmt)
	{
		printf("File %s is not a compressed ASTC file\n", filename);
		fclose(f);
		return true;
	}

	// Skip over any key-value pairs
	int seekerr;
	seekerr = fseek(f, hdr.bytes_of_key_value_data, SEEK_CUR);
	if (seekerr)
	{
		printf("Failed to skip key-value pairs in %s\n", filename);
		fclose(f);
	}

	// Read the length of the data and endianess convert
	unsigned int data_len;
	actual = fread(&data_len, 1, sizeof(data_len), f);
	if (actual != sizeof(data_len))
	{
		printf("Failed to read mip 0 size from %s\n", filename);
		fclose(f);
		return true;
	}

	if (switch_endianness)
	{
		data_len = u32_byterev(data_len);
	}

	// Read the data
	unsigned char* data = new unsigned char[data_len];
	actual = fread(data, 1, data_len, f);
	if (actual != data_len)
	{
		printf("Failed to read mip 0 data from %s\n", filename);
		fclose(f);
		delete[] data;
		return true;
	}

	img.block_x = fmt->x;
	img.block_y = fmt->y;
	img.block_z = fmt->z == 0 ? 1 : fmt->z;

 	img.dim_x = hdr.pixel_width;
	img.dim_y = hdr.pixel_height;
	img.dim_z = hdr.pixel_depth == 0 ? 1 : hdr.pixel_depth;

	img.data_len = data_len;
	img.data = data;

	is_srgb = fmt->srgb;

	return false;
}


bool store_ktx_compressed_image(
	const astc_compressed_image& img,
	const char* filename,
	bool srgb
) {
	unsigned int fmt = get_format(img.block_x, img.block_y, img.block_z, srgb);

	ktx_header hdr;
	memcpy(hdr.magic, ktx_magic, 12);
	hdr.endianness = 0x04030201;
	hdr.gl_type = 0;
	hdr.gl_type_size = 1;
	hdr.gl_format = 0;
	hdr.gl_internal_format = fmt;
	hdr.gl_base_internal_format = GL_RGBA;
	hdr.pixel_width = img.dim_x;
	hdr.pixel_height = img.dim_y;
	hdr.pixel_depth = (img.dim_z == 1) ? 0 : img.dim_z;
	hdr.number_of_array_elements = 0;
	hdr.number_of_faces = 1;
	hdr.number_of_mipmap_levels = 1;
	hdr.bytes_of_key_value_data = 0;

	size_t expected = sizeof(ktx_header) + 4 + img.data_len;
	size_t actual = 0;

	FILE *wf = fopen(filename, "wb");
	actual += fwrite(&hdr, 1, sizeof(ktx_header), wf);
	actual += fwrite(&img.data_len, 1, 4, wf);
	actual += fwrite(img.data, 1, img.data_len, wf);
	fclose(wf);

	if (actual != expected)
	{
		return true;
	}

	return false;
}

static int store_ktx_uncompressed_image(
	const astcenc_image* img,
	const char* ktx_filename,
	int y_flip
) {
	unsigned int dim_x = img->dim_x;
	unsigned int dim_y = img->dim_y;
	unsigned int dim_z = img->dim_z;

	int bitness = img->data_type == ASTCENC_TYPE_U8 ? 8 : 16;
	int image_channels = determine_image_channels(img);

	ktx_header hdr;

	int gl_format_of_channels[4] = { GL_LUMINANCE, GL_LUMINANCE_ALPHA, GL_RGB, GL_RGBA };

	memcpy(hdr.magic, ktx_magic, 12);
	hdr.endianness = 0x04030201;
	hdr.gl_type = (bitness == 16) ? GL_HALF_FLOAT : GL_UNSIGNED_BYTE;
	hdr.gl_type_size = bitness / 8;
	hdr.gl_format = gl_format_of_channels[image_channels - 1];
	hdr.gl_internal_format = gl_format_of_channels[image_channels - 1];
	hdr.gl_base_internal_format = gl_format_of_channels[image_channels - 1];
	hdr.pixel_width = dim_x;
	hdr.pixel_height = dim_y;
	hdr.pixel_depth = (dim_z == 1) ? 0 : dim_z;
	hdr.number_of_array_elements = 0;
	hdr.number_of_faces = 1;
	hdr.number_of_mipmap_levels = 1;
	hdr.bytes_of_key_value_data = 0;

	// collect image data to write
	uint8_t ***row_pointers8 = nullptr;
	uint16_t ***row_pointers16 = nullptr;
	if (bitness == 8)
	{
		row_pointers8 = new uint8_t **[dim_z];
		row_pointers8[0] = new uint8_t *[dim_y * dim_z];
		row_pointers8[0][0] = new uint8_t[dim_x * dim_y * dim_z * image_channels + 3];

		for (unsigned int z = 1; z < dim_z; z++)
		{
			row_pointers8[z] = row_pointers8[0] + dim_y * z;
			row_pointers8[z][0] = row_pointers8[0][0] + dim_y * dim_x * image_channels * z;
		}

		for (unsigned int z = 0; z < dim_z; z++)
		{
			for (unsigned int y = 1; y < dim_y; y++)
			{
				row_pointers8[z][y] = row_pointers8[z][0] + dim_x * image_channels * y;
			}
		}

		uint8_t*** data8 = static_cast<uint8_t***>(img->data);
		for (unsigned int z = 0; z < dim_z; z++)
		{
			for (unsigned int y = 0; y < dim_y; y++)
			{
				int ym = y_flip ? dim_y - y - 1 : y;
				switch (image_channels)
				{
				case 1:		// single-component, treated as Luminance
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers8[z][y][x] = data8[z][ym][4 * x];
					}
					break;
				case 2:		// two-component, treated as Luminance-Alpha
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers8[z][y][2 * x]     = data8[z][ym][4 * x];
						row_pointers8[z][y][2 * x + 1] = data8[z][ym][4 * x + 3];
					}
					break;
				case 3:		// three-component, treated a
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers8[z][y][3 * x]     = data8[z][ym][4 * x];
						row_pointers8[z][y][3 * x + 1] = data8[z][ym][4 * x + 1];
						row_pointers8[z][y][3 * x + 2] = data8[z][ym][4 * x + 2];
					}
					break;
				case 4:		// four-component, treated as RGBA
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers8[z][y][4 * x]     = data8[z][ym][4 * x];
						row_pointers8[z][y][4 * x + 1] = data8[z][ym][4 * x + 1];
						row_pointers8[z][y][4 * x + 2] = data8[z][ym][4 * x + 2];
						row_pointers8[z][y][4 * x + 3] = data8[z][ym][4 * x + 3];
					}
					break;
				}
			}
		}
	}
	else						// if bitness == 16
	{
		row_pointers16 = new uint16_t **[dim_z];
		row_pointers16[0] = new uint16_t *[dim_y * dim_z];
		row_pointers16[0][0] = new uint16_t[dim_x * dim_y * dim_z * image_channels + 1];

		for (unsigned int z = 1; z < dim_z; z++)
		{
			row_pointers16[z] = row_pointers16[0] + dim_y * z;
			row_pointers16[z][0] = row_pointers16[0][0] + dim_y * dim_x * image_channels * z;
		}

		for (unsigned int z = 0; z < dim_z; z++)
		{
			for (unsigned int y = 1; y < dim_y; y++)
			{
				row_pointers16[z][y] = row_pointers16[z][0] + dim_x * image_channels * y;
			}
		}

		uint16_t*** data16 = static_cast<uint16_t***>(img->data);
		for (unsigned int z = 0; z < dim_z; z++)
		{
			for (unsigned int y = 0; y < dim_y; y++)
			{
				int ym = y_flip ? dim_y - y - 1 : y;
				switch (image_channels)
				{
				case 1:		// single-component, treated as Luminance
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers16[z][y][x] = data16[z][ym][4 * x];
					}
					break;
				case 2:		// two-component, treated as Luminance-Alpha
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers16[z][y][2 * x]     = data16[z][ym][4 * x];
						row_pointers16[z][y][2 * x + 1] = data16[z][ym][4 * x + 3];
					}
					break;
				case 3:		// three-component, treated as RGB
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers16[z][y][3 * x]     = data16[z][ym][4 * x];
						row_pointers16[z][y][3 * x + 1] = data16[z][ym][4 * x + 1];
						row_pointers16[z][y][3 * x + 2] = data16[z][ym][4 * x + 2];
					}
					break;
				case 4:		// four-component, treated as RGBA
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers16[z][y][4 * x]     = data16[z][ym][4 * x];
						row_pointers16[z][y][4 * x + 1] = data16[z][ym][4 * x + 1];
						row_pointers16[z][y][4 * x + 2] = data16[z][ym][4 * x + 2];
						row_pointers16[z][y][4 * x + 3] = data16[z][ym][4 * x + 3];
					}
					break;
				}
			}
		}
	}

	int retval = image_channels + (bitness == 16 ? 0x80 : 0);
	uint32_t image_bytes = dim_x * dim_y * dim_z * image_channels * (bitness / 8);
	uint32_t image_write_bytes = (image_bytes + 3) & ~3;

	FILE *wf = fopen(ktx_filename, "wb");
	if (wf)
	{
		void *dataptr = (bitness == 16) ? (void *)(row_pointers16[0][0]) : (void *)(row_pointers8[0][0]);

		size_t expected_bytes_written = sizeof(ktx_header) + image_write_bytes + 4;
		size_t hdr_bytes_written = fwrite(&hdr, 1, sizeof(ktx_header), wf);
		size_t bytecount_bytes_written = fwrite(&image_bytes, 1, 4, wf);
		size_t data_bytes_written = fwrite(dataptr, 1, image_write_bytes, wf);
		fclose(wf);
		if (hdr_bytes_written + bytecount_bytes_written + data_bytes_written != expected_bytes_written)
			retval = -1;
	}
	else
	{
		retval = -1;
	}

	if (row_pointers8)
	{
		delete[] row_pointers8[0][0];
		delete[] row_pointers8[0];
		delete[] row_pointers8;
	}

	if (row_pointers16)
	{
		delete[] row_pointers16[0][0];
		delete[] row_pointers16[0];
		delete[] row_pointers16;
	}

	return retval;
}

/*
	Loader for DDS files.

	Note that after the header, data are densely packed with no padding;
	in the case of multiple surfaces, they appear one after another in
	the file, again with no padding.

	This code is NOT endian-neutral.
*/
struct dds_pixelformat
{
	uint32_t size;				// structure size, set to 32.
	/*
	   flags bits are a combination of the following: 0x1 : Texture contains alpha data 0x2 : ---- (older files: texture contains alpha data, for Alpha-only texture) 0x4 : The fourcc field is valid,
	   indicating a compressed or DX10 texture format 0x40 : texture contains uncompressed RGB data 0x200 : ---- (YUV in older files) 0x20000 : Texture contains Luminance data (can be combined with
	   0x1 for Lum-Alpha) */
	uint32_t flags;
	uint32_t fourcc;			// "DX10" to indicate a DX10 format, "DXTn" for the DXT formats
	uint32_t rgbbitcount;		// number of bits per texel; up to 32 for non-DX10 formats.
	uint32_t rbitmask;			// bitmap indicating position of red/luminance color component
	uint32_t gbitmask;			// bitmap indicating position of green color component
	uint32_t bbitmask;			// bitmap indicating position of blue color component
	uint32_t abitmask;			// bitmap indicating position of alpha color component
};

struct dds_header
{
	uint32_t size;				// header size; must be exactly 124.
	/*
	   flag field is an OR or the following bits, that indicate fields containing valid data:
		1: caps/caps2/caps3/caps4 (set in all DDS files, ignore on read)
		2: height (set in all DDS files, ignore on read)
		4: width (set in all DDS files, ignore on read)
		8: pitch (for uncompressed texture)
		0x1000: the pixel format field (set in all DDS files, ignore on read)
		0x20000: mipmap count (for mipmapped textures with >1 level)
		0x80000: pitch (for compressed texture)
		0x800000: depth (for 3d textures)
	*/
	uint32_t flags;
	uint32_t height;
	uint32_t width;
	uint32_t pitch_or_linear_size;	// scanline pitch for uncompressed; total size in bytes for compressed
	uint32_t depth;
	uint32_t mipmapcount;
	// unused, set to 0
	uint32_t reserved1[11];
	dds_pixelformat ddspf;
	/*
	   caps field is an OR of the following values:
		8 : should be set for a file that contains more than 1 surface (ignore on read)
		0x400000 : should be set for a mipmapped texture
		0x1000 : should be set if the surface is a texture at all (all DDS files, ignore on read)
	*/
	uint32_t caps;
	/*
	   caps2 field is an OR of the following values:
		0x200 : texture is cubemap
		0x400 : +X face of cubemap is present
		0x800 : -X face of cubemap is present
		0x1000 : +Y face of cubemap is present
		0x2000 : -Y face of cubemap is present
		0x4000 : +Z face of cubemap is present
		0x8000 : -Z face of cubemap is present
		0x200000 : texture is a 3d texture.
	*/
	uint32_t caps2;
	// unused, set to 0
	uint32_t caps3;
	// unused, set to 0
	uint32_t caps4;
	// unused, set to 0
	uint32_t reserved2;
};

struct dds_header_dx10
{
	uint32_t dxgi_format;
	uint32_t resource_dimension;	// 2=1d-texture, 3=2d-texture or cubemap, 4=3d-texture
	uint32_t misc_flag;			// 4 if cubemap, else 0
	uint32_t array_size;		// size of array in case of a texture array; set to 1 for a non-array
	uint32_t reserved;			// set to 0.
};

#define DDS_MAGIC 0x20534444
#define DX10_MAGIC 0x30315844

astcenc_image* load_dds_uncompressed_image(
	const char* filename,
	unsigned int dim_pad,
	bool y_flip,
	bool& is_hdr,
	unsigned int& num_components
) {
	FILE *f = fopen(filename, "rb");
	if (!f)
	{
		printf("Failed to open file %s\n", filename);
		return nullptr;
	}

	uint8_t magic[4];

	dds_header hdr;
	size_t magic_bytes_read = fread(magic, 1, 4, f);
	size_t header_bytes_read = fread(&hdr, 1, sizeof(hdr), f);
	if (magic_bytes_read != 4 || header_bytes_read != sizeof(hdr))
	{
		printf("Failed to read header of DDS file %s\n", filename);
		fclose(f);
		return nullptr;
	}

	uint32_t magicx = magic[0] | (magic[1] << 8) | (magic[2] << 16) | (magic[3] << 24);

	if (magicx != DDS_MAGIC || hdr.size != 124)
	{
		printf("File %s does not have a valid DDS header\n", filename);
		fclose(f);
		return nullptr;
	}

	int use_dx10_header = 0;
	if (hdr.ddspf.flags & 4)
	{
		if (hdr.ddspf.fourcc == DX10_MAGIC)
		{
			use_dx10_header = 1;
		}
		else
		{
			printf("DDS file %s is compressed, not supported\n", filename);
			fclose(f);
			return nullptr;
		}
	}

	dds_header_dx10 dx10_header;
	if (use_dx10_header)
	{
		size_t dx10_header_bytes_read = fread(&dx10_header, 1, sizeof(dx10_header), f);
		if (dx10_header_bytes_read != sizeof(dx10_header))
		{
			printf("Failed to read header of DDS file %s\n", filename);
			fclose(f);
			return nullptr;
		}
	}

	unsigned int dim_x = hdr.width;
	unsigned int dim_y = hdr.height;
	unsigned int dim_z = (hdr.flags & 0x800000) ? hdr.depth : 1;

	int bitness;				// the bitcount that we will use internally in the codec
	int bytes_per_component;	// the bytes per component in the DDS file itself
	int components;
	int copy_method;

	// figure out the format actually used in the DDS file.
	if (use_dx10_header)
	{
		// DX10 header present; use the DXGI format.
		#define DXGI_FORMAT_R32G32B32A32_FLOAT   2
		#define DXGI_FORMAT_R32G32B32_FLOAT      6
		#define DXGI_FORMAT_R16G16B16A16_FLOAT  10
		#define DXGI_FORMAT_R16G16B16A16_UNORM  11
		#define DXGI_FORMAT_R32G32_FLOAT        16
		#define DXGI_FORMAT_R8G8B8A8_UNORM      28
		#define DXGI_FORMAT_R16G16_FLOAT    34
		#define DXGI_FORMAT_R16G16_UNORM    35
		#define DXGI_FORMAT_R32_FLOAT       41
		#define DXGI_FORMAT_R8G8_UNORM      49
		#define DXGI_FORMAT_R16_FLOAT       54
		#define DXGI_FORMAT_R16_UNORM       56
		#define DXGI_FORMAT_R8_UNORM        61
		#define DXGI_FORMAT_B8G8R8A8_UNORM  86
		#define DXGI_FORMAT_B8G8R8X8_UNORM  87

		struct dxgi_params
		{
			int bitness;
			int bytes_per_component;
			int components;
			int copy_method;
			uint32_t dxgi_format_number;
		};

		static const dxgi_params format_params[] = {
			{16, 4, 4, RGBA32F_TO_RGBA16F, DXGI_FORMAT_R32G32B32A32_FLOAT},
			{16, 4, 3, RGB32F_TO_RGBA16F, DXGI_FORMAT_R32G32B32_FLOAT},
			{16, 2, 4, RGBA16F_TO_RGBA16F, DXGI_FORMAT_R16G16B16A16_FLOAT},
			{16, 2, 4, RGBA16_TO_RGBA16F, DXGI_FORMAT_R16G16B16A16_UNORM},
			{16, 4, 2, RG32F_TO_RGBA16F, DXGI_FORMAT_R32G32_FLOAT},
			{8, 1, 4, RGBA8_TO_RGBA8, DXGI_FORMAT_R8G8B8A8_UNORM},
			{16, 2, 2, RG16F_TO_RGBA16F, DXGI_FORMAT_R16G16_FLOAT},
			{16, 2, 2, RG16_TO_RGBA16F, DXGI_FORMAT_R16G16_UNORM},
			{16, 4, 1, R32F_TO_RGBA16F, DXGI_FORMAT_R32_FLOAT},
			{8, 1, 2, RG8_TO_RGBA8, DXGI_FORMAT_R8G8_UNORM},
			{16, 2, 1, R16F_TO_RGBA16F, DXGI_FORMAT_R16_FLOAT},
			{16, 2, 1, R16_TO_RGBA16F, DXGI_FORMAT_R16_UNORM},
			{8, 1, 1, R8_TO_RGBA8, DXGI_FORMAT_R8_UNORM},
			{8, 1, 4, BGRA8_TO_RGBA8, DXGI_FORMAT_B8G8R8A8_UNORM},
			{8, 1, 4, BGRX8_TO_RGBA8, DXGI_FORMAT_B8G8R8X8_UNORM},
		};

		int dxgi_modes_supported = sizeof(format_params) / sizeof(format_params[0]);
		int did_select_format = 0;
		for (int i = 0; i < dxgi_modes_supported; i++)
		{
			if (dx10_header.dxgi_format == format_params[i].dxgi_format_number)
			{
				bitness = format_params[i].bitness;
				bytes_per_component = format_params[i].bytes_per_component;
				components = format_params[i].components;
				copy_method = format_params[i].copy_method;
				did_select_format = 1;
				break;
			}
		}

		if (!did_select_format)
		{
			printf("DDS file %s: DXGI format not supported by codec\n", filename);
			fclose(f);
			return nullptr;
		}
	}
	else
	{
		// No DX10 header present. Then try to match the bitcount and bitmask against
		// a set of prepared patterns.
		uint32_t flags = hdr.ddspf.flags;
		uint32_t bitcount = hdr.ddspf.rgbbitcount;
		uint32_t rmask = hdr.ddspf.rbitmask;
		uint32_t gmask = hdr.ddspf.gbitmask;
		uint32_t bmask = hdr.ddspf.bbitmask;
		uint32_t amask = hdr.ddspf.abitmask;

		// RGBA-unorm8
		if ((flags & 0x41) == 0x41 && bitcount == 32 && rmask == 0xFF && gmask == 0xFF00 && bmask == 0xFF0000 && amask == 0xFF000000)
		{
			bytes_per_component = 1;
			components = 4;
			copy_method = RGBA8_TO_RGBA8;
		}
		// BGRA-unorm8
		else if ((flags & 0x41) == 0x41 && bitcount == 32 && rmask == 0xFF0000 && gmask == 0xFF00 && bmask == 0xFF && amask == 0xFF000000)
		{
			bytes_per_component = 1;
			components = 4;
			copy_method = BGRA8_TO_RGBA8;
		}
		// RGBX-unorm8
		else if ((flags & 0x40) && bitcount == 32 && rmask == 0xFF && gmask == 0xFF00 && bmask == 0xFF0000)
		{
			bytes_per_component = 1;
			components = 4;
			copy_method = RGBX8_TO_RGBA8;
		}
		// BGRX-unorm8
		else if ((flags & 0x40) && bitcount == 32 && rmask == 0xFF0000 && gmask == 0xFF00 && bmask == 0xFF)
		{
			bytes_per_component = 1;
			components = 4;
			copy_method = BGRX8_TO_RGBA8;
		}
		// RGB-unorm8
		else if ((flags & 0x40) && bitcount == 24 && rmask == 0xFF && gmask == 0xFF00 && bmask == 0xFF0000)
		{
			bytes_per_component = 1;
			components = 3;
			copy_method = RGB8_TO_RGBA8;
		}
		// BGR-unorm8
		else if ((flags & 0x40) && bitcount == 24 && rmask == 0xFF0000 && gmask == 0xFF00 && bmask == 0xFF)
		{
			bytes_per_component = 1;
			components = 3;
			copy_method = BGR8_TO_RGBA8;
		}
		// RG-unorm16
		else if ((flags & 0x40) && bitcount == 16 && rmask == 0xFFFF && gmask == 0xFFFF0000)
		{
			bytes_per_component = 2;
			components = 2;
			copy_method = RG16_TO_RGBA16F;
		}
		// A8L8
		else if ((flags & 0x20001) == 0x20001 && bitcount == 16 && rmask == 0xFF && amask == 0xFF00)
		{
			bytes_per_component = 1;
			components = 2;
			copy_method = LA8_TO_RGBA8;
		}
		// L8
		else if ((flags & 0x20000) && bitcount == 8 && rmask == 0xFF)
		{
			bytes_per_component = 1;
			components = 1;
			copy_method = L8_TO_RGBA8;
		}
		// L16
		else if ((flags & 0x20000) && bitcount == 16 && rmask == 0xFFFF)
		{
			bytes_per_component = 2;
			components = 1;
			copy_method = L16_TO_RGBA16F;
		}
		else
		{
			printf("DDS file %s: Non-DXGI format not supported by codec\n", filename);
			fclose(f);
			return nullptr;
		}

		bitness = bytes_per_component * 8;
	}

	// then, load the actual file.
	uint32_t xstride = bytes_per_component * components * dim_x;
	uint32_t ystride = xstride * dim_y;
	uint32_t bytes_of_surface = ystride * dim_z;

	uint8_t *buf = new uint8_t[bytes_of_surface];
	size_t bytes_read = fread(buf, 1, bytes_of_surface, f);
	fclose(f);
	if (bytes_read != bytes_of_surface)
	{
		delete[] buf;
		printf("Failed to read file %s\n", filename);
		return nullptr;
	}

	// then transfer data from the surface to our own image-data-structure.
	astcenc_image *astc_img = alloc_image(bitness, dim_x, dim_y, dim_z, dim_pad);

	for (unsigned int z = 0; z < dim_z; z++)
	{
		unsigned int zdst = dim_z == 1 ? z : z + dim_pad;

		for (unsigned int y = 0; y < dim_y; y++)
		{
			unsigned int ymod = y_flip ? dim_y - y - 1 : y;
			unsigned int ydst = ymod + dim_pad;
			void* dst;

			if (astc_img->data_type == ASTCENC_TYPE_U8)
			{
				uint8_t*** data8 = static_cast<uint8_t***>(astc_img->data);
				dst = static_cast<void*>(data8[zdst][ydst] + 4 * dim_pad);
			}
			else // if (astc_img->data_type == ASTCENC_TYPE_F16)
			{
				assert(astc_img->data_type == ASTCENC_TYPE_F16);
				uint16_t*** data16 = static_cast<uint16_t***>(astc_img->data);
				dst = static_cast<void*>(data16[zdst][ydst] + 4 * dim_pad);
			}

			uint8_t *src = buf + (z * ystride) + (y * xstride);
			copy_scanline(dst, src, dim_x, copy_method);
		}
	}

	delete[] buf;
	fill_image_padding_area(astc_img);
	is_hdr = bitness == 16;
	num_components = components;
	return astc_img;
}

static int store_dds_uncompressed_image(
	const astcenc_image* img,
	const char* dds_filename,
	int y_flip
) {
	unsigned int dim_x = img->dim_x;
	unsigned int dim_y = img->dim_y;
	unsigned int dim_z = img->dim_z;

	int bitness = img->data_type == ASTCENC_TYPE_U8 ? 8 : 16;
	int image_channels = (bitness == 16) ? 4 : determine_image_channels(img);


	// DDS-pixel-format structures to use when storing LDR image with 1,2,3 or 4 components.
	static const dds_pixelformat format_of_image_channels[4] =
	{
		{32, 0x20000, 0, 8, 0xFF, 0, 0, 0},	// luminance
		{32, 0x20001, 0, 16, 0xFF, 0, 0, 0xFF00},	// L8A8
		{32, 0x40, 0, 24, 0xFF, 0xFF00, 0xFF0000, 0},	// RGB8
		{32, 0x41, 0, 32, 0xFF, 0xFF00, 0xFF0000, 0xFF000000}	// RGBA8
	};

	// DDS-pixel-format structures to use when storing HDR image.
	static const dds_pixelformat dxt10_diverter =
	{
		32, 4, DX10_MAGIC, 0, 0, 0, 0, 0
	};

	// header handling. We will write:
	// * DDS magic value
	// * DDS header
	// * DDS DX10 header, if the file is floating-point
	// * pixel data.

	// main header data
	dds_header hdr;
	hdr.size = 124;
	hdr.flags = 0x100F | (dim_z > 1 ? 0x800000 : 0);
	hdr.height = dim_y;
	hdr.width = dim_x;
	hdr.pitch_or_linear_size = image_channels * (bitness / 8) * dim_x;
	hdr.depth = dim_z;
	hdr.mipmapcount = 1;
	for (unsigned int i = 0; i < 11; i++)
	{
		hdr.reserved1[i] = 0;
	}
	hdr.caps = 0x1000;
	hdr.caps2 = (dim_z > 1) ? 0x200000 : 0;
	hdr.caps3 = 0;
	hdr.caps4 = 0;

	// pixel-format data
	if (bitness == 8)
	{
		hdr.ddspf = format_of_image_channels[image_channels - 1];
	}
	else
	{
		hdr.ddspf = dxt10_diverter;
	}

	// DX10 data
	dds_header_dx10 dx10;
	dx10.dxgi_format = DXGI_FORMAT_R16G16B16A16_FLOAT;
	dx10.resource_dimension = (dim_z > 1) ? 4 : 3;
	dx10.misc_flag = 0;
	dx10.array_size = 1;
	dx10.reserved = 0;

	// collect image data to write
	uint8_t ***row_pointers8 = nullptr;
	uint16_t ***row_pointers16 = nullptr;

	if (bitness == 8)
	{
		row_pointers8 = new uint8_t **[dim_z];
		row_pointers8[0] = new uint8_t *[dim_y * dim_z];
		row_pointers8[0][0] = new uint8_t[dim_x * dim_y * dim_z * image_channels];

		for (unsigned int z = 1; z < dim_z; z++)
		{
			row_pointers8[z] = row_pointers8[0] + dim_y * z;
			row_pointers8[z][0] = row_pointers8[0][0] + dim_y * dim_z * image_channels * z;
		}

		for (unsigned int z = 0; z < dim_z; z++)
		{
			for (unsigned int y = 1; y < dim_y; y++)
			{
				row_pointers8[z][y] = row_pointers8[z][0] + dim_x * image_channels * y;
			}
		}

		uint8_t*** data8 = static_cast<uint8_t***>(img->data);
		for (unsigned int z = 0; z < dim_z; z++)
		{
			for (unsigned int y = 0; y < dim_y; y++)
			{
				int ym = y_flip ? dim_y - y - 1 : y;
				switch (image_channels)
				{
				case 1:		// single-component, treated as Luminance
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers8[z][y][x] = data8[z][ym][4 * x];
					}
					break;
				case 2:		// two-component, treated as Luminance-Alpha
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers8[z][y][2 * x]     = data8[z][ym][4 * x];
						row_pointers8[z][y][2 * x + 1] = data8[z][ym][4 * x + 3];
					}
					break;
				case 3:		// three-component, treated as RGB
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers8[z][y][3 * x]     = data8[z][ym][4 * x];
						row_pointers8[z][y][3 * x + 1] = data8[z][ym][4 * x + 1];
						row_pointers8[z][y][3 * x + 2] = data8[z][ym][4 * x + 2];
					}
					break;
				case 4:		// four-component, treated as RGBA
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers8[z][y][4 * x]     = data8[z][ym][4 * x];
						row_pointers8[z][y][4 * x + 1] = data8[z][ym][4 * x + 1];
						row_pointers8[z][y][4 * x + 2] = data8[z][ym][4 * x + 2];
						row_pointers8[z][y][4 * x + 3] = data8[z][ym][4 * x + 3];
					}
					break;
				}
			}
		}
	}
	else						// if bitness == 16
	{
		row_pointers16 = new uint16_t **[dim_z];
		row_pointers16[0] = new uint16_t *[dim_y * dim_z];
		row_pointers16[0][0] = new uint16_t[dim_x * dim_y * dim_z * image_channels];

		for (unsigned int z = 1; z < dim_z; z++)
		{
			row_pointers16[z] = row_pointers16[0] + dim_y * z;
			row_pointers16[z][0] = row_pointers16[0][0] + dim_y * dim_x * image_channels * z;
		}

		for (unsigned int z = 0; z < dim_z; z++)
		{
			for (unsigned int y = 1; y < dim_y; y++)
			{
				row_pointers16[z][y] = row_pointers16[z][0] + dim_x * image_channels * y;
			}
		}

		uint16_t*** data16 = static_cast<uint16_t***>(img->data);
		for (unsigned int z = 0; z < dim_z; z++)
		{
			for (unsigned int y = 0; y < dim_y; y++)
			{
				int ym = y_flip ? dim_y - y - 1: y;
				switch (image_channels)
				{
				case 1:		// single-component, treated as Luminance
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers16[z][y][x] = data16[z][ym][4 * x];
					}
					break;
				case 2:		// two-component, treated as Luminance-Alpha
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers16[z][y][2 * x]     = data16[z][ym][4 * x];
						row_pointers16[z][y][2 * x + 1] = data16[z][ym][4 * x + 3];
					}
					break;
				case 3:		// three-component, treated as RGB
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers16[z][y][3 * x]     = data16[z][ym][4 * x];
						row_pointers16[z][y][3 * x + 1] = data16[z][ym][4 * x + 1];
						row_pointers16[z][y][3 * x + 2] = data16[z][ym][4 * x + 2];
					}
					break;
				case 4:		// four-component, treated as RGBA
					for (unsigned int x = 0; x < dim_x; x++)
					{
						row_pointers16[z][y][4 * x]     = data16[z][ym][4 * x];
						row_pointers16[z][y][4 * x + 1] = data16[z][ym][4 * x + 1];
						row_pointers16[z][y][4 * x + 2] = data16[z][ym][4 * x + 2];
						row_pointers16[z][y][4 * x + 3] = data16[z][ym][4 * x + 3];
					}
					break;
				}
			}
		}
	}

	int retval = image_channels;
	uint32_t image_bytes = dim_x * dim_y * dim_z * image_channels * (bitness / 8);

	uint32_t dds_magic = DDS_MAGIC;

	FILE *wf = fopen(dds_filename, "wb");
	if (wf)
	{
		void *dataptr = (bitness == 16) ? (void *)(row_pointers16[0][0]) : (void *)(row_pointers8[0][0]);

		size_t expected_bytes_written = 4 + sizeof(dds_header) + (bitness > 8 ? sizeof(dds_header_dx10) : 0) + image_bytes;

		size_t magic_bytes_written = fwrite(&dds_magic, 1, 4, wf);
		size_t hdr_bytes_written = fwrite(&hdr, 1, sizeof(dds_header), wf);

		size_t dx10_bytes_written;
		if (bitness > 8)
		{
			dx10_bytes_written = fwrite(&dx10, 1, sizeof(dx10), wf);
		}
		else
		{
			dx10_bytes_written = 0;
		}

		size_t data_bytes_written = fwrite(dataptr, 1, image_bytes, wf);

		fclose(wf);
		if (magic_bytes_written + hdr_bytes_written + dx10_bytes_written + data_bytes_written != expected_bytes_written)
		{
			retval = -1;
		}
	}
	else
	{
		retval = -1;
	}

	if (row_pointers8)
	{
		delete[] row_pointers8[0][0];
		delete[] row_pointers8[0];
		delete[] row_pointers8;
	}

	if (row_pointers16)
	{
		delete[] row_pointers16[0][0];
		delete[] row_pointers16[0];
		delete[] row_pointers16;
	}

	return retval;
}

/***************************************************************************

Main image load/store functions

We have specialized loaders for DDS and KTX; for other formats,
we use stb_image. This image loader will choose one based on filename.

We have specialized image storer for DDS and KTX; for OpenEXR,
we use tinyexr; for TGA, BMP and PNG, we use stb_image_write.

***************************************************************************/






// descriptors for each image/texture file format that we support loading of - endings and
// loader function. The last entry is a catch-all to use when nothing else matches;
// this will result in an attempt to use stb_image to load the image.
static const struct {
	const char* ending1;
	const char* ending2;
	astcenc_image* (*loader_func)(const char*, unsigned int, bool, bool&, unsigned int&);
} loader_descs[] = {
	// HDR formats
	{".exr",   ".EXR",  load_image_with_tinyexr },
	// Container formats
	{".ktx",   ".KTX",  load_ktx_uncompressed_image },
	{".dds",   ".DDS",  load_dds_uncompressed_image },
	// Generic catch all; this one must be last in the list
	{ nullptr, nullptr, load_image_with_stb }
};

static const int loader_descr_count = sizeof(loader_descs) / sizeof(loader_descs[0]);

// descriptors for each image/texture file format that we support storing to to - endings,
// enforced-bitness, and storer function.
static const struct
{
	const char *ending1;
	const char *ending2;
	const char *file_format_name;
	int enforced_bitness;
	int (*storer_func)(const astcenc_image *output_image, const char *output_filename, int y_flip);
} storer_descs[] = {
	// LDR formats
	{".bmp", ".BMP", "BMP",             8, store_bmp_image_with_stb},
	{".png", ".PNG", "PNG",             8, store_png_image_with_stb},
	{".tga", ".TGA", "Targa",           8, store_tga_image_with_stb},
	// HDR formats
	{".exr", ".EXR", "OpenEXR",        16, store_exr_image_with_tinyexr},
	{".hdr", ".HDR", "Radiance HDR",   16, store_hdr_image_with_stb},
	// Container formats
	{".dds", ".DDS", "DirectDraw DDS", -1, store_dds_uncompressed_image},
	{".ktx", ".KTX", "Khronos KTX",    -1, store_ktx_uncompressed_image}
};

static const int storer_descr_count = sizeof(storer_descs) / sizeof(storer_descs[0]);

// check from filename ending what the enforced bitness of the format-to-store is.
// May return:
//  8:  enforced 8-bit UNOR8
//  16: enforced 16-bit FP16
//  -1: no format enforced
// If the format has an unrecognized ending, an error message is produced.
// Lack of an ending is likely to result from a write to /dev/null
// or some other non-file thing; for this, we use the KTX format.

int get_output_filename_enforced_bitness(
	const char*output_filename
) {
	const char *eptr = strrchr(output_filename, '.');
	if (!eptr)
	{
		return -1;
	}

	for (int i = 0; i < storer_descr_count; i++)
	{
		if (strcmp(eptr, storer_descs[i].ending1) == 0
		 || strcmp(eptr, storer_descs[i].ending2) == 0)
		{
			return storer_descs[i].enforced_bitness;
		}
	}

	printf("ERROR: Unknown file extension for output file: %s\n", eptr);
	exit(1);
}

astcenc_image* load_ncimage(
	const char* filename,
	unsigned int dim_pad,
	bool y_flip,
	bool& is_hdr,
	unsigned int& num_components
) {
	// Get the file extension
	const char* eptr = strrchr(filename, '.');
	if (!eptr)
	{
		eptr = filename;
	}

	// Scan through descriptors until a matching loader is found
	for (unsigned int i = 0; i < loader_descr_count; i++)
	{
		if (loader_descs[i].ending1 == nullptr
			|| strcmp(eptr, loader_descs[i].ending1) == 0
			|| strcmp(eptr, loader_descs[i].ending2) == 0)
		{
			return loader_descs[i].loader_func(filename, dim_pad, y_flip, is_hdr, num_components);
		}
	}

	// Should never reach here - stb_image provides a generic handler
	return nullptr;
}

int store_ncimage(
	const astcenc_image* output_image,
	const char* output_filename,
	const char** file_format_name,
	int y_flip
) {
	const char* eptr = strrchr(output_filename, '.');
	if (!eptr)
	{
		eptr = ".ktx"; // use KTX file format if we don't have an ending.
	}

	for (int i=0; i < storer_descr_count; i++)
	{
		if (strcmp(eptr, storer_descs[i].ending1) == 0
		 || strcmp(eptr, storer_descs[i].ending2) == 0)
		{
			*file_format_name = storer_descs[i].file_format_name;
			return storer_descs[i].storer_func(output_image, output_filename, y_flip);
		}
	}

	// Should never reach here - get_output_filename_enforced_bitness should
	// have acted as a preflight check
	return -1;
}

/* ============================================================================
	ASTC compressed file loading
============================================================================ */
struct astc_header
{
	uint8_t magic[4];
	uint8_t block_x;
	uint8_t block_y;
	uint8_t block_z;
	uint8_t dim_x[3];			// dims = dim[0] + (dim[1] << 8) + (dim[2] << 16)
	uint8_t dim_y[3];			// Sizes are given in texels;
	uint8_t dim_z[3];			// block count is inferred
};


static const uint32_t ASTC_MAGIC_ID = 0x5CA1AB13;

static unsigned int unpack_bytes(
	uint8_t a,
	uint8_t b,
	uint8_t c,
	uint8_t d
) {
	return ((unsigned int)(a))       +
	       ((unsigned int)(b) << 8)  +
	       ((unsigned int)(c) << 16) +
	       ((unsigned int)(d) << 24);
}

int load_cimage(
	const char* filename,
	astc_compressed_image& out_image
) {
	std::ifstream file(filename, std::ios::in | std::ios::binary);
	if (!file)
	{
		printf("ERROR: File open failed '%s'\n", filename);
		return 1;
	}

	astc_header hdr;
	file.read((char*)&hdr, sizeof(astc_header));
	if (!file)
	{
		printf("ERROR: File read failed '%s'\n", filename);
		return 1;
	}

	unsigned int magicval = unpack_bytes(hdr.magic[0], hdr.magic[1], hdr.magic[2], hdr.magic[3]);
	if (magicval != ASTC_MAGIC_ID)
	{
		printf("ERROR: File not recognized '%s'\n", filename);
		return 1;
	}

	// Ensure these are not zero to avoid div by zero
	unsigned int block_x = MAX(hdr.block_x, 1);
	unsigned int block_y = MAX(hdr.block_y, 1);
	unsigned int block_z = MAX(hdr.block_z, 1);

	unsigned int dim_x = unpack_bytes(hdr.dim_x[0], hdr.dim_x[1], hdr.dim_x[2], 0);
	unsigned int dim_y = unpack_bytes(hdr.dim_y[0], hdr.dim_y[1], hdr.dim_y[2], 0);
	unsigned int dim_z = unpack_bytes(hdr.dim_z[0], hdr.dim_z[1], hdr.dim_z[2], 0);

	if (dim_x == 0 || dim_z == 0 || dim_z == 0)
	{
		printf("ERROR: File corrupt '%s'\n", filename);
		return 1;
	}

	unsigned int xblocks = (dim_x + block_x - 1) / block_x;
	unsigned int yblocks = (dim_y + block_y - 1) / block_y;
	unsigned int zblocks = (dim_z + block_z - 1) / block_z;

	size_t data_size = xblocks * yblocks * zblocks * 16;
	uint8_t *buffer = new uint8_t[data_size];

	file.read((char*)buffer, data_size);
	if (!file)
	{
		printf("ERROR: File read failed '%s'\n", filename);
		return 1;
	}

	out_image.data = buffer;
	out_image.data_len = data_size;
	out_image.block_x = block_x;
	out_image.block_y = block_y;
	out_image.block_z = block_z;
	out_image.dim_x = dim_x;
	out_image.dim_y = dim_y;
	out_image.dim_z = dim_z;
	return 0;
}


int store_cimage(
	const astc_compressed_image& comp_img,
	const char* filename
) {
	astc_header hdr;
	hdr.magic[0] =  ASTC_MAGIC_ID        & 0xFF;
	hdr.magic[1] = (ASTC_MAGIC_ID >>  8) & 0xFF;
	hdr.magic[2] = (ASTC_MAGIC_ID >> 16) & 0xFF;
	hdr.magic[3] = (ASTC_MAGIC_ID >> 24) & 0xFF;

	hdr.block_x = comp_img.block_x;
	hdr.block_y = comp_img.block_y;
	hdr.block_z = comp_img.block_z;

	hdr.dim_x[0] =  comp_img.dim_x        & 0xFF;
	hdr.dim_x[1] = (comp_img.dim_x >>  8) & 0xFF;
	hdr.dim_x[2] = (comp_img.dim_x >> 16) & 0xFF;

	hdr.dim_y[0] =  comp_img.dim_y       & 0xFF;
	hdr.dim_y[1] = (comp_img.dim_y >>  8) & 0xFF;
	hdr.dim_y[2] = (comp_img.dim_y >> 16) & 0xFF;

	hdr.dim_z[0] =  comp_img.dim_z        & 0xFF;
	hdr.dim_z[1] = (comp_img.dim_z >>  8) & 0xFF;
	hdr.dim_z[2] = (comp_img.dim_z >> 16) & 0xFF;

 	std::ofstream file(filename, std::ios::out | std::ios::binary);
	if (!file)
	{
		printf("ERROR: File open failed '%s'\n", filename);
		return 1;
	}

	file.write((char*)&hdr, sizeof(astc_header));
	file.write((char*)comp_img.data, comp_img.data_len);
	return 0;
}