summaryrefslogtreecommitdiffstatshomepage
path: root/src/emu/save.cpp
blob: 2245bfd1fb40d931596d56a9e69b27eb7d548c20 (plain) (blame)
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
// license:BSD-3-Clause
// copyright-holders:Aaron Giles
/***************************************************************************

    save.cpp

    Save state management functions.

****************************************************************************

    Save state file format:

    00..07  'MAMESAVE'
    08      Format version (this is format 2)
    09      Flags
    0A..1B  Game name padded with \0
    1C..1F  Signature
    20..end Save game data (compressed)

    Data is always written as native-endian.
    Data is converted from the endiannness it was written upon load.

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

#include "emu.h"
#include "emuopts.h"
#include "coreutil.h"
#include "unzip.h"

#include <iomanip>
#include <zlib.h>


//**************************************************************************
//  DEBUGGING
//**************************************************************************

#define VERBOSE 0

#define LOG(x) do { if (VERBOSE) machine().logerror x; } while (0)



//**************************************************************************
//  ZLIB WRITE STREAMER
//**************************************************************************

// this class wraps the logic needed to stream compressed (deflated) data to
// a file in a .ZIP-compatible format
class zlib_write_streamer
{
public:
	// construction
	zlib_write_streamer(emu_file &output);

	// simple getters
	util::crc32_t crc() const { return m_crc_accum.finish(); }
	u32 uncompressed_bytes() const { return m_uncompressed_bytes; }
	u32 compressed_bytes() const { return m_compressed_bytes; }

	// initialize compression
	bool begin();

	// add more compressed data
	bool write(void const *data, u32 count);

	// finish compression
	bool end();

private:
	// internal state
	emu_file &m_output;                    // the file to spill data to
	z_stream m_stream;                     // the current zlib stream
	util::crc32_creator m_crc_accum;       // accumulated CRC value
	u32 m_uncompressed_bytes;              // accumulated uncompressed bytes
	u32 m_compressed_bytes;                // accumulated compressed bytes
	u8 m_buffer[4096];                     // temporary buffer to accumulate
};


//-------------------------------------------------
//  zlib_write_streamer - constuctor
//-------------------------------------------------

zlib_write_streamer::zlib_write_streamer(emu_file &output) :
	m_output(output)
{
	m_stream.zalloc = Z_NULL;
	m_stream.zfree = Z_NULL;
	m_stream.opaque = Z_NULL;
	m_stream.avail_in = m_stream.avail_out = 0;
}


//-------------------------------------------------
//  begin - initialize compression
//-------------------------------------------------

bool zlib_write_streamer::begin()
{
	// reset the output buffer
	m_stream.next_out = &m_buffer[0];
	m_stream.avail_out = sizeof(m_buffer);

	// reset our accumulators
	m_crc_accum.reset();
	m_uncompressed_bytes = 0;
	m_compressed_bytes = 0;

	// initialize the zlib engine; the negative window size means
	// no headers, which is what a .ZIP file wants
	return (deflateInit2(&m_stream, Z_BEST_COMPRESSION, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) == Z_OK);
}


//-------------------------------------------------
//  write - add more compressed data
//-------------------------------------------------

bool zlib_write_streamer::write(void const *data, u32 count)
{
	// point the input buffer to the data
	m_stream.next_in = const_cast<Bytef *>(reinterpret_cast<Bytef const *>(data));
	m_stream.avail_in = count;

	// loop until all consumed
	while (m_stream.avail_in != 0)
	{
		// deflate as much as possible
		if (deflate(&m_stream, Z_NO_FLUSH) != Z_OK)
		{
			deflateEnd(&m_stream);
			return false;
		}

		// if we ran out of output space, flush to the file and reset
		if (m_stream.avail_out == 0)
		{
			if (m_output.write(&m_buffer[0], sizeof(m_buffer)) != sizeof(m_buffer))
			{
				deflateEnd(&m_stream);
				return false;
			}
			m_compressed_bytes += sizeof(m_buffer);
			m_stream.next_out = &m_buffer[0];
			m_stream.avail_out = sizeof(m_buffer);
		}
	}

	// update accumulators
	m_uncompressed_bytes += count;
	m_crc_accum.append(data, count);
	return true;
}


//-------------------------------------------------
//  end - finish cmopression
//-------------------------------------------------

bool zlib_write_streamer::end()
{
	// loop until all data processed
	int zerr = Z_OK;
	while (zerr != Z_STREAM_END)
	{
		// deflate and attempt to finish
		zerr = deflate(&m_stream, Z_FINISH);
		if (zerr != Z_OK && zerr != Z_STREAM_END)
		{
			deflateEnd(&m_stream);
			return false;
		}

		// if there's any output data, flush it to the file and reset
		if (m_stream.avail_out != sizeof(m_buffer))
		{
			u32 bytes = sizeof(m_buffer) - m_stream.avail_out;
			if (m_output.write(&m_buffer[0], bytes) != bytes)
			{
				deflateEnd(&m_stream);
				return false;
			}
			m_compressed_bytes += bytes;
			m_stream.next_out = &m_buffer[0];
			m_stream.avail_out = sizeof(m_buffer);
		}
	}

	// finalize the CRC
	m_crc_accum.finish();
	return (deflateEnd(&m_stream) == Z_OK);
}



//**************************************************************************
//  SAVE ZIP STATE
//**************************************************************************

// this class manages the creation of a ZIP file containing a JSON with most of
// the save data, plus various binary files containing larger chunks of data
class save_zip_state
{
	// internal constants
	static constexpr u32 JSON_EXPAND_CHUNK = 1024 * 1024;
	static constexpr u32 JSON_EXPAND_THRESH = 1024;

public:
	// the size threshold in bytes above which we will write an external file
	static constexpr u32 JSON_EXTERNAL_BINARY_THRESHOLD = 16 * 1024;

	// construction
	save_zip_state();

	// simple getters
	char const *json_string() { m_json[m_json_offset] = 0; return &m_json[0]; }
	int json_length() const { return m_json_offset; }

	// append a character to the JSON stream
	save_zip_state &json_append(char ch) { 	m_json[m_json_offset++] = ch; return *this; }

	// append an end-of-line sequence to the JSON stream
	save_zip_state &json_append_eol() { return json_append(13).json_append(10); }

	// additional JSON output helpers
	save_zip_state &json_append(char const *buffer);
	save_zip_state &json_append_indent(int count);
	save_zip_state &json_append_name(char const *name);
	save_zip_state &json_append_signed(int64_t value);
	save_zip_state &json_append_unsigned(uint64_t value);
	save_zip_state &json_append_float(double value);

	// stage an item to be output as raw data
	char const *add_data_file(char const *proposed_name, save_registered_item &item, uintptr_t base);

	// commit the results to the given file
	bool commit(emu_file &output);

private:
	// check the reserve; if we're getting close, expand out one more chunk
	void json_check_reserve()
	{
		if (m_json_reserved - m_json_offset < JSON_EXPAND_THRESH)
		{
			m_json_reserved += JSON_EXPAND_CHUNK;
			m_json.resize(m_json_reserved);
		}
	}

	// other internal helpers
	void create_end_of_central_directory(std::vector<u8> &header, u32 central_dir_entries, u64 central_dir_offset, u32 central_dir_size);
	void create_zip_file_header(std::vector<u8> &local, std::vector<u8> &central, char const *filename, u64 local_offset);
	void create_zip_file_footer(std::vector<u8> &local, std::vector<u8> &central, u32 filesize, u32 compressed, u32 crc);
	bool write_data_recursive(zlib_write_streamer &zlib, save_registered_item &item, uintptr_t base);

	// file_entry represents a single raw data file that will be written
	struct file_entry
	{
		file_entry(char const *name, save_registered_item &item, uintptr_t base) :
			m_item(item), m_name(name), m_base(base) { }

		save_registered_item &m_item;
		std::string m_name;
		uintptr_t m_base;
		std::vector<u8> m_central_directory;
	};

	// internal state
	std::list<file_entry> m_file_list;     // list of files to be output
	std::vector<char> m_json;              // accumulated JSON data
	u32 m_json_offset;                     // current output offset in JSON stream
	u32 m_json_reserved;                   // current total reserved size for JSON stream
	u16 m_archive_date;                    // precomputed archive date, in MS-DOS format
	u16 m_archive_time;                    // precomputed archive time, in MS-DOS format
};


//-------------------------------------------------
//  save_zip_state - constuctor
//-------------------------------------------------

save_zip_state::save_zip_state() :
	m_json_offset(0),
	m_json_reserved(0)
{
	json_check_reserve();
}


//-------------------------------------------------
//  json_append - append a string to the JSON
//  stream
//-------------------------------------------------

save_zip_state &save_zip_state::json_append(char const *buffer)
{
	json_check_reserve();
	while (*buffer != 0)
		json_append(*buffer++);
	return *this;
}


//-------------------------------------------------
//  json_append_indent - append an indentation of
//  the given depth to the JSON stream
//-------------------------------------------------

save_zip_state &save_zip_state::json_append_indent(int count)
{
	for (int index = 0; index < count; index++)
		json_append('\t');
	return *this;
}


//-------------------------------------------------
//  json_append_name - append a string-ified name
//  to the JSON stream
//-------------------------------------------------

save_zip_state &save_zip_state::json_append_name(char const *name)
{
	if (name == nullptr || name[0] == 0)
		return *this;
	return json_append('"').json_append(name).json_append('"').json_append(':');
}


//-------------------------------------------------
//  json_append_signed - append a signed integer
//  value to the JSON stream
//-------------------------------------------------

save_zip_state &save_zip_state::json_append_signed(int64_t value)
{
	json_check_reserve();

	// quote values that don't fit into a double
	bool quote = (int64_t(double(value)) != value);
	if (quote)
		json_append('"');

	// just use sprintf -- is there a faster way?
	char buffer[20];
	sprintf(buffer, "%lld", value);
	json_append(buffer);

	// end quotes
	if (quote)
		json_append('"');
	return *this;
}


//-------------------------------------------------
//  json_append_unsigned - append an unsigned
//  integer value to the JSON stream
//-------------------------------------------------

save_zip_state &save_zip_state::json_append_unsigned(uint64_t value)
{
	json_check_reserve();

	// quote values that don't fit into a double
	bool quote = (uint64_t(double(value)) != value);
	if (quote)
		json_append('"');

	// just use sprintf -- is there a faster way?
	char buffer[20];
	sprintf(buffer, "%llu", value);
	json_append(buffer);

	// end quotes
	if (quote)
		json_append('"');
	return *this;
}


//-------------------------------------------------
//  json_append_float - append a floating-point
//  value to the JSON stream
//-------------------------------------------------

save_zip_state &save_zip_state::json_append_float(double value)
{
	json_check_reserve();
	char buffer[20];
	sprintf(buffer, "%g", value);
	return json_append(buffer);
}


//-------------------------------------------------
//  add_data_file - add a data file to the ZIP
//  file, creating a clean, unique filename for it
//-------------------------------------------------

char const *save_zip_state::add_data_file(char const *proposed_name, save_registered_item &item, uintptr_t base)
{
	// first sanitize the filename
	std::string base_filename = proposed_name;
	for (int index = 0; index < base_filename.length(); )
	{
		if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.", base_filename[index]) == nullptr)
		{
			if (index != 0 && base_filename[index - 1] != '.')
				base_filename[index++] = '.';
			else
				base_filename.erase(index, 1);
		}
		else
			index++;
	}

	// now ensure it is unique
	std::string filename;
	bool retry = true;
	for (int index = 1; retry; index++)
	{
		if (index == 1)
			filename = string_format("%s.bin", base_filename.c_str());
		else
			filename = string_format("%s.%d.bin", base_filename.c_str(), index);

		// see if anyone else has this name; if so, retry it
		retry = false;
		for (auto &file : m_file_list)
			if (filename == file.m_name)
			{
				retry = true;
				break;
			}
	}

	// add to the list
	m_file_list.emplace_back(filename.c_str(), item, base);
	return m_file_list.back().m_name.c_str();
}


//-------------------------------------------------
//  commit - assemble all the files into their
//  final forms and write the ZIP data to the
//  output file
//-------------------------------------------------

bool save_zip_state::commit(emu_file &output)
{
	zlib_write_streamer zlib(output);
	std::vector<u8> local_header;
	std::vector<u8> local_footer;

	// determine the MS-DOS formatted time
	time_t rawtime;
	::time(&rawtime);
	struct tm &timeinfo = *localtime(&rawtime);
	m_archive_date = timeinfo.tm_mday | ((timeinfo.tm_mon + 1) << 5) | ((timeinfo.tm_year - 1980) << 9);
	m_archive_time = (timeinfo.tm_sec / 2) | (timeinfo.tm_min << 5) | (timeinfo.tm_hour << 11);

	// write the local header (and create the central directory entry) for the JSON itself
	std::vector<u8> json_central_directory;
	u64 local_header_offset = output.tell();
	create_zip_file_header(local_header, json_central_directory, "save.json", local_header_offset);
	output.write(&local_header[0], local_header.size());

	// stream the JSON and compress it
	if (!zlib.begin() || !zlib.write(&m_json[0], m_json_offset) || !zlib.end())
		return false;

	// write the local footer and update the central directory entry
	create_zip_file_footer(local_footer, json_central_directory, zlib.uncompressed_bytes(), zlib.compressed_bytes(), zlib.crc());
	output.seek(local_header_offset + 0xe, SEEK_SET);
	output.write(&local_footer[0], local_footer.size());
	output.seek(0, SEEK_END);

	// then write out the other files
	for (auto &file : m_file_list)
	{
		// write the local header (and create the central directory entry) for the file
		u64 local_header_offset = output.tell();
		create_zip_file_header(local_header, file.m_central_directory, file.m_name.c_str(), local_header_offset);
		output.write(&local_header[0], local_header.size());

		// write the file header and compress it
		if (!zlib.begin() || !write_data_recursive(zlib, file.m_item, file.m_base) || !zlib.end())
			return false;

		// write the local footer and update the central directory entry
		create_zip_file_footer(local_footer, file.m_central_directory, zlib.uncompressed_bytes(), zlib.compressed_bytes(), zlib.crc());
		output.seek(local_header_offset + 0xe, SEEK_SET);
		output.write(&local_footer[0], local_footer.size());
		output.seek(0, SEEK_END);
	}

	// remember the base of the central directory, then write it
	u64 central_dir_offset = output.tell();
	output.write(&json_central_directory[0], json_central_directory.size());
	for (auto &file : m_file_list)
		output.write(&file.m_central_directory[0], file.m_central_directory.size());

	// now create the
	std::vector<u8> eocd;
	create_end_of_central_directory(eocd, m_file_list.size() + 1, central_dir_offset, output.tell() - central_dir_offset);
	output.write(&eocd[0], eocd.size());
	return true;
}


//-------------------------------------------------
//  create_zip_file_header - create both the local
//  and central file headers; the CRC and size
//  information is stored as 0 at this stage
//-------------------------------------------------

void save_zip_state::create_zip_file_header(std::vector<u8> &local, std::vector<u8> &central, char const *filename, u64 local_offset)
{
	// reset the headers
	local.clear();
	central.clear();

	// write the standard headers
	local.push_back(0x50);	central.push_back(0x50);
	local.push_back(0x4b);	central.push_back(0x4b);
	local.push_back(0x03);	central.push_back(0x01);
	local.push_back(0x04);	central.push_back(0x02);

	// version created by = 3.0 / 0 (MS-DOS) (central directory only)
							central.push_back(0x1e);
							central.push_back(0x00);

	// version to extract = 2.0
	local.push_back(0x14);	central.push_back(0x14);
	local.push_back(0x00);	central.push_back(0x00);

	// general purpose bit flag = 0x02 (2=max compression)
	local.push_back(0x02);	central.push_back(0x02);
	local.push_back(0x00);	central.push_back(0x00);

	// compression method = 8 (deflate)
	local.push_back(0x08);	central.push_back(0x08);
	local.push_back(0x00);	central.push_back(0x00);

	// last mod file time
	local.push_back(BIT(m_archive_time, 0, 8));	central.push_back(BIT(m_archive_time, 0, 8));
	local.push_back(BIT(m_archive_time, 8, 8));	central.push_back(BIT(m_archive_time, 8, 8));

	// last mod file date
	local.push_back(BIT(m_archive_date, 0, 8));	central.push_back(BIT(m_archive_date, 0, 8));
	local.push_back(BIT(m_archive_date, 8, 8));	central.push_back(BIT(m_archive_date, 8, 8));

	// crc-32 -- to be written later
	local.push_back(0x00);	central.push_back(0x00);
	local.push_back(0x00);	central.push_back(0x00);
	local.push_back(0x00);	central.push_back(0x00);
	local.push_back(0x00);	central.push_back(0x00);

	// compressed size -- to be written later
	local.push_back(0x00);	central.push_back(0x00);
	local.push_back(0x00);	central.push_back(0x00);
	local.push_back(0x00);	central.push_back(0x00);
	local.push_back(0x00);	central.push_back(0x00);

	// uncompressed size -- to be written later
	local.push_back(0x00);	central.push_back(0x00);
	local.push_back(0x00);	central.push_back(0x00);
	local.push_back(0x00);	central.push_back(0x00);
	local.push_back(0x00);	central.push_back(0x00);

	// file name length
	u16 len = strlen(filename);
	local.push_back(BIT(len, 0, 8)); central.push_back(BIT(len, 0, 8));
	local.push_back(BIT(len, 8, 8)); central.push_back(BIT(len, 8, 8));

	// extra field length
	local.push_back(0x00);	central.push_back(0x00);
	local.push_back(0x00);	central.push_back(0x00);

	// file comment length (central directory only)
							central.push_back(0x00);
							central.push_back(0x00);

	// disk number start (central directory only)
							central.push_back(0x00);
							central.push_back(0x00);

	// internal file attributes (central directory only)
							central.push_back(0x00);
							central.push_back(0x00);

	// external file attributes (central directory only)
							central.push_back(0x00);
							central.push_back(0x00);
							central.push_back(0x00);
							central.push_back(0x00);

	// relative offset of local header (central directory only)
							central.push_back(BIT(local_offset, 0, 8));
							central.push_back(BIT(local_offset, 8, 8));
							central.push_back(BIT(local_offset, 16, 8));
							central.push_back(BIT(local_offset, 24, 8));

	// filename
	for ( ; *filename != 0; filename++)
	{
		local.push_back(*filename);
		central.push_back(*filename);
	}
}


//-------------------------------------------------
//  create_zip_file_footer - create the CRC and
//  size information, and update the central
//  directory entry with the data
//-------------------------------------------------

void save_zip_state::create_zip_file_footer(std::vector<u8> &local, std::vector<u8> &central, u32 filesize, u32 compressed, u32 crc)
{
	// reset the local footer data
	local.clear();

	// crc-32 -- to be written later
	local.push_back(central[16] = BIT(crc, 0, 8));
	local.push_back(central[17] = BIT(crc, 8, 8));
	local.push_back(central[18] = BIT(crc, 16, 8));
	local.push_back(central[19] = BIT(crc, 24, 8));

	// compressed size -- to be written later
	local.push_back(central[20] = BIT(compressed, 0, 8));
	local.push_back(central[21] = BIT(compressed, 8, 8));
	local.push_back(central[22] = BIT(compressed, 16, 8));
	local.push_back(central[23] = BIT(compressed, 24, 8));

	// uncompressed size -- to be written later
	local.push_back(central[24] = BIT(filesize, 0, 8));
	local.push_back(central[25] = BIT(filesize, 8, 8));
	local.push_back(central[26] = BIT(filesize, 16, 8));
	local.push_back(central[27] = BIT(filesize, 24, 8));
}


//-------------------------------------------------
//  write_data_recursive - write potentially
//  multi-dimensional arrays to the compressed
//  output, computing size and CRC
//-------------------------------------------------

bool save_zip_state::write_data_recursive(zlib_write_streamer &zlib, save_registered_item &item, uintptr_t base)
{
	save_registered_item &inner = item.subitems().front();
	if (inner.is_array())
	{
		for (int index = 0; index < item.count(); index++)
		{
			if (!write_data_recursive(zlib, inner, base))
				return false;
			base += item.native_size();
		}
	}
	else
	{
		u32 size = item.count() * item.native_size();
		if (!zlib.write(reinterpret_cast<void *>(base), size))
			return false;
	}
	return true;
}


//-------------------------------------------------
//  create_end_of_central_directory - create a
//  buffer containing the end of central directory
//  record
//-------------------------------------------------

void save_zip_state::create_end_of_central_directory(std::vector<u8> &header, u32 central_dir_entries, u64 central_dir_offset, u32 central_dir_size)
{
	// end of central directory header
	header.push_back(0x50);
	header.push_back(0x4b);
	header.push_back(0x05);
	header.push_back(0x06);

	// number of this disk
	header.push_back(0x00);
	header.push_back(0x00);

	// number of disk with start of central directory
	header.push_back(0x00);
	header.push_back(0x00);

	// total central directory entries on this disk
	header.push_back(BIT(central_dir_entries, 0, 8));
	header.push_back(BIT(central_dir_entries, 8, 8));

	// total central directory entries
	header.push_back(BIT(central_dir_entries, 0, 8));
	header.push_back(BIT(central_dir_entries, 8, 8));

	// size of the central directory
	header.push_back(BIT(central_dir_size, 0, 8));
	header.push_back(BIT(central_dir_size, 8, 8));
	header.push_back(BIT(central_dir_size, 16, 8));
	header.push_back(BIT(central_dir_size, 24, 8));

	// offset of central directory
	header.push_back(BIT(central_dir_offset, 0, 8));
	header.push_back(BIT(central_dir_offset, 8, 8));
	header.push_back(BIT(central_dir_offset, 16, 8));
	header.push_back(BIT(central_dir_offset, 24, 8));

	// ZIP comment length
	header.push_back(0x00);
	header.push_back(0x00);
}



//**************************************************************************
//  ZLIB READ STREAMER
//**************************************************************************

class zlib_read_streamer
{
public:
	// construction
	zlib_read_streamer(emu_file &input);

	// simple getters
	util::crc32_t crc() const { return m_crc_accum.finish(); }
	util::crc32_t expected_crc() const { return m_expected_crc; }
	u32 uncompressed_bytes() const { return m_uncompressed_bytes; }
	u32 compressed_bytes() const { return m_compressed_bytes; }

	// initialize decompression
	bool begin(u64 offset);

	// read more compressed data
	bool read(void *data, u32 count);

	// finish decompression
	bool end();

private:
	// internal state
	emu_file &m_input;                     // the file to read from
	z_stream m_stream;                     // the current zlib stream
	util::crc32_creator m_crc_accum;       // accumulated CRC value
	u32 m_uncompressed_bytes;              // accumulated uncompressed bytes
	u32 m_compressed_bytes;                // accumulated compressed bytes
	u32 m_input_remaining;                 // number of input bytes remaining
	u32 m_expected_crc;                    // expected CRC value
	u8 m_buffer[4096];                     // temporary buffer to accumulate
};


//-------------------------------------------------
//  zlib_read_streamer - constuctor
//-------------------------------------------------

zlib_read_streamer::zlib_read_streamer(emu_file &input) :
	m_input(input)
{
	m_stream.zalloc = Z_NULL;
	m_stream.zfree = Z_NULL;
	m_stream.opaque = Z_NULL;
	m_stream.avail_in = m_stream.avail_out = 0;
}


//-------------------------------------------------
//  begin - initialize decompression
//-------------------------------------------------

bool zlib_read_streamer::begin(u64 offset)
{
	// read the local file header
	u8 local[30];
	m_input.seek(offset, SEEK_SET);
	if (m_input.read(&local[0], sizeof(local)) != sizeof(local))
		return false;

	// validate header
	if (local[0] != 0x50 || local[1] != 0x4b || local[2] != 0x03 || local[3] != 0x04)
		return false;

	// only deflate is supported
	if (local[8] != 0x08)
		return false;

	// parse data from the header
	m_expected_crc = local[14] | (local[15] << 8) | (local[16] << 16) | (local[17] << 24);
	m_compressed_bytes = local[18] | (local[19] << 8) | (local[20] << 16) | (local[21] << 24);
	m_uncompressed_bytes = local[22] | (local[23] << 8) | (local[24] << 16) | (local[25] << 24);
	u32 name_len = local[26] | (local[27] << 8);
	u32 extra_len = local[28] | (local[29] << 8);

	// advance past the header to the actual start of data
	offset += 30 + name_len + extra_len;
	m_input.seek(offset, SEEK_SET);

	// reset the input buffer
	m_stream.avail_in = 0;

	// reset our accumulators
	m_crc_accum.reset();
	m_input_remaining = m_compressed_bytes;

	// initialize the zlib engine; the negative window size means
	// no headers, which is what a .ZIP file wants
	return (inflateInit2(&m_stream, -MAX_WBITS) == Z_OK);
}


//-------------------------------------------------
//  read - read more compressed data
//-------------------------------------------------

bool zlib_read_streamer::read(void *data, u32 count)
{
	// point the output buffer to the target buffer
	m_stream.next_out = reinterpret_cast<Bytef *>(data);
	m_stream.avail_out = count;

	// loop until all consumed
	while (m_stream.avail_out != 0)
	{
		// if we need more data, fetch it
		if (m_stream.avail_in == 0)
		{
			m_stream.next_in = &m_buffer[0];
			m_stream.avail_in = std::min<u32>(sizeof(m_buffer), m_input_remaining);
			m_input_remaining -= m_stream.avail_in;
			if (m_input.read(&m_buffer[0], m_stream.avail_in) != m_stream.avail_in)
			{
				inflateEnd(&m_stream);
				return false;
			}
		}

		// deflate as much as possible
		auto zerr = inflate(&m_stream, Z_NO_FLUSH);
		if (zerr != Z_OK && (zerr != Z_STREAM_END || m_stream.avail_out != 0))
		{
			inflateEnd(&m_stream);
			return false;
		}
	}

	// update accumulators
	m_crc_accum.append(data, count);
	return true;
}


//-------------------------------------------------
//  end - finish cmopression
//-------------------------------------------------

bool zlib_read_streamer::end()
{
	// fail if CRCs didn't match
	return (inflateEnd(&m_stream) == Z_OK && crc() == expected_crc());
}



//**************************************************************************
//  LOAD ZIP STATE
//**************************************************************************

// this class manages loading from a ZIP file containing a JSON with most of
// the save data, plus various binary files containing larger chunks of data
class load_zip_state
{
public:
	// load_error is the exception we throw if anything bad happens
	class load_error : public std::exception { };

	// construction
	load_zip_state(emu_file &file);

	// simple getters
	emu_file &file() const { return m_file; }
	char const *warnings() const { return (m_warnings.length() == 0) ? nullptr : m_warnings.c_str(); }
	char const *errors() const { return (m_errors.length() == 0) ? nullptr : m_errors.c_str(); }
	char const *json_position() const { return m_json_ptr; }

	// simple setters
	void json_set_position(char const *pos) { m_json_ptr = pos; }

	// return the next character in the buffer
	char json_peek() const { return *m_json_ptr; }

	// advance to the next non-whitespace character
	void json_skip_whitespace() { while (isspace(*m_json_ptr)) m_json_ptr++; }

	// various JSON parsing helpers
	bool json_matches(char target);
	bool json_matches(char const *target);
	bool json_parse_number(double &result);
	bool json_parse_int_string(int64_t &result);
	bool json_parse_uint_string(uint64_t &result);
	bool json_parse_string(std::string &result);

	// initialize, checking the input file basic validity
	save_error init();

	// find a file in the ZIP, returning its uncompressed size and offset to local header
	bool find_file(char const *name, u64 &offset, u32 &size);

	// recursively read data using
	bool read_data_recursive(zlib_read_streamer &zlib, save_registered_item &item, bool flip, u32 &remaining, uintptr_t base);

	// report a warning
	template<typename... Params>
	void report_warning(char const *format, Params &&... args)
	{
		m_warnings.append(string_format(format, std::forward<Params>(args)...));
		m_warnings += "\n";
	}

	// report an error; this implicitly throws to exit
	template<typename... Params>
	void report_error(char const *format, Params &&... args)
	{
		m_errors.append(string_format(format, std::forward<Params>(args)...));
		m_errors += "\n";
		throw load_error();
	}

private:
	// file_entry represents a single file within the ZIP
	struct file_entry
	{
		file_entry(char const *name, u64 offset, u32 compsize, u32 uncompsize) :
			m_name(name), m_offset(offset), m_compsize(compsize), m_uncompsize(uncompsize) { }

		std::string m_name;
		u64 m_offset;
		u32 m_compsize;
		u32 m_uncompsize;
	};

	// internal state
	emu_file &m_file;                      // input file
	std::vector<u8> m_json_data;           // buffered JSON file
	char const *m_json_ptr;                // current input pointer to data
	std::list<file_entry> m_file_list;     // list of files to be output
	std::string m_warnings;                // accumulated warnings string
	std::string m_errors;                  // accumulated errors string
};


//-------------------------------------------------
//  load_zip_state - constructor
//-------------------------------------------------

load_zip_state::load_zip_state(emu_file &file) :
	m_file(file),
	m_json_ptr(nullptr)
{
}


//-------------------------------------------------
//  json_matches - return true and advance if the
//  next character matches the target
//-------------------------------------------------

bool load_zip_state::json_matches(char target)
{
	json_skip_whitespace();
	if (*m_json_ptr == target)
	{
		m_json_ptr++;
		return true;
	}
	return false;
}


//-------------------------------------------------
//  json_matches - return true and advance if the
//  next characters match the target string
//-------------------------------------------------

bool load_zip_state::json_matches(char const *target)
{
	json_skip_whitespace();
	char const *start = m_json_ptr;
	for ( ; *target != 0; target++)
		if (!json_matches(*target))
			break;
	if (*target == 0)
		return true;
	m_json_ptr = start;
	return false;
}


//-------------------------------------------------
//  json_parse_number - parse a floating-point
//  number from the JSON
//-------------------------------------------------

bool load_zip_state::json_parse_number(double &result)
{
	json_skip_whitespace();
	char const *start = m_json_ptr;
	result = strtod(start, const_cast<char **>(&m_json_ptr));
	return (start != m_json_ptr);
}


//-------------------------------------------------
//  json_parse_int_string - parse a 64-bit signed
//  integer from a string
//-------------------------------------------------

bool load_zip_state::json_parse_int_string(int64_t &result)
{
	if (!json_matches('"'))
		return false;
	char const *start = m_json_ptr;
	result = strtoll(start, const_cast<char **>(&m_json_ptr), 10);
	return (start != m_json_ptr && json_matches('"'));
}


//-------------------------------------------------
//  json_parse_int_string - parse a 64-bit unsigned
//  integer from a string
//-------------------------------------------------

bool load_zip_state::json_parse_uint_string(uint64_t &result)
{
	if (!json_matches('"'))
		return false;
	char const *start = m_json_ptr;
	result = strtoull(start, const_cast<char **>(&m_json_ptr), 10);
	return (start != m_json_ptr && json_matches('"'));
}


//-------------------------------------------------
//  json_parse_int_string - parse a 64-bit unsigned
//  integer from a string
//-------------------------------------------------

bool load_zip_state::json_parse_string(std::string &result)
{
	if (!json_matches('"'))
		return false;
	char const *start = m_json_ptr;
	char ch;
	bool found_controls = false;
	while ((ch = *m_json_ptr) != 0)
	{
		m_json_ptr++;
		if (ch == '\\')
		{
			m_json_ptr++;
			found_controls = true;
		}
		else if (ch == '"')
			break;
	}
	result = std::string(start, m_json_ptr - 1 - start);

	// if we saw any control characters, go back and fix them up
	if (found_controls)
		for (int index = 0; index < result.length(); index++)
			if (result[index] == '\\')
			{
				char ch = result[index + 1];
				result.erase(index + 1, 1);
				switch (ch)
				{
					case '/':	result[index] = ch;	break;
					case '\\':	result[index] = ch;	break;
					case '"':	result[index] = ch;	break;
					case 'b':	result[index] = 8;	break;
					case 'f':	result[index] = 12;	break;
					case 'n':	result[index] = 10;	break;
					case 'r':	result[index] = 13;	break;
					case 't':	result[index] = 9;	break;
					case 'u':	result[index] = '?'; result.erase(index + 1, 4); break;
				}
			}
	return true;
}


//-------------------------------------------------
//  init - initialize by parsing the ZIP structure
//  and loading the JSON data
//-------------------------------------------------

save_error load_zip_state::init()
{
	// read the last 1k of the file to find the end of central directory record
	u8 buffer[1024];
	u64 filesize = m_file.size();
	int bufread = std::min(filesize, sizeof(buffer));
	m_file.seek(-bufread, SEEK_END);
	if (m_file.read(&buffer[0], bufread) != bufread)
		return STATERR_READ_ERROR;

	// scan backwards to find it
	u32 dir_offset = 0;
	u32 dir_size = 0;
	u32 dir_entries = 0;
	for (int scan = bufread - 20; scan >= 0; scan--)
		if (buffer[scan + 0] == 0x50 && buffer[scan + 1] == 0x4b && buffer[scan + 2] == 0x05 && buffer[scan + 3] == 0x06)
		{
			u8 *eocd = &buffer[scan];
			dir_entries = eocd[10] | (eocd[11] << 8);
			dir_size = eocd[12] | (eocd[13] << 8) | (eocd[14] << 16) | (eocd[15] << 24);
			dir_offset = eocd[16] | (eocd[17] << 8) | (eocd[18] << 16) | (eocd[19] << 24);
			break;
		}

	// if nothing found, it's an error
	if (dir_entries == 0)
		return STATERR_INVALID_HEADER;

	// read the central directory
	std::vector<u8> central(dir_size);
	m_file.seek(dir_offset, SEEK_SET);
	if (m_file.read(&central[0], dir_size) != dir_size)
		return STATERR_READ_ERROR;

	// parse through the entries
	u32 offset = 0;
	for ( ; dir_entries != 0 && offset < central.size() - 46; dir_entries--)
	{
		// find the start of entry
		if (offset + 46 >= dir_size)
			return STATERR_INVALID_HEADER;
		if (central[offset] != 0x50 && central[offset + 1] != 0x4b && central[offset + 2] != 0x01 && central[offset + 3] != 0x02)
			return STATERR_INVALID_HEADER;

		// only deflate is supported; anything else will be an error
		if (central[offset + 10] != 8)
			return STATERR_INVALID_HEADER;

		// pull out all the interesting data
		u32 compsize = central[offset + 20] | (central[offset + 21] << 8) | (central[offset + 22] << 16) | (central[offset + 23] << 24);
		u32 uncompsize = central[offset + 24] | (central[offset + 25] << 8) | (central[offset + 26] << 16) | (central[offset + 27] << 24);
		u32 namelen = central[offset + 28] | (central[offset + 29] << 8);
		u32 extralen = central[offset + 30] | (central[offset + 31] << 8);
		u32 commentlen = central[offset + 32] | (central[offset + 33] << 8);
		u32 header_offs = central[offset + 42] | (central[offset + 43] << 8) | (central[offset + 44] << 16) | (central[offset + 45] << 24);
		std::string filename(reinterpret_cast<char *>(&central[offset + 46]), namelen);
		offset += 46 + namelen + extralen + commentlen;

		// add a file entry
		m_file_list.emplace_back(filename.c_str(), header_offs, compsize, uncompsize);
	}

	// now find the json file
	u64 json_offset;
	u32 json_size;
	if (!find_file("save.json", json_offset, json_size))
		return STATERR_READ_ERROR;
	m_json_data.resize(json_size + 1);

	// read the data
	zlib_read_streamer reader(m_file);
	if (!reader.begin(json_offset) || !reader.read(&m_json_data[0], json_size) || !reader.end())
		return STATERR_READ_ERROR;
	m_json_data[json_size] = 0;
	m_json_ptr = reinterpret_cast<char *>(&m_json_data[0]);

	return STATERR_NONE;
}


//-------------------------------------------------
//  find_file - find a file by name and return the
//  uncompressed size plus the file offset
//-------------------------------------------------

bool load_zip_state::find_file(char const *name, u64 &offset, u32 &uncompsize)
{
	// just scan the list for a filename match and return the data
	for (auto &file : m_file_list)
		if (file.m_name == name)
		{
			offset = file.m_offset;
			uncompsize = file.m_uncompsize;
			return true;
		}

	return false;
}


//-------------------------------------------------
//  read_data_recursive - write potentially
//  multi-dimensional arrays to the compressed
//  output, computing size and CRC
//-------------------------------------------------

bool load_zip_state::read_data_recursive(zlib_read_streamer &zlib, save_registered_item &item, bool flip, u32 &remaining, uintptr_t base)
{
	save_registered_item &inner = item.subitems().front();
	if (inner.is_array())
	{
		for (int index = 0; index < item.count(); index++)
		{
			if (!read_data_recursive(zlib, inner, flip, remaining, base))
				return false;
			base += item.native_size();
		}
	}
	else
	{
		u32 size = item.count() * item.native_size();
		size = std::min(size, remaining);
		if (!zlib.read(reinterpret_cast<void *>(base), size))
			return false;
		remaining -= size;
		if (flip)
			switch (item.native_size())
			{
			case 2:
			{
				u16 *data = reinterpret_cast<u16 *>(base);
				for (int index = 0; index < item.count(); index++)
					data[index] = swapendian_int16(data[index]);
				break;
			}
			case 4:
			{
				u32 *data = reinterpret_cast<u32 *>(base);
				for (int index = 0; index < item.count(); index++)
					data[index] = swapendian_int32(data[index]);
				break;
			}
			case 8:
			{
				u64 *data = reinterpret_cast<u64 *>(base);
				for (int index = 0; index < item.count(); index++)
					data[index] = swapendian_int64(data[index]);
				break;
			}
			}
	}
	return true;
}



//**************************************************************************
//  SAVE REGISTERED ITEM
//**************************************************************************

//-------------------------------------------------
//  save_registered_item - constructor
//-------------------------------------------------

save_registered_item::save_registered_item() :
	m_ptr_offset(0),
	m_type(TYPE_CONTAINER),
	m_native_size(0)
{
}

// constructor for a new item
save_registered_item::save_registered_item(uintptr_t ptr_offset, save_type type, uint32_t native_size, char const *name) :
	m_ptr_offset(ptr_offset),
	m_type(type),
	m_native_size(native_size),
	m_name(name)
{
	// cleanup names a bit
	if (m_name[0] == '*')
		m_name.erase(0, 1);
	if (m_name[0] == 'm' && m_name[1] == '_')
		m_name.erase(0, 2);
}


//-------------------------------------------------
//  append - append a new item to the current one
//-------------------------------------------------

std::string type_string(save_registered_item::save_type type, uint32_t native_size)
{
	switch (type)
	{
	case save_registered_item::TYPE_CONTAINER:	return "CONTAINER";
	case save_registered_item::TYPE_POINTER:	return "POINTER";
	case save_registered_item::TYPE_UNIQUE:		return "UNIQUE";
	case save_registered_item::TYPE_VECTOR:		return "VECTOR";
	case save_registered_item::TYPE_STRUCT:		return "STRUCT";
	case save_registered_item::TYPE_BOOL:		return "BOOL";
	case save_registered_item::TYPE_INT:		return string_format("INT%d", 8 * native_size);
	case save_registered_item::TYPE_UINT:		return string_format("UINT%d", 8 * native_size);
	case save_registered_item::TYPE_FLOAT:		return string_format("FLOAT%d", 8 * native_size);
	default:				return string_format("ARRAY[%d]", int(type));
	}
}

save_registered_item &save_registered_item::append(uintptr_t ptr_offset, save_type type, uint32_t native_size, char const *name)
{
	// make sure there are no duplicates
	if (find(name) != nullptr)
		throw emu_fatalerror("Duplicate save state registration '%s'\n", name);

//printf("%s '%s': adding %s '%s' @ %llX, size %d\n", type_string(m_type, m_native_size).c_str(), m_name.c_str(), type_string(type, native_size).c_str(), name, ptr_offset, native_size);

	// add the item to the back of the list
	m_items.emplace_back(ptr_offset, type, native_size, name);
	return m_items.back();
}


//-------------------------------------------------
//  find - find a subitem by name
//-------------------------------------------------

save_registered_item *save_registered_item::find(char const *name)
{
	// blank names can't be found this way
	if (name[0] == 0)
		return nullptr;

	// make sure there are no duplicates
	for (auto &item : m_items)
		if (strcmp(item.name(), name) == 0)
			return &item;
	return nullptr;
}


//-------------------------------------------------
//  sort_and_prune - prune empty subitems and
//  sort them by name
//-------------------------------------------------

bool save_registered_item::sort_and_prune()
{
	// only applies to arrays, structs, and containers; don't prune anything else
	if (!is_array() && !is_struct_or_container())
		return false;

	// first prune any empty items
	for (auto it = m_items.begin(); it != m_items.end(); )
	{
		if (it->sort_and_prune())
			it = m_items.erase(it);
		else
			++it;
	}

	// then sort the rest if we have more than 1
	if (m_items.size() > 1)
		m_items.sort([] (auto const &x, auto const &y) { return (std::strcmp(x.name(), y.name()) < 0); });

	// return true if we have nothing
	return (m_items.size() == 0);
}


//-------------------------------------------------
//  unwrap_and_update_objbase - unwrap trivial
//  type and update the object base
//-------------------------------------------------

bool save_registered_item::unwrap_and_update_objbase(uintptr_t &objbase) const
{
	// update the base pointer with our local base/offset
	objbase += m_ptr_offset;

	// switch off the type
	switch (m_type)
	{
		// unique ptrs retrieve the pointer from their container
		case TYPE_UNIQUE:
			objbase = reinterpret_cast<uintptr_t>(reinterpret_cast<generic_unique *>(objbase)->get());
			return true;

		// vectors retrieve the pointer from their container
		case TYPE_VECTOR:
			objbase = reinterpret_cast<uintptr_t>(&(*reinterpret_cast<generic_vector *>(objbase))[0]);
			return true;

		// pointers just extract the pointer directly
		case TYPE_POINTER:
			objbase = reinterpret_cast<uintptr_t>(*reinterpret_cast<generic_pointer *>(objbase));
			return true;

		// containers are always based at 0
		case TYPE_CONTAINER:
			objbase = 0;
			return false;

		// everything else is as-is
		default:
			return false;
	}
}


//-------------------------------------------------
//  save_binary - save this item and all owned
//  items into a binary form
//-------------------------------------------------

uint64_t save_registered_item::save_binary(uint8_t *ptr, uint64_t length, uintptr_t objbase) const
{
	// update the base pointer and forward if a trivial unwrap
	if (unwrap_and_update_objbase(objbase))
		return m_items.front().save_binary(ptr, length, objbase);

	// switch off the type
	uint64_t offset = 0;
	switch (m_type)
	{
		// boolean types save as a single byte
		case TYPE_BOOL:
			if (offset + 1 <= length)
				ptr[offset] = read_bool(objbase) ? 1 : 0;
			offset++;
			break;

		// integral/float types save as their native size
		case TYPE_INT:
		case TYPE_UINT:
		case TYPE_FLOAT:
			if (offset + m_native_size <= length)
				memcpy(&ptr[offset], reinterpret_cast<void const *>(objbase), m_native_size);
			offset += m_native_size;
			break;

		// structs and containers iterate over owned items
		case TYPE_CONTAINER:
		case TYPE_STRUCT:
			for (auto &item : m_items)
				offset += item.save_binary(&ptr[offset], (offset < length) ? length - offset : 0, objbase);
			break;

		// arrays are multiples of a single item
		default:
			if (is_array())
			{
				auto &item = m_items.front();
				for (uint32_t rep = 0; rep < m_type; rep++)
					offset += item.save_binary(&ptr[offset], (offset < length) ? length - offset : 0, objbase + rep * m_native_size);
			}
			break;
	}
	return offset;
}


//-------------------------------------------------
//  restore_binary - restore this item and all
//  owned items from binary form
//-------------------------------------------------

uint64_t save_registered_item::restore_binary(uint8_t const *ptr, uint64_t length, uintptr_t objbase) const
{
	// update the base pointer and forward if a trivial unwrap
	if (unwrap_and_update_objbase(objbase))
		return m_items.front().restore_binary(ptr, length, objbase);

	// switch off the type
	uint64_t offset = 0;
	switch (m_type)
	{
		// boolean types save as a single byte
		case TYPE_BOOL:
			if (offset + 1 <= length)
				write_bool(objbase, (ptr[offset] != 0));
			offset++;
			break;

		// integral/float types save as their native size
		case TYPE_INT:
		case TYPE_UINT:
		case TYPE_FLOAT:
			if (offset + m_native_size <= length)
				memcpy(reinterpret_cast<void *>(objbase), &ptr[offset], m_native_size);
			offset += m_native_size;
			break;

		// structs and containers iterate over owned items
		case TYPE_CONTAINER:
		case TYPE_STRUCT:
			for (auto &item : m_items)
				offset += item.restore_binary(&ptr[offset], (offset < length) ? length - offset : 0, objbase);
			break;

		// arrays are multiples of a single item
		default:
			if (is_array())
			{
				auto &item = m_items.front();
				for (uint32_t rep = 0; rep < m_type; rep++)
					offset += item.restore_binary(&ptr[offset], (offset < length) ? length - offset : 0, objbase + rep * m_native_size);
			}
			break;
	}
	return offset;
}


//-------------------------------------------------
//  save_json - save this item into a JSON stream
//-------------------------------------------------

void save_registered_item::save_json(save_zip_state &zipstate, char const *nameprefix, int indent, bool inline_form, uintptr_t objbase)
{
	// update the base pointer and forward if a trivial unwrap
	if (unwrap_and_update_objbase(objbase))
		return m_items.front().save_json(zipstate, nameprefix, indent, inline_form, objbase);

	// update the name prefix
	std::string localname = nameprefix;
	if (m_name.length() != 0)
	{
		if (localname.length() != 0)
			localname += ".";
		localname += m_name;
	}

	// output the name if present
	zipstate.json_append_name(m_name.c_str());

	// switch off the type
	switch (m_type)
	{
		// boolean types
		case TYPE_BOOL:
			zipstate.json_append(read_bool(objbase) ? "true" : "false");
			break;

		// signed integral types
		case TYPE_INT:
			zipstate.json_append_signed(read_int_signed(objbase, m_native_size));
			break;

		// unsigned integral types
		case TYPE_UINT:
			zipstate.json_append_unsigned(read_int_unsigned(objbase, m_native_size));
			break;

		// float types
		case TYPE_FLOAT:
			zipstate.json_append_float(read_float(objbase, m_native_size));
			break;

		// structs and containers iterate over owned items
		case TYPE_CONTAINER:
		case TYPE_STRUCT:
			if (inline_form || compute_binary_size(objbase - m_ptr_offset) <= 16)
			{
				// inline form outputs everything on a single line
				zipstate.json_append('{');
				for (auto &item : m_items)
				{
					item.save_json(zipstate, localname.c_str(), indent, true, objbase);
					if (&item != &m_items.back())
						zipstate.json_append(',');
				}
				zipstate.json_append('}');
			}
			else
			{
				// normal form outputs each item on its own line, indented
				zipstate.json_append('{').json_append_eol();
				for (auto &item : m_items)
				{
					zipstate.json_append_indent(indent + 1);
					item.save_json(zipstate, localname.c_str(), indent + 1, false, objbase);
					if (&item != &m_items.back())
						zipstate.json_append(',');
					zipstate.json_append_eol();
				}
				zipstate.json_append_indent(indent).json_append('}');
			}
			break;

		// arrays are multiples of a single item
		default:
			if (is_array())
			{
				auto &item = m_items.front();

				// look for large arrays of ints/floats
				save_registered_item *inner = &item;
				u32 total = count();
				while (inner->is_array())
				{
					total *= inner->count();
					inner = &inner->m_items.front();
				}
				if (inner->is_int_or_float() && total * inner->m_native_size >= save_zip_state::JSON_EXTERNAL_BINARY_THRESHOLD)
				{
					char const *filename = zipstate.add_data_file(localname.c_str(), *this, objbase);

					zipstate.json_append('[').json_append('{');
					zipstate.json_append_name("external_file");
					zipstate.json_append('"').json_append(filename).json_append('"').json_append(',');
					zipstate.json_append_name("unit");
					zipstate.json_append_signed(inner->m_native_size).json_append(',');
					zipstate.json_append_name("count");
					zipstate.json_append_signed(total).json_append(',');
					zipstate.json_append_name("little_endian");
					zipstate.json_append((ENDIANNESS_NATIVE == ENDIANNESS_LITTLE) ? "true" : "false");
					zipstate.json_append('}').json_append(']');
				}
				else
				{
					uint32_t item_size = item.compute_binary_size(objbase);
					if (inline_form || m_type * item_size <= 16)
					{
						// strictly inline form outputs everything on a single line
						zipstate.json_append('[');
						for (uint32_t rep = 0; rep < m_type; rep++)
						{
							item.save_json(zipstate, localname.c_str(), 0, true, objbase + rep * m_native_size);
							if (rep != m_type - 1)
								zipstate.json_append(',');
						}
						zipstate.json_append(']');
					}
					else
					{
						// normal form outputs a certain number of items per row
						zipstate.json_append('[').json_append_eol();
						uint32_t items_per_row = 1;
						if (item.is_int_or_float())
							items_per_row = (item_size <= 2) ? 32 : 16;

						// iterate over the items
						for (uint32_t rep = 0; rep < m_type; rep++)
						{
							if (rep % items_per_row == 0)
								zipstate.json_append_indent(indent + 1);
							item.save_json(zipstate, localname.c_str(), indent + 1, false, objbase + rep * m_native_size);
							if (rep != m_type - 1)
								zipstate.json_append(',');
							if (rep % items_per_row == items_per_row - 1)
								zipstate.json_append_eol();
						}
						if (m_type % items_per_row != 0)
							zipstate.json_append_eol();
						zipstate.json_append_indent(indent).json_append(']');
					}
				}
			}
			break;
	}
}


//-------------------------------------------------
//  restore_json - read data from a JSON file into
//  the target containers
//-------------------------------------------------

void save_registered_item::restore_json(load_zip_state &input, char const *nameprefix, json_restore_mode mode, uintptr_t objbase)
{
	// update the base pointer and forward if a trivial unwrap
	if (unwrap_and_update_objbase(objbase))
		return m_items.front().restore_json(input, nameprefix, mode, objbase);

	// update the name prefix
	std::string localname = nameprefix;
	if (m_name.length() != 0)
	{
		if (localname.length() != 0)
			localname += ".";
		localname += m_name;
	}

	// switch off the type
	switch (m_type)
	{
		// boolean types
		case TYPE_BOOL:
		{
			bool value = false;
			if (input.json_matches("true"))
				value = true;
			else if (input.json_matches("false"))
				value = false;
			else
				input.report_error("%s: Unknown boolean value", localname.c_str());
			if (mode == RESTORE_DATA)
				write_bool(objbase, value);
			else if (mode == COMPARE_DATA && read_bool(objbase) != value)
				input.report_warning("%s: Compare failed: JSON says %d, data says %d", localname.c_str(), value, read_bool(objbase));
			break;
		}

		// signed integral types
		case TYPE_INT:
		{
			double dvalue;
			int64_t ivalue;
			if (input.json_parse_number(dvalue))
			{
				if (mode == RESTORE_DATA && !write_int_signed(objbase, m_native_size, dvalue))
					input.report_warning("%s: Value of out range: %g", localname.c_str(), dvalue);
				else if (mode == COMPARE_DATA && read_int_signed(objbase, m_native_size) != int64_t(dvalue))
					input.report_warning("%s: Compare failed: JSON says %I64d, data says %g", localname.c_str(), dvalue, read_int_signed(objbase, m_native_size));
			}
			else if (input.json_parse_int_string(ivalue))
			{
				if (mode == RESTORE_DATA && !write_int_signed(objbase, m_native_size, ivalue))
					input.report_warning("%s: Value of out range: %I64d", localname.c_str(), ivalue);
				else if (mode == COMPARE_DATA && read_int_signed(objbase, m_native_size) != ivalue)
					input.report_warning("%s: Compare failed: JSON says %I64d, data says %I64d", localname.c_str(), ivalue, read_int_signed(objbase, m_native_size));
			}
			else
				input.report_error("%s: Expected integer value", localname.c_str());
			break;
		}

		// unsigned integral types
		case TYPE_UINT:
		{
			double dvalue;
			uint64_t ivalue;
			if (input.json_parse_number(dvalue))
			{
				if (mode == RESTORE_DATA && !write_int_unsigned(objbase, m_native_size, dvalue))
					input.report_warning("%s: Value of out range: %g", localname.c_str(), dvalue);
				else if (mode == COMPARE_DATA && read_int_unsigned(objbase, m_native_size) != uint64_t(dvalue))
					input.report_warning("%s: Compare failed: JSON says %I64d, data says %g", localname.c_str(), dvalue, read_int_unsigned(objbase, m_native_size));
			}
			else if (input.json_parse_uint_string(ivalue))
			{
				if (mode == RESTORE_DATA && !write_int_unsigned(objbase, m_native_size, ivalue))
					input.report_warning("%s: Value of out range: %I64d", localname.c_str(), ivalue);
				else if (mode == COMPARE_DATA && read_int_unsigned(objbase, m_native_size) != ivalue)
					input.report_warning("%s: Compare failed: JSON says %I64d, data says %I64d", localname.c_str(), ivalue, read_int_unsigned(objbase, m_native_size));
			}
			else
				input.report_error("%s: Expected integer value", localname.c_str());
			break;
		}

		// float types
		case TYPE_FLOAT:
		{
			double value;
			if (!input.json_parse_number(value))
				input.report_error("%s: Expected number", localname.c_str());
			if (mode == RESTORE_DATA && !write_float(objbase, m_native_size, value))
				input.report_warning("%s: Value of out range: %g", localname.c_str(), value);
			else if (mode == COMPARE_DATA && read_float(objbase, m_native_size) != value)
				input.report_warning("%s: Compare failed: JSON says %g, data says %g", localname.c_str(), value, read_float(objbase, m_native_size));
			break;
		}

		// structs and containers iterate over owned items
		case TYPE_CONTAINER:
		case TYPE_STRUCT:
			if (!input.json_matches('{'))
				input.report_error("%s: Expected '{'", localname.c_str());
			if (!input.json_matches('}'))
				while (1)
				{
					std::string name;
					if (!input.json_parse_string(name) || name == "")
						input.report_error("%s: Expected name within struct", localname.c_str());
					if (!input.json_matches(':'))
						input.report_error("%s: Expected ':'", localname.c_str());
					save_registered_item *target = find(name.c_str());
					if (target == nullptr)
						input.report_warning("%s: Found extraneous item '%s'", localname.c_str(), name.c_str());
					target->restore_json(input, nameprefix, (target == nullptr) ? PARSE_ONLY : mode, objbase);
					if (input.json_matches('}'))
						break;
					if (!input.json_matches(','))
						input.report_error("%s: Expected ','", localname.c_str());
				}
			break;

		// arrays are multiples of a single item
		default:
			if (is_array())
			{
				auto &item = m_items.front();
				if (!input.json_matches('['))
					input.report_error("%s: Expected '['", localname.c_str());
				if (parse_external_data(input, *this, localname.c_str(), mode, objbase))
				{
					if (!input.json_matches(']'))
						input.report_error("%s: Expected ']'", localname.c_str());
				}
				else
				{
					u32 rep = 0;
					if (!input.json_matches(']'))
						while (1)
						{
							item.restore_json(input, nameprefix, (rep >= count()) ? PARSE_ONLY : mode, objbase + rep * m_native_size);
							rep++;
							if (input.json_matches(']'))
								break;
							if (!input.json_matches(','))
								input.report_error("%s: Expected ','", localname.c_str());
						}
					if (rep != count())
						input.report_warning("%s: Found %s array items than expected", localname.c_str(), (rep < count()) ? "fewer" : "more");
				}
			}
			break;
	}
}


//-------------------------------------------------
//  parse_external_data - attempt to parse an
//  external file spec from a JSON file and load
//  it; returns false if not an external file spec
//-------------------------------------------------

bool save_registered_item::parse_external_data(load_zip_state &input, save_registered_item &baseitem, char const *localname, bool parseonly, uintptr_t objbase)
{
	const bool native_little_endian = (ENDIANNESS_NATIVE == ENDIANNESS_LITTLE);

	char const *pos = input.json_position();
	if (!input.json_matches('{'))
		return false;

	std::string parsed_filename;
	double parsed_unit = 0;
	double parsed_count = 0;
	bool parsed_little_endian = native_little_endian;
	bool valid = false;
	while (1)
	{
		std::string name;
		if (!input.json_parse_string(name) || name == "")
			input.report_error("%s: Expected name within struct", localname);
		if (!input.json_matches(':'))
			input.report_error("%s: Expected ':'", localname);
		valid = false;
		if (name == "external_file" && parsed_filename == "" && input.json_parse_string(parsed_filename) && parsed_filename != "")
			valid = true;
		else if (name == "unit" && parsed_unit == 0 && input.json_parse_number(parsed_unit) && parsed_unit != 0)
			valid = true;
		else if (name == "count" && parsed_count == 0 && input.json_parse_number(parsed_count) && parsed_count != 0)
			valid = true;
		else if (name == "little_endian")
		{
			if (input.json_matches("true"))
				parsed_little_endian = true, valid = true;
			else if (input.json_matches("false"))
				parsed_little_endian = false, valid = true;
		}
		if (!valid)
			break;
		if (input.json_matches('}'))
			break;
		if (!input.json_matches(','))
			input.report_error("%s: Expected ','", localname);
	}
	if (!valid)
	{
		input.json_set_position(pos);
		return false;
	}

	// validate the data we found
	u64 offset;
	u32 size;
	if (!input.find_file(parsed_filename.c_str(), offset, size))
		input.report_error("%s: Unable to find file '%s' in archive", localname, parsed_filename.c_str());
	if (parsed_unit != 1 && parsed_unit != 2 && parsed_unit != 4 && parsed_unit != 8)
		input.report_error("%s: Invalid unit size for external file, expected 1, 2, 4, or 8", localname);
	if (parsed_count == 0)
		input.report_error("%s: Invalid count for external file", localname);

	// look for the innermost registered item
	save_registered_item *inner = &baseitem.subitems().front();
	u32 total = count();
	while (inner->is_array())
	{
		total *= inner->count();
		inner = &inner->subitems().front();
	}
	if (!inner->is_int_or_float())
		input.report_error("%s: External file specified, but not valid for this type", localname);
	if (parsed_unit != inner->native_size())
		input.report_error("%s: External file has mismatched unit size", localname);

	// if parseonly, we're done
	if (parseonly)
		return true;

	// ok time to stream the data out
	bool flip = (parsed_little_endian != native_little_endian);
	zlib_read_streamer reader(input.file());
	if (!reader.begin(offset) || !input.read_data_recursive(reader, *this, flip, size, objbase) || !reader.end())
		input.report_error("%s: Error reading file '%s' in archive", localname, parsed_filename.c_str());

	return true;
}


//-------------------------------------------------
//  read_int_unsigned - read an unsigned integer
//  of the given size
//-------------------------------------------------

uint64_t save_registered_item::read_int_unsigned(uintptr_t objbase, int size) const
{
	switch (size)
	{
		case 1:	return *reinterpret_cast<uint8_t const *>(objbase);
		case 2:	return *reinterpret_cast<uint16_t const *>(objbase);
		case 4:	return *reinterpret_cast<uint32_t const *>(objbase);
		case 8:	return *reinterpret_cast<uint64_t const *>(objbase);
	}
	return 0;
}


//-------------------------------------------------
//  read_int_signed - read a signed integer of the
//  given size
//-------------------------------------------------

int64_t save_registered_item::read_int_signed(uintptr_t objbase, int size) const
{
	switch (size)
	{
		case 1:	return *reinterpret_cast<int8_t const *>(objbase);
		case 2:	return *reinterpret_cast<int16_t const *>(objbase);
		case 4:	return *reinterpret_cast<int32_t const *>(objbase);
		case 8:	return *reinterpret_cast<int64_t const *>(objbase);
	}
	return 0;
}


//-------------------------------------------------
//  read_float - read a floating-point value of the
//  given size
//-------------------------------------------------

double save_registered_item::read_float(uintptr_t objbase, int size) const
{
	switch (size)
	{
		case 4:	return *reinterpret_cast<float const *>(objbase);
		case 8:	return *reinterpret_cast<double const *>(objbase);
	}
	return 0;
}


//-------------------------------------------------
//  write_int_signed - write a signed integer of
//  the given size
//-------------------------------------------------

bool save_registered_item::write_int_signed(uintptr_t objbase, int size, int64_t data) const
{
	switch (size)
	{
		case 1:	*reinterpret_cast<int8_t *>(objbase) = int8_t(data); return (data >= -0x80 && data <= 0x7f);
		case 2:	*reinterpret_cast<int16_t *>(objbase) = int16_t(data); return (data >= -0x8000 && data <= 0x7fff);
		case 4:	*reinterpret_cast<int32_t *>(objbase) = int32_t(data); return (data >= -0x80000000ll && data <= 0x7fffffffll);
		case 8:	*reinterpret_cast<int64_t *>(objbase) = int64_t(data); return true;
	}
	return false;
}

bool save_registered_item::write_int_signed(uintptr_t objbase, int size, double data) const
{
	int64_t converted = int64_t(data);
	bool ok = (double(converted) == data);
	return write_int_signed(objbase, size, converted) && ok;
}


//-------------------------------------------------
//  write_int_unsigned - write an unsigned integer
//  of the given size
//-------------------------------------------------

bool save_registered_item::write_int_unsigned(uintptr_t objbase, int size, uint64_t data) const
{
	switch (size)
	{
		case 1:	*reinterpret_cast<uint8_t *>(objbase) = uint8_t(data); return (data <= 0xff);
		case 2:	*reinterpret_cast<uint16_t *>(objbase) = uint16_t(data); return (data <= 0xffff);
		case 4:	*reinterpret_cast<uint32_t *>(objbase) = uint32_t(data); return (data <= 0xffffffffull);
		case 8:	*reinterpret_cast<uint64_t *>(objbase) = uint64_t(data); return true;
	}
	return false;
}

bool save_registered_item::write_int_unsigned(uintptr_t objbase, int size, double data) const
{
	uint64_t converted = uint64_t(data);
	bool ok = (data >= 0 && double(converted) == data);
	return write_int_unsigned(objbase, size, converted) && ok;
}


//-------------------------------------------------
//  write_float - write a floating-point value of
//  the given size
//-------------------------------------------------

bool save_registered_item::write_float(uintptr_t objbase, int size, double data) const
{
	switch (size)
	{
		case 4:	*reinterpret_cast<float *>(objbase) = float(data); return true;
		case 8:	*reinterpret_cast<double *>(objbase) = double(data); return true;
	}
	return false;
}



//**************************************************************************
//  SAVE MANAGER
//**************************************************************************

//-------------------------------------------------
//  save_manager - constructor
//-------------------------------------------------

save_manager::save_manager(running_machine &machine) :
	m_machine(machine),
	m_reg_allowed(true),
	m_root_registrar(m_root_item)
{
	m_rewind = std::make_unique<rewinder>(*this);
}


//-------------------------------------------------
//  allow_registration - allow/disallow
//  registrations to happen
//-------------------------------------------------

void save_manager::allow_registration(bool allowed)
{
	// allow/deny registration
	m_reg_allowed = allowed;
	if (!allowed)
	{
		// prune and sort
		m_root_item.sort_and_prune();

		// dump out a sample JSON
		{
			save_zip_state state;
			m_root_item.save_json(state);
			printf("%s\n", state.json_string());
		}

		// everything is registered by now, evaluate the savestate size
		m_rewind->clamp_capacity();
	}
}


//-------------------------------------------------
//  register_presave - register a pre-save
//  function callback
//-------------------------------------------------

void save_manager::register_presave(save_prepost_delegate func)
{
	// check for invalid timing
	if (!m_reg_allowed)
		fatalerror("Attempt to register callback function after state registration is closed!\n");

	// scan for duplicates and push through to the end
	for (auto &cb : m_presave_list)
		if (cb->m_func == func)
			fatalerror("Duplicate save state function (%s/%s)\n", cb->m_func.name(), func.name());

	// allocate a new entry
	m_presave_list.push_back(std::make_unique<state_callback>(func));
}


//-------------------------------------------------
//  state_save_register_postload -
//  register a post-load function callback
//-------------------------------------------------

void save_manager::register_postload(save_prepost_delegate func)
{
	// check for invalid timing
	if (!m_reg_allowed)
		fatalerror("Attempt to register callback function after state registration is closed!\n");

	// scan for duplicates and push through to the end
	for (auto &cb : m_postload_list)
		if (cb->m_func == func)
			fatalerror("Duplicate save state function (%s/%s)\n", cb->m_func.name(), func.name());

	// allocate a new entry
	m_postload_list.push_back(std::make_unique<state_callback>(func));
}


//-------------------------------------------------
//  dispatch_postload - invoke all registered
//  postload callbacks for updates
//-------------------------------------------------

void save_manager::dispatch_postload()
{
	for (auto &func : m_postload_list)
		func->m_func();
}


//-------------------------------------------------
//  dispatch_presave - invoke all registered
//  presave callbacks for updates
//-------------------------------------------------

void save_manager::dispatch_presave()
{
	for (auto &func : m_presave_list)
		func->m_func();
}


//-------------------------------------------------
//  save_binary - invoke all registered presave
//  callbacks for updates and then generate the
//  data in binary form
//-------------------------------------------------

save_error save_manager::save_binary(void *buf, size_t size)
{
	// call the pre-save functions
	dispatch_presave();

	// write the output
	u64 finalsize = m_root_item.save_binary(reinterpret_cast<u8 *>(buf), size);
	if (finalsize != size)
		return STATERR_WRITE_ERROR;

	return STATERR_NONE;
}


//-------------------------------------------------
//  load_binary - restore all data and then call
//  the postload callbacks
//-------------------------------------------------

save_error save_manager::load_binary(void *buf, size_t size)
{
	// read the input
	u64 finalsize = m_root_item.restore_binary(reinterpret_cast<u8 *>(buf), size);
	if (finalsize != size)
		return STATERR_READ_ERROR;

	// call the post-load functions
	dispatch_postload();
	return STATERR_NONE;
}


//-------------------------------------------------
//  save_file - invoke all registered presave
//  callbacks for updates and then generate the
//  data in JSON/ZIP form
//-------------------------------------------------

save_error save_manager::save_file(emu_file &file)
{
	// call the pre-save functions
	dispatch_presave();

	// create the JSON and target all the output files
	save_zip_state state;
	m_root_item.save_json(state);

	// then commit the state to the file
	return state.commit(file) ? STATERR_NONE : STATERR_WRITE_ERROR;
}


//-------------------------------------------------
//  load_file - restore all data and then call
//  the postload callbacks
//-------------------------------------------------

save_error save_manager::load_file(emu_file &file)
{
	// create the JSON and target all the output files
	load_zip_state state(file);
	save_error err = state.init();
	if (err != STATERR_NONE)
		return err;

	// restore_json will throw on parse errors and the like
	try
	{
		m_root_item.restore_json(state);
		char const *warnings = state.warnings();
		if (warnings != nullptr)
			printf("WARNINGS during state load:\n%s", warnings);
	}
	catch (load_zip_state::load_error &)
	{
		char const *errors = state.errors();
		if (errors != nullptr)
			printf("ERRORS during state load:\n%s", errors);
		return STATERR_READ_ERROR;
	}

	// call the post-load functions
	dispatch_postload();
	return STATERR_NONE;
}



//**************************************************************************
//  RAM STATE
//**************************************************************************

//-------------------------------------------------
//  ram_state - constructor
//-------------------------------------------------

ram_state::ram_state(save_manager &save) :
	m_valid(false),
	m_time(m_save.machine().time()),
	m_save(save)
{
}


//-------------------------------------------------
//  save - write the current machine state to the
//  allocated stream
//-------------------------------------------------

save_error ram_state::save()
{
	// initialize
	m_valid = false;

	// get the save manager to write state
	const save_error err = m_save.save_binary(m_data);
	if (err != STATERR_NONE)
		return err;

	// final confirmation
	m_valid = true;
	m_time = m_save.machine().time();

	return STATERR_NONE;
}


//-------------------------------------------------
//  load - restore the machine state from the
//  stream
//-------------------------------------------------

save_error ram_state::load()
{
	// get the save manager to load state
	return m_save.load_binary(m_data);
}



//**************************************************************************
//  REWINDER
//**************************************************************************

//-------------------------------------------------
//  rewinder - constuctor
//-------------------------------------------------

rewinder::rewinder(save_manager &save) :
	m_save(save),
	m_enabled(save.machine().options().rewind()),
	m_capacity(save.machine().options().rewind_capacity()),
	m_current_index(REWIND_INDEX_NONE),
	m_first_invalid_index(REWIND_INDEX_NONE),
	m_first_time_warning(true),
	m_first_time_note(true)
{
}


//-------------------------------------------------
//  clamp_capacity - safety checks for commandline
//  override
//-------------------------------------------------

void rewinder::clamp_capacity()
{
	if (!m_enabled)
		return;

	const size_t total = m_capacity * 1024 * 1024;
	const size_t single = m_save.binary_size();

	// can't set below zero, but allow commandline to override options' upper limit
	if (total < 0)
		m_capacity = 0;

	// if capacity is below savestate size, can't save anything
	if (total < single)
	{
		m_enabled = false;
		m_save.machine().logerror("Rewind has been disabled, because rewind capacity is smaller than savestate size.\n");
		m_save.machine().logerror("Rewind buffer size: %d bytes. Savestate size: %d bytes.\n", total, single);
		m_save.machine().popmessage("Rewind has been disabled. See error.log for details");
	}
}


//-------------------------------------------------
//  invalidate - mark all the future states as
//  invalid to prevent loading them, as the
//  current input might have changed
//-------------------------------------------------

void rewinder::invalidate()
{
	if (!m_enabled)
		return;

	// is there anything to invalidate?
	if (!current_index_is_last())
	{
		// all states starting from the current one will be invalid
		m_first_invalid_index = m_current_index;

		// actually invalidate
		for (auto it = m_state_list.begin() + m_first_invalid_index; it < m_state_list.end(); ++it)
			it->get()->m_valid = false;
	}
}


//-------------------------------------------------
//  capture - record a single state, returns true
//  on success
//-------------------------------------------------

bool rewinder::capture()
{
	if (!m_enabled)
	{
		report_error(STATERR_DISABLED, rewind_operation::SAVE);
		return false;
	}

	if (current_index_is_last())
	{
		// we need to create a new state
		std::unique_ptr<ram_state> state = std::make_unique<ram_state>(m_save);
		const save_error error = state->save();

		// validate the state
		if (error == STATERR_NONE)
			// it's safe to append
			m_state_list.push_back(std::move(state));
		else
		{
			// internal error, complain and evacuate
			report_error(error, rewind_operation::SAVE);
			return false;
		}
	}
	else
	{
		// invalidate the future states
		invalidate();

		// update the existing state
		ram_state *state = m_state_list.at(m_current_index).get();
		const save_error error = state->save();

		// validate the state
		if (error != STATERR_NONE)
		{
			// internal error, complain and evacuate
			report_error(error, rewind_operation::SAVE);
			return false;
		}
	}

	// make sure we will fit in
	if (!check_size())
		// the list keeps growing
		m_current_index++;

	// update first invalid index
	if (current_index_is_last())
		m_first_invalid_index = REWIND_INDEX_NONE;
	else
		m_first_invalid_index = m_current_index + 1;

	// success
	report_error(STATERR_NONE, rewind_operation::SAVE);
	return true;
}


//-------------------------------------------------
//  step - single step back in time, returns true
//  on success
//-------------------------------------------------

bool rewinder::step()
{
	if (!m_enabled)
	{
		report_error(STATERR_DISABLED, rewind_operation::LOAD);
		return false;
	}

	// do we have states to load?
	if (m_current_index <= REWIND_INDEX_FIRST || m_first_invalid_index == REWIND_INDEX_FIRST)
	{
		// no valid states, complain and evacuate
		report_error(STATERR_NOT_FOUND, rewind_operation::LOAD);
		return false;
	}

	// prepare to load the last valid index if we're too far ahead
	if (m_first_invalid_index > REWIND_INDEX_NONE && m_current_index > m_first_invalid_index)
		m_current_index = m_first_invalid_index;

	// step back and obtain the state pointer
	ram_state *state = m_state_list.at(--m_current_index).get();

	// try to load and report the result
	const save_error error = state->load();
	report_error(error, rewind_operation::LOAD);

	if (error == save_error::STATERR_NONE)
		return true;

	return false;
}


//-------------------------------------------------
//  check_size - shrink the state list if it is
//  about to hit the capacity. returns true if
//  the list got shrank
//-------------------------------------------------

bool rewinder::check_size()
{
	if (!m_enabled)
		return false;

	// state sizes in bytes
	const size_t singlesize = m_save.binary_size();
	size_t totalsize = m_state_list.size() * singlesize;

	// convert our limit from megabytes
	const size_t capsize = m_capacity * 1024 * 1024;

	// safety check that shouldn't be allowed to trigger
	if (totalsize > capsize)
	{
		// states to remove
		const u32 count = (totalsize - capsize) / singlesize;

		// drop everything that's beyond capacity
		m_state_list.erase(m_state_list.begin(), m_state_list.begin() + count);
	}

	// update before new check
	totalsize = m_state_list.size() * singlesize;

	// check if capacity will be hit by the newly captured state
	if (totalsize + singlesize >= capsize)
	{
		// check if we have spare states ahead
		if (!current_index_is_last())
			// no need to move states around
			return false;

		// we can now get the first state and invalidate it
		std::unique_ptr<ram_state> first(std::move(m_state_list.front()));
		first->m_valid = false;

		// move it to the end for future use
		m_state_list.push_back(std::move(first));
		m_state_list.erase(m_state_list.begin());

		if (m_first_time_note)
		{
			m_save.machine().logerror("Rewind note: Capacity has been reached. Old savestates will be erased.\n");
			m_save.machine().logerror("Capacity: %d bytes. Savestate size: %d bytes. Savestate count: %d.\n",
				totalsize, singlesize, m_state_list.size());
			m_first_time_note = false;
		}

		return true;
	}

	return false;
}


//-------------------------------------------------
//  report_error - report rewind results
//-------------------------------------------------

void rewinder::report_error(save_error error, rewind_operation operation)
{
	const char *const opname = (operation == rewind_operation::LOAD) ? "load" : "save";
	switch (error)
	{
	// internal saveload failures
	case STATERR_ILLEGAL_REGISTRATIONS:
		m_save.machine().logerror("Rewind error: Unable to %s state due to illegal registrations.", opname);
		m_save.machine().popmessage("Rewind error occured. See error.log for details.");
		break;

	case STATERR_INVALID_HEADER:
		m_save.machine().logerror("Rewind error: Unable to %s state due to an invalid header. "
			"Make sure the save state is correct for this machine.\n", opname);
		m_save.machine().popmessage("Rewind error occured. See error.log for details.");
		break;

	case STATERR_READ_ERROR:
		m_save.machine().logerror("Rewind error: Unable to %s state due to a read error.\n", opname);
		m_save.machine().popmessage("Rewind error occured. See error.log for details.");
		break;

	case STATERR_WRITE_ERROR:
		m_save.machine().logerror("Rewind error: Unable to %s state due to a write error.\n", opname);
		m_save.machine().popmessage("Rewind error occured. See error.log for details.");
		break;

	// external saveload failures
	case STATERR_NOT_FOUND:
		if (operation == rewind_operation::LOAD)
		{
			m_save.machine().logerror("Rewind error: No rewind state to load.\n");
			m_save.machine().popmessage("Rewind error occured. See error.log for details.");
		}
		break;

	case STATERR_DISABLED:
		if (operation == rewind_operation::LOAD)
		{
			m_save.machine().logerror("Rewind error: Rewind is disabled.\n");
			m_save.machine().popmessage("Rewind error occured. See error.log for details.");
		}
		break;

	// success
	case STATERR_NONE:
		{
			const u64 supported = m_save.machine().system().flags & MACHINE_SUPPORTS_SAVE;
			const char *const warning = supported || !m_first_time_warning ? "" :
				"Rewind warning: Save states are not officially supported for this machine.\n";
			const char *const opnamed = (operation == rewind_operation::LOAD) ? "loaded" : "captured";

			// for rewinding outside of debugger, give some indication that rewind has worked, as screen doesn't update
			m_save.machine().popmessage("Rewind state %i %s.\n%s", m_current_index + 1, opnamed, warning);
			if (m_first_time_warning && operation == rewind_operation::LOAD && !supported)
			{
				m_save.machine().logerror(warning);
				m_first_time_warning = false;
			}
		}
		break;

	// something that shouldn't be allowed to happen
	default:
		m_save.machine().logerror("Error: Unknown error during state %s.\n", opname);
		m_save.machine().popmessage("Rewind error occured. See error.log for details.");
		break;
	}
}