summaryrefslogtreecommitdiffstatshomepage
path: root/src/tools/imgtool/modules/ti99.cpp
blob: 3f57f91db7cec6ef5ba4517a54e63d3026ccc7ea (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
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>0.9.8: orthonormalize.hpp File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="logo.png"/></td>
  <td id="projectalign" style="padding-left: 0.5em;">
   <div id="projectname">0.9.8
   </div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.10 -->
  <div id="navrow1" class="tabs">
    <ul class="tablist">
      <li><a href="index.html"><span>Main&#160;Page</span></a></li>
      <li><a href="modules.html"><span>Modules</span></a></li>
      <li class="current"><a href="files.html"><span>Files</span></a></li>
    </ul>
  </div>
  <div id="navrow2" class="tabs2">
    <ul class="tablist">
      <li><a href="files.html"><span>File&#160;List</span></a></li>
    </ul>
  </div>
<div id="nav-path" class="navpath">
  <ul>
<li class="navelem"><a class="el" href="dir_275089585c7fc1b5fd5d7d42c69cb1da.html">D:</a></li><li class="navelem"><a class="el" href="dir_7b98f88bffbed4b390b5f8f520d9c08e.html">Source</a></li><li class="navelem"><a class="el" href="dir_1f76e953200861345293ade84ac7fb6c.html">G-Truc</a></li><li class="navelem"><a class="el" href="dir_e29b03b892e0e25920d021a614d4db9b.html">glm</a></li><li class="navelem"><a class="el" href="dir_5ce58d942b2d0776e17a9a58abc01e04.html">glm</a></li><li class="navelem"><a class="el" href="dir_8d176b5b7dd0ae42ea6876078f2bde49.html">gtx</a></li>  </ul>
</div>
</div><!-- top -->
<div class="header">
  <div class="summary">
<a href="#func-members">Functions</a>  </div>
  <div class="headertitle">
<div class="title">orthonormalize.hpp File Reference</div>  </div>
</div><!--header-->
<div class="contents">

<p><a href="a00079_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:ga23c4340b8f1559d259229b6d8bdc3f97"><td class="memTemplParams" colspan="2">template&lt;typename T , precision P&gt; </td></tr>
<tr class="memitem:ga23c4340b8f1559d259229b6d8bdc3f97"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL tmat3x3&lt; T, P &gt;&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00216.html#ga23c4340b8f1559d259229b6d8bdc3f97">orthonormalize</a> (tmat3x3&lt; T, P &gt; const &amp;m)</td></tr>
<tr class="separator:ga23c4340b8f1559d259229b6d8bdc3f97"><td class="memSeparator" colspan="2">&#160;</td></tr>
<tr class="memitem:gad7afff30d7323fdc7aed7f5a16a0c596"><td class="memTemplParams" colspan="2">template&lt;typename T , precision P&gt; </td></tr>
<tr class="memitem:gad7afff30d7323fdc7aed7f5a16a0c596"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL tvec3&lt; T, P &gt;&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00216.html#gad7afff30d7323fdc7aed7f5a16a0c596">orthonormalize</a> (tvec3&lt; T, P &gt; const &amp;x, tvec3&lt; T, P &gt; const &amp;y)</td></tr>
<tr class="separator:gad7afff30d7323fdc7aed7f5a16a0c596"><td class="memSeparator" colspan="2">&#160;</td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p><a class="el" href="a00216.html">GLM_GTX_orthonormalize</a> </p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00156.html" title="The core of GLM, which implements exactly and only the GLSL specification to the degree possible...">GLM Core</a> (dependence) </dd>
<dd>
<a class="el" href="a00192.html" title="Min and max functions for 3 to 4 parameters. ">GLM_GTX_extented_min_max</a> (dependence) </dd></dl>

<p>Definition in file <a class="el" href="a00079_source.html">orthonormalize.hpp</a>.</p>
</div></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.10
</small></address>
</body>
</html>
1049'>1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358
// license:BSD-3-Clause
// copyright-holders:Raphael Nabet
/*
    Handlers for ti99 disk images

    We support the following types of image:
    * floppy disks ("DSK format") in v9t9, pc99 and old mess image format
    * hard disks ("WIN format") in MAME harddisk format (256-byte sectors only,
      i.e. no SCSI)
    Files are extracted in TIFILES format.  There is a compile-time option to
    extract text files in flat format instead, but I need to re-implement it
    properly (using filters comes to mind).

    Raphael Nabet, 2002-2004

    TODO:
    - finish and test hd support ***test sibling FDR support***
    - check allocation bitmap against corruption when an image is opened
*/

#include "imgtool.h"
#include "harddisk.h"
#include "imghd.h"

#include "opresolv.h"

#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>

/*
    Concepts shared by both disk structures:
    ----------------------------------------

    In both formats, the entire disk surface is split into physical records,
    each 256-byte-long.  For best efficiency, the sector size is usually 256
    bytes so that one sector is equivalent to a physical record (this is true
    with floppies and HFDC hard disks).  If the sector size is not 256 bytes
    (e.g. 512 bytes with SCSI hard disks, possibly 128 bytes on a TI-99
    simulator running on TI-990), sectors are grouped or split to form 256-byte
    physical records.  Physical records are numbered from 0, with the first
    starting on sector 0 track 0.  To avoid confusion with physical records in
    files, such physical records will be called "absolute physical records",
    abbreviated as "absolute physrecs" or "aphysrecs".

    Disk space is allocated in units referred to as AUs.  Each AU represents an
    integral number of 256-byte physical records.  The number of physrecs per
    AU varies depending on the disk format and size.  AUs are numbered from 0,
    with the first starting with absolute physrec 0.

    Absolute physrec 0 contains a 256-byte record with volume information,
    which is called "Volume Information Block", abbreviated as "vib".

    To keep track of which areas on the disk are allocated and which are free,
    disk managers maintain a bit map of allocated AUs (called "allocation
    bitmap", abbreviated as "abm").  Each bit in the allocation bitmap
    represents an AU: if a bit is 0, the AU is free; if a bit is 1, the AU is
    allocated (or possibly bad if the disk manager can track bad sectors).
    Where on the disk the abm is located depends on the disk structure (see
    structure-specific description for details).

    Files are implemented as a succession of 256-byte physical records.  To
    avoid confusion with absolute physical records, these physical records will
    be called "file physical records", abbreviated as "file physrecs" or
    "fphysrecs".

    Programs do normally not access file physical records directly.  They may
    call high-level file routines that enable to create either fixed-length
    logical records of any size from 1 through 255, or variable-length records
    of any size from 0 through 254: logical records are grouped by file
    managers into 256-byte physical records.  Some disk managers (HFDC and
    SCSI) allow programs to create fixed-length records larger than 255 bytes,
    too, but few programs use this possibility.  Additionally, program files
    can be created: program files do not implement any logical record, and can
    be seen as a flat byte stream, not unlike files under MSDOS, UNIX and the C
    standard library.  (Unfortunately, the API for program files lacks
    flexibility, and most programs that need to process a flat byte stream
    will use fixed-size records of 128 bytes.)

        Fixed-length records (reclen < 256) are grouped like this:
              fphysrec 0        fphysrec 1
            _______________   _______________
            |R0 |R1 |R2 |X|   |R3 |R4 |R5 |X|
            ---------------   ---------------
                        \_/               \_/
                       unused            unused
                  (size < reclen)   (size < reclen)

        Fixed-length records (reclen > 256) are grouped like this:
              fphysrec 0         fphysrec 1         fphysrec 2          fphysrec 3      ...
            _________________  _________________  _________________   _________________
            |  R0 (#0-255)  |  | R0 (#256-511) |  |R0 (#512-end)|X|   |  R1 (#0-255)  |   ...
            -----------------  -----------------  -----------------   -----------------
                                                                \_/
                                                               unused

        Variable length records are grouped like this:
                             fphysrec 0:
            byte:
                    ------------------------------
                  0 |l0 = length of record 0 data|
                    |----------------------------|
                  1 |                            |
                    |                            |
                  : |       record 0 data        |
                    |                            |
                 l0 |                            |
                    |----------------------------|
               l0+1 |l1 = length of record 1 data|
                    |----------------------------|
               l0+2 |                            |
                    |                            |
                  : |       record 1 data        |
                    |                            |
            l0+l1+1 |                            |
                    |----------------------------|
                  : :                            :
                  : :                            :
                    |----------------------------|
                  n |lm = length of record m data|
                    |----------------------------|
                n+1 |                            |
                    |                            |
                  : |       record m data        |
                    |                            |
               n+lm |                            |
                    |----------------------------|
             n+lm+1 |>ff: EOR mark               |
                    |----------------------------|
             n+lm+2 |                            |
                    |                            |
                  : |           unused           |
                  : |(we should have size < lm+1)|
                    |                            |
                255 |                            |
                    ------------------------------

                             fphysrec 1:
            byte:
                    ------------------------------
                  0 |lm+1=length of record 0 data|
                    |----------------------------|
                  1 |                            |
                    |                            |
                  : |      record m+1 data       |
                    |                            |
               lm+1 |                            |
                    |----------------------------|
                  : :                            :
                  : :                            :

            I think the EOR mark is not required if all 256 bytes of a physical
            record are used by logical records.


    All files are associated with a "file descriptor record" ("fdr") that holds
    file information (name, format, length) and points to the data AUs. The WIN
    disk structure also supports sibling FDRs, in case a file is so fragmented
    that all the data pointers cannot fit in one FDR; the DSK disk structure
    does not implement any such feature, and you may be unable to append data
    to an existing file if it is too fragmented, even though the disk is not
    full.


    DSK disk structure:
    -------------------

    The DSK disk structure is used for floppy disks, and a few RAMDISKs as
    well.  It supports 1600 AUs and 16 MBytes at most (the 16 MByte value is a
    theoretical maximum, as I doubt anyone has ever created so big a DSK volume).

    The disk sector size is always 256 bytes (the only potential exceptions are
    the SCSI floppy disk units and the TI-99 simulator on TI-990, but I don't
    know anything about either).

    For some reason, the number of physrecs per AU is always a power of 2.
    Originally, AUs always were one physical record each.  However, since the
    allocation bitmap cannot support more than 1600 AUs, disks larger than
    400kbytes need to have several physical records per AU.  Note that
    relatively few disk controllers implement AUs that span multiple physical
    records (IIRC, these are Myarc's HFDC, SCSI DSR with floppy disk interface,
    and some upgraded Myarc and Corcomp DD floppy controllers).

    The allocation bitmap is located in the VIB.  It is 200 bytes long, and
    supports 1600 AUs at most.

    Directories are implemented with a "File Descriptor Index Record" (FDIR)
    for each directory.  The FDIR is array of 0 through 128 words, containing
    the aphysrec address of each fdr in the directory, sorted by ascending file
    name, terminated with a 0.  Note that, while we should be prepared to read
    images images with 128 entries, I think (not 100% sure) that we should
    write no more than 127 for compatibility with some existing disk managers.

    Originally, the DSK structure only supported one directory level (i.e. the
    root directory level).  The FDIR record for the root directory is always
    located in aphysrec 1.  Moreover, Myarc extended the DSK structure to
    support up to 3 subdirectories in the root directory (note that there is no
    support for more subdirs, or for subdirs located in subdirs).  To do so,
    they used an unused field of the VIB to hold the 10-char name of each
    directory and the aphysrec address of the associated FDIR record.

    aphysrec 0: Volume Information Block (VIB): see below
    aphysrec 1: FDIR for root directory
    Remaining AUs are used for fdr and data (and subdirectory FDIR if
    applicable).  There is one FDIR record per directory; the FDIR points to
    the FDR for each file in the directory.  The FDR (File Descriptor Record)
    contains the file information (name, format, length, pointers to data
    physrecs/AUs, etc).


    WIN disk structure:
    -------------------

    The WIN disk structure is used for hard disks.  It supports 65535 AUs and
    256 MBytes at most.

    The disk sector size is 256 bytes on HFDC, 512 bytes on SCSI.  512-byte
    sectors are split into 256-byte physical records.

    We may have from 1 through 16 physrecs per AUs.  Since we cannot have more
    than 65535 AUs, we need to have several physical records per AU in disks
    larger than 16 Mbytes.

    Contrary to the DSK disk structure, the WIN disk structure supports
    hierarchic subdirectories, with a limit of 114 subdirectories and 127 files
    per directory.  Each directory is associated with both a "Directory
    Descriptor Record" (DDR) and a "File Descriptor Index Record" (FDIR).  The
    only exception is the root directory, which uses the VIB instead of a DDR
    (the VIB includes all the important fields of the DDR).  The DDR contains
    some directory info (name, number of files and subdirectories directly
    enclosed in the directory, AU address of the FDIR of the parent directory,
    etc), the AU address of the associated FDIR, and the AU address of the DDR
    of up to 114 subdirectories, sorted by ascending directory name.  The WIN
    FDIR is similar to, yet different from, the DSK FDIR: it contains up to 127
    (vs. 128) AU address (vs. aphysrec address) of each fdr in the directory,
    sorted by ascending file name.  Additionally, it includes the AU address of
    the associated DDR.

    When a file has more than 54 data fragments, the disk manager creates
    sibling FDRs that hold additional fragments.  (Sibling FDRs are called
    offspring FDRs in most existing documentation, but I prefer "sibling FDRs"
    as "offspring FDRs" wrongly suggests a directory-like hierarchy.
    Incidentally, I cannot really figure out why they chose to duplicate the
    FDR rather than create a file extension record, but there must be a
    reason.)  Note that sibling FDRs usually fill unused physrecs in the AU
    allocated for the eldest FDR, and a new AU is allocated for new sibling
    FDRs only when the first AU is full.

    aphysrec 0: Volume Information Block (VIB): see below
    aphysrec 1-n (where n = 1+SUP(number_of_AUs/2048)): Volume bitmap
    Remaining AUs are used for ddr, fdir, fdr and data.
*/

/* Since string length is encoded with a byte, the maximum length of a string
is 255.  Since we need to add a device name (1 char minimum, typically 4 chars)
and a '.' separator, we chose a practical value of 250 (though few applications
will accept paths of such length). */
#define MAX_PATH_LEN 253
#define MAX_SAFE_PATH_LEN 250

#define MAX_DIR_LEVEL 125   /* We need to put a recursion limit to avoid endless recursion hazard */


#if 0
#pragma mark MISCELLANEOUS UTILITIES
#endif

/*
    Miscellaneous utilities that are used to handle TI data types
*/

struct UINT16BE
{
	uint8_t bytes[2];
};

struct UINT16LE
{
	uint8_t bytes[2];
};

static inline uint16_t get_UINT16BE(UINT16BE word)
{
	return (word.bytes[0] << 8) | word.bytes[1];
}

static inline void set_UINT16BE(UINT16BE *word, uint16_t data)
{
	word->bytes[0] = (data >> 8) & 0xff;
	word->bytes[1] = data & 0xff;
}

static inline uint16_t get_UINT16LE(UINT16LE word)
{
	return word.bytes[0] | (word.bytes[1] << 8);
}

static inline void set_UINT16LE(UINT16LE *word, uint16_t data)
{
	word->bytes[0] = data & 0xff;
	word->bytes[1] = (data >> 8) & 0xff;
}

/*
    Convert a C string to a 10-character file name (padded with spaces if necessary)

    dst (O): destination 10-character array
    src (I): source C string
*/
static void str_to_fname(char dst[10], const char *src)
{
	int i;


	i = 0;

	/* copy 10 characters at most */
	if (src)
		while ((i<10) && (src[i]!='\0'))
		{
			dst[i] = src[i];
			i++;
		}

	/* pad with spaces */
	while (i<10)
	{
		dst[i] = ' ';
		i++;
	}
}

/*
    Convert a 10-character file name to a C string (removing trailing spaces if necessary)

    dst (O): destination C string
    src (I): source 10-character array
    n (I): length of dst buffer (string may be truncated if less than 11)
*/
static void fname_to_str(char *dst, const char src[10], int n)
{
	int i;
	int last_nonspace;


	/* copy 10 characters at most */
	if (--n > 10)
		n = 10;

	/* copy filename */
	i = 0;
	last_nonspace = -1;

	while (i<n)
	{
		dst[i] = src[i];
		if (src[i] != ' ')
			last_nonspace = i;
		i++;
	}

	/* terminate with '\0' */
	dst[last_nonspace+1] = '\0';
}

/*
    Check a 10-character file name.

    filename (I): 10-character array with file name

    Return non-zero if the file name is invalid.
*/
static int check_fname(const char filename[10])
{
	int i;
	int space_found_flag;


	/* check and copy file name */
	space_found_flag = false;
	for (i=0; i<10; i++)
	{
		switch (filename[i])
		{
		case '.':
		case '\0':
			/* illegal characters */
			return 1;
		case ' ':
			/* illegal in a file name, but file names shorter than 10
			characters are padded with spaces */
			space_found_flag = true;
			break;
		default:
			/* all other characters are legal (though non-ASCII characters,
			control characters and even lower-case characters are not
			recommended) */
			if (space_found_flag)
				return 1;
			break;
		}
	}

	return 0;
}

/*
    Check a file path.

    fpath (I): C string with file path

    Return non-zero if the file path is invalid.
*/
static int check_fpath(const char *fpath)
{
	const char *element_start, *element_end;
	int element_len;


	/* first check that the path is not too long and that there is no space
	character */
	if ((strlen(fpath) > MAX_PATH_LEN) || strchr(fpath, ' '))
		return 1;

	/* check that each path element has an acceptable length */
	element_start = fpath;
	do
	{
		/* find next path element */
		element_end = strchr(element_start, '.');
		element_len = element_end ? (element_end - element_start) : strlen(element_start);
		if ((element_len > 10) || (element_len == 0))
			return 1;

		/* iterate */
		if (element_end)
			element_start = element_end+1;
		else
			element_start = NULL;
	}
	while (element_start);

	return 0;
}

#if 0
#pragma mark -
#pragma mark LEVEL 1 DISK ROUTINES
#endif

/*
    Level 1 deals with accessing the disk hardware (in our case, the raw disk
    image).

    Higher level routines will only know the disk as a succession of
    256-byte-long physical records addressed by a linear address.
*/

/*
    Disk geometry
*/
struct ti99_geometry
{
	int secspertrack;
	int cylinders;
	int heads;
};

/*
    Physical sector address
*/
struct ti99_sector_address
{
	int sector;
	int cylinder;
	int side;
};

/*
    Time stamp (used in fdr, and WIN VIB/DDR)
*/
struct ti99_date_time
{
	uint8_t time_MSB, time_LSB;/* 0-4: hour, 5-10: minutes, 11-15: seconds/2 */
	uint8_t date_MSB, date_LSB;/* 0-6: year, 7-10: month, 11-15: day */
};

/*
    Subdirectory descriptor (HFDC only)

    The HFDC supports up to 3 subdirectories.
*/
struct dsk_subdir
{
	char name[10];          /* subdirectory name (10 characters, pad with spaces) */
	UINT16BE fdir_aphysrec; /* aphysrec address of fdir record for this subdirectory */
};

/*
    DSK VIB record

    Most fields in this record are only relevant to level 2 routines, but level
    1 routines need the disk geometry information extracted from the VIB.
*/
struct dsk_vib
{
	char name[10];          /* disk volume name (10 characters, pad with spaces) */
	UINT16BE totphysrecs;   /* total number of physrecs on disk (usually 360, */
								/* 720, 640, 1280 or 1440).  (TI originally */
								/* said it should be the total number of AUs, */
								/* but, in practice, DSRs that supports disks */
								/* over 400kbytes (e.g. HFDC) write the total */
								/* number of physrecs.) */
	uint8_t secspertrack;     /* sectors per track (usually 9 (FM SD), */
								/* 16 or 18 (MFM DD), or 36 (MFM HD) */
	uint8_t id[3];            /* 'DSK' */
	uint8_t protection;       /* 'P' if disk is protected, ' ' otherwise. */
	uint8_t cylinders;        /* tracks per side (usually 40) */
	uint8_t heads;            /* sides (1 or 2) */
	uint8_t density;          /* density: 1 (FM SD), 2 (MFM DD), or 3 (MFM HD) */
	dsk_subdir subdir[3];   /* descriptor for up to 3 subdirectories (HFDC only) */
								/* reserved by TI */
	uint8_t abm[200];         /* allocation bitmap: there is one bit per AU. */
								/* A binary 1 in a bit position indicates that */
								/* the allocation unit associated with that */
								/* bit has been allocated. */
								/* Bits corresponding to system reserved AUs, */
								/* non-existent AUs, and bad AUs, are set to one, too. */
								/* (AU 0 is associated to LSBit of byte 0, */
								/* AU 7 to MSBit of byte 0, AU 8 to LSBit */
								/* of byte 1, etc.) */
};

enum ti99_img_format
{
	if_mess,
	if_v9t9,
	if_pc99_fm,
	if_pc99_mfm,
	if_harddisk
};

/*
    level-1 disk image descriptor
*/
struct ti99_lvl1_imgref
{
	ti99_img_format img_format; /* tells the image format */
	imgtool::stream *file_handle;        /* imgtool file handle */
	struct mess_hard_disk_file harddisk_handle;     /* MAME harddisk handle (harddisk format) */
	ti99_geometry geometry;     /* geometry */
	unsigned pc99_track_len;        /* unformatted track length (pc99 format) */
	uint32_t *pc99_data_offset_array; /* offset for each sector (pc99 format) */
};

/*
    calculate CRC for data address marks or sector data

    crc (I/O): current CRC value to be updated (initialize to 0xffff before
        calling this function for the first time)
    value: new byte of data to update the CRC with
*/
static void calc_crc(uint16_t *crc, uint8_t value)
{
	uint8_t l, h;

	l = value ^ (*crc >> 8);
	*crc = (*crc & 0xff) | (l << 8);
	l >>= 4;
	l ^= (*crc >> 8);
	*crc <<= 8;
	*crc = (*crc & 0xff00) | l;
	l = (l << 4) | (l >> 4);
	h = l;
	l = (l << 2) | (l >> 6);
	l &= 0x1f;
	*crc = *crc ^ (l << 8);
	l = h & 0xf0;
	*crc = *crc ^ (l << 8);
	l = (h << 1) | (h >> 7);
	l &= 0xe0;
	*crc = *crc ^ l;
}

/*
    Parse a PC99 disk image

    file_handle (I/O): imgtool file handle
    fm_format (I): if true, the image is in FM format, otherwise it is in MFM
        format
    pass (I): 0 for first pass, 1 for second pass
    vib (O): buffer where the vib should be stored (first pass)
    geometry (O): disk image geometry (second pass)
    data_offset_array (O): array of data offset to generate (second pass)
    out_track_len (O): track length is returned there

    Return imgtool error code
*/
#define MAX_TRACK_LEN 6872
#define DATA_OFFSET_NONE 0xffffffff
static int parse_pc99_image(imgtool::stream &file_handle, int fm_format, int pass, dsk_vib *vib, const ti99_geometry *geometry, uint32_t *data_offset_array, unsigned *out_track_len)
{
	int track_len, num_tracks;  /* length of a track in bytes, and number of tracks */
	int phys_track;
	int expected_cylinder, expected_head;
	int track_start_pos, track_pos;
	uint8_t c;
	uint8_t cylinder, head, sector;
	int seclen;
	uint8_t crc1, crc2;
	uint16_t crc;
	long data_offset;
	uint8_t track_buf[MAX_TRACK_LEN];
	int i;

	if (fm_format)
		track_len = 3253;
	else
		track_len = 6872;

	if (out_track_len)
		*out_track_len = track_len;

	if (file_handle.size() % track_len)
		return IMGTOOLERR_CORRUPTIMAGE;

	num_tracks = file_handle.size() / track_len;
	if (num_tracks <= 0)
		return IMGTOOLERR_CORRUPTIMAGE;

	/* we only support 40-track-per-side images */
	if ((num_tracks != 40) && (num_tracks != 80))
		return IMGTOOLERR_UNIMPLEMENTED;

	if (pass == 1)
	{
		/* initialize offset map */
		for (head = 0; head < geometry->heads; head++)
			for (cylinder = 0; cylinder < geometry->cylinders; cylinder++)
				for (sector = 0; sector < geometry->secspertrack; sector++)
					data_offset_array[(head*geometry->cylinders + cylinder)*geometry->secspertrack + sector] = DATA_OFFSET_NONE;
	}
	/* rewind to start of file */
	file_handle.seek(0, SEEK_SET);

	/* pass 0 only looks for vib in track 0; pass 1 scans every track */
	for (phys_track=0; phys_track < ((pass == 1) ? num_tracks : 1); phys_track++)
	{
		if (file_handle.read(track_buf, track_len) != track_len)
			return IMGTOOLERR_READERROR;

		/* we only support 40-track-per-side images */
		expected_cylinder = phys_track % 40;
		expected_head = phys_track / 40;

		track_start_pos = 0;

		while (track_start_pos < track_len)
		{
			if (fm_format)
			{
				do
				{
					c = track_buf[track_start_pos];
					track_start_pos++;
				} while ((c != 0xfe) && (track_start_pos < track_len));

				if (c != 0xfe)
					break;

				track_pos = track_start_pos;

				crc = 0xffff;
				calc_crc(& crc, c);
			}
			else
			{
				do
				{
					c = track_buf[track_start_pos];
					track_start_pos++;
				} while ((c != 0xa1) && (track_start_pos < track_len));

				if (c != 0xa1)
					break;

				track_pos = track_start_pos;

				c = track_buf[track_pos];
				track_pos++;
				if (track_pos == track_len)
					track_pos = 0;

				if (c != 0xa1)
					continue;

				c = track_buf[track_pos];
				track_pos++;
				if (track_pos == track_len)
					track_pos = 0;

				if (c != 0xa1)
					continue;

				crc = 0xffff;
				calc_crc(& crc, c);

				c = track_buf[track_pos];
				track_pos++;
				if (track_pos == track_len)
					track_pos = 0;

				if (c != 0xfe)
					continue;
			}

			c = track_buf[track_pos];
			track_pos++;
			if (track_pos == track_len)
				track_pos = 0;

			cylinder = c;
			calc_crc(& crc, c);

			c = track_buf[track_pos];
			track_pos++;
			if (track_pos == track_len)
				track_pos = 0;

			head = c;
			calc_crc(& crc, c);

			c = track_buf[track_pos];
			track_pos++;
			if (track_pos == track_len)
				track_pos = 0;

			sector = c;
			calc_crc(& crc, c);

			c = track_buf[track_pos];
			track_pos++;
			if (track_pos == track_len)
				track_pos = 0;

			seclen = 128 << c;
			calc_crc(& crc, c);

			c = track_buf[track_pos];
			track_pos++;
			if (track_pos == track_len)
				track_pos = 0;

			crc1 = c;
			calc_crc(& crc, c);

			c = track_buf[track_pos];
			track_pos++;
			if (track_pos == track_len)
				track_pos = 0;

			crc2 = c;
			calc_crc(& crc, c);

#if 0
			/* CRC seems to be completely hosed */
			if (crc)
				printf("aargh!");
#endif
			if ((seclen != 256) || (crc1 != 0xf7) || (crc2 != 0xf7)
					|| (cylinder != expected_cylinder) || (head != expected_head)
					|| ((pass == 1) && ((cylinder >= geometry->cylinders)
										|| (head >= geometry->heads)
										|| (sector >= geometry->secspertrack))))
				continue;

			c = track_buf[track_pos];
			track_pos++;
			if (track_pos == track_len)
				track_pos = 0;

			while (c == (fm_format ? 0xff : 0x4e))
			{
				c = track_buf[track_pos];
				track_pos++;
				if (track_pos == track_len)
					track_pos = 0;
			}

			while (c == 0x00)
			{
				c = track_buf[track_pos];
				track_pos++;
				if (track_pos == track_len)
					track_pos = 0;
			}

			if (fm_format)
			{
				if (c != 0xfb)
					continue;

				crc = 0xffff;
				calc_crc(& crc, c);
			}
			else
			{
				if (c != 0xa1)
					continue;

				c = track_buf[track_pos];
				track_pos++;
				if (track_pos == track_len)
					track_pos = 0;

				if (c != 0xa1)
					continue;

				c = track_buf[track_pos];
				track_pos++;
				if (track_pos == track_len)
					track_pos = 0;

				if (c != 0xa1)
					continue;

				crc = 0xffff;
				calc_crc(& crc, c);

				c = track_buf[track_pos];
				track_pos++;
				if (track_pos == track_len)
					track_pos = 0;

				if (c != 0xfb)
					continue;
			}
			data_offset = track_pos;
			for (i=0; i<seclen; i++)
			{
				c = track_buf[track_pos];
				track_pos++;
				if (track_pos == track_len)
					track_pos = 0;

				calc_crc(& crc, c);
			}

			c = track_buf[track_pos];
			track_pos++;
			if (track_pos == track_len)
				track_pos = 0;

			crc1 = c;
			calc_crc(& crc, c);

			c = track_buf[track_pos];
			track_pos++;
			if (track_pos == track_len)
				track_pos = 0;

			crc2 = c;
			calc_crc(& crc, c);

#if 0
			/* CRC seems to be completely hosed */
			if (crc)
				printf("aargh!");
#endif
			if ((crc1 != 0xf7) || (crc2 != 0xf7))
				continue;

			switch (pass)
			{
			case 0:
				if ((cylinder == 0) && (head == 0) && (sector == 0))
				{
					/* return vib */
					if ((data_offset + 256) <= track_len)
						memcpy(vib, track_buf + data_offset, 256);
					else
					{
						memcpy((uint8_t *)vib, track_buf + data_offset, track_len-data_offset);
						memcpy((uint8_t *)vib + (track_len-data_offset), track_buf, 256-(track_len-data_offset));
					}
					return 0;
				}
				break;

			case 1:
				/* set up offset map */
				if (data_offset_array[(head*geometry->cylinders + cylinder)*geometry->secspertrack + sector] != DATA_OFFSET_NONE)
					/* error: duplicate sector */
					return IMGTOOLERR_CORRUPTIMAGE;
				data_offset_array[(head*geometry->cylinders + cylinder)*geometry->secspertrack + sector] = data_offset;
				break;
			}
		}
	}

	if (pass == 0)
		return IMGTOOLERR_CORRUPTIMAGE;

	if (pass == 1)
	{
		/* check offset map */
		for (head = 0; head < geometry->heads; head++)
			for (cylinder = 0; cylinder < geometry->cylinders; cylinder++)
				for (sector = 0; sector < geometry->secspertrack; sector++)
					if (data_offset_array[(head*geometry->cylinders + cylinder)*geometry->secspertrack + sector] == DATA_OFFSET_NONE)
						/* error: missing sector */
						return IMGTOOLERR_CORRUPTIMAGE;
	}

	return 0;
}


/*
    Read the volume information block (aphysrec 0) assuming no geometry
    information.  (Called when an image is opened to figure out the
    geometry information.)

    file_handle (I/O): imgtool file handle
    img_format (I): image format (MESS, V9T9 or PC99)
    dest (O): pointer to 256-byte destination buffer

    Return imgtool error code
*/
static int read_image_vib_no_geometry(imgtool::stream &file_handle, ti99_img_format img_format, dsk_vib *dest)
{
	int reply;

	switch (img_format)
	{
	case if_mess:
	case if_v9t9:
		/* seek to sector */
		reply = file_handle.seek(0, SEEK_SET);
		if (reply)
			return IMGTOOLERR_READERROR;
		/* read it */
		reply = file_handle.read(dest, 256);
		if (reply != 256)
			return IMGTOOLERR_READERROR;
		return 0;

	case if_pc99_fm:
	case if_pc99_mfm:
		return parse_pc99_image(file_handle, img_format == if_pc99_fm, 0, dest, NULL, NULL, NULL);

	case if_harddisk:
		/* not implemented, because we don't need it */
		break;
	}

	return IMGTOOLERR_UNIMPLEMENTED;
}

/*
    Open a disk image at level 1

    file_handle (I/O): imgtool file handle
    img_format (I): image format (MESS, V9T9, PC99, or MAME harddisk)
    l1_img (O): level-1 image handle
    vib (O): buffer where the vib should be stored (floppy images only)

    Return imgtool error code
*/
static imgtoolerr_t open_image_lvl1(imgtool::stream::ptr &&file_handle, ti99_img_format img_format, ti99_lvl1_imgref *l1_img, dsk_vib *vib)
{
	imgtoolerr_t err;
	int reply;
	uint16_t totphysrecs;

	l1_img->img_format = img_format;

	if (img_format == if_harddisk)
	{
		err = imghd_open(*file_handle, &l1_img->harddisk_handle);
		if (err)
			return err;

		const auto &info = imghd_get_header(&l1_img->harddisk_handle);
		l1_img->geometry.cylinders = info.cylinders;
		l1_img->geometry.heads = info.heads;
		l1_img->geometry.secspertrack = info.sectors;
		if (info.sectorbytes != 256)
		{
			imghd_close(&l1_img->harddisk_handle);
			return IMGTOOLERR_CORRUPTIMAGE; /* TODO: support 512-byte sectors */
		}

#if 0
		/* read vib */
		reply = read_absolute_physrec(l1_img, 0, vib);
		if (reply)
			return reply;
#endif
	}
	else
	{
		/* read vib */
		reply = read_image_vib_no_geometry(*file_handle, img_format, vib);
		if (reply)
			return (imgtoolerr_t)reply;

		/* extract geometry information */
		totphysrecs = get_UINT16BE(vib->totphysrecs);

		l1_img->geometry.secspertrack = vib->secspertrack;
		if (l1_img->geometry.secspertrack == 0)
			/* Some images might be like this, because the original SSSD TI
			controller always assumes 9. */
			l1_img->geometry.secspertrack = 9;
		l1_img->geometry.cylinders = vib->cylinders;
		if (l1_img->geometry.cylinders == 0)
			/* Some images are like this, because the original SSSD TI
			controller always assumes 40. */
			l1_img->geometry.cylinders = 40;
		l1_img->geometry.heads = vib->heads;
		if (l1_img->geometry.heads == 0)
			/* Some images are like this, because the original SSSD TI
			controller always assumes that tracks beyond 40 are on side 2. */
			l1_img->geometry.heads = totphysrecs / (l1_img->geometry.secspertrack * l1_img->geometry.cylinders);

		/* check information */
		if ((totphysrecs != (l1_img->geometry.secspertrack * l1_img->geometry.cylinders * l1_img->geometry.heads))
				|| (totphysrecs < 2)
				|| memcmp(vib->id, "DSK", 3) || (! strchr(" P", vib->protection))
				|| (((img_format == if_mess) || (img_format == if_v9t9))
					&& (file_handle->size() != totphysrecs*256U)))
			return (imgtoolerr_t)IMGTOOLERR_CORRUPTIMAGE;

		if ((img_format == if_pc99_fm) || (img_format == if_pc99_mfm))
		{
			l1_img->pc99_data_offset_array = (uint32_t*)malloc(sizeof(*l1_img->pc99_data_offset_array)*totphysrecs);
			if (! l1_img->pc99_data_offset_array)
				return IMGTOOLERR_OUTOFMEMORY;
			reply = parse_pc99_image(*file_handle, img_format == if_pc99_fm, 1, NULL, & l1_img->geometry, l1_img->pc99_data_offset_array, &l1_img->pc99_track_len);
			if (reply)
			{
				free(l1_img->pc99_data_offset_array);
				return (imgtoolerr_t)reply;
			}
		}
	}

	l1_img->file_handle = file_handle.release();    // we can only do this when we're sure we're successful

	return (imgtoolerr_t)0;
}

/*
    Close a disk image at level 1

    l1_img (I/O): level-1 image handle

    Return imgtool error code
*/
static void close_image_lvl1(ti99_lvl1_imgref *l1_img)
{
	if (l1_img->img_format == if_harddisk)
	{
		imghd_close(&l1_img->harddisk_handle);
	}

	delete l1_img->file_handle;

	if ((l1_img->img_format == if_pc99_fm) || (l1_img->img_format == if_pc99_mfm))
		free(l1_img->pc99_data_offset_array);
}

/*
    Convert physical sector address to offset in disk image (old MESS and V9T9
    formats only)

    l1_img (I/O): level-1 image handle
    address (I): physical sector address

    Return offset in image
*/
static inline int sector_address_to_image_offset(const ti99_lvl1_imgref *l1_img, const ti99_sector_address *address)
{
	int offset = 0;

	switch (l1_img->img_format)
	{
	case if_mess:
		/* old MESS format */
		offset = (((address->cylinder*l1_img->geometry.heads) + address->side)*l1_img->geometry.secspertrack + address->sector)*256;
		break;

	case if_v9t9:
		/* V9T9 format */
		if (address->side & 1)
			/* on side 1, tracks are stored in the reverse order */
			offset = (((address->side*l1_img->geometry.cylinders) + (l1_img->geometry.cylinders-1 - address->cylinder))*l1_img->geometry.secspertrack + address->sector)*256;
		else
			offset = (((address->side*l1_img->geometry.cylinders) + address->cylinder)*l1_img->geometry.secspertrack + address->sector)*256;
		break;

	case if_pc99_fm:
	case if_pc99_mfm:
		/* pc99 format */
	case if_harddisk:
		/* harddisk format */
		assert(1);      /* not implemented */
		break;
	}

	return offset;
}

/*
    Read one 256-byte sector from a disk image

    l1_img (I/O): level-1 image handle
    address (I): physical sector address
    dest (O): pointer to 256-byte destination buffer

    Return non-zero on error
*/
static int read_sector(ti99_lvl1_imgref *l1_img, const ti99_sector_address *address, void *dest)
{
	int reply;
	uint32_t track_len, track_offset, sector_offset;

	switch (l1_img->img_format)
	{
	case if_mess:
		/* old MESS format */
	case if_v9t9:
		/* V9T9 format */
		/* seek to sector */
		reply = l1_img->file_handle->seek(sector_address_to_image_offset(l1_img, address), SEEK_SET);
		if (reply)
			return 1;
		/* read it */
		reply = l1_img->file_handle->read(dest, 256);
		if (reply != 256)
			return 1;
		break;

	case if_pc99_fm:
	case if_pc99_mfm:
		/* pc99 format */
		track_len = l1_img->pc99_track_len;
		track_offset = (address->side*l1_img->geometry.cylinders + address->cylinder)*track_len;
		sector_offset = l1_img->pc99_data_offset_array[(address->side*l1_img->geometry.cylinders + address->cylinder)*l1_img->geometry.secspertrack + address->sector];

		if ((sector_offset + 256) <= track_len)
		{
			/* seek to sector */
			reply = l1_img->file_handle->seek(track_offset+sector_offset, SEEK_SET);
			if (reply)
				return 1;
			/* read it */
			reply = l1_img->file_handle->read(dest, 256);
			if (reply != 256)
				return 1;
		}
		else
		{
			/* seek to sector */
			reply = l1_img->file_handle->seek(track_offset+sector_offset, SEEK_SET);
			if (reply)
				return 1;
			/* read first chunk (until end of track) */
			reply = l1_img->file_handle->read((uint8_t *)dest, track_len-sector_offset);
			if (reply != track_len-sector_offset)
				return 1;

			/* wrap to start of track */
			reply = l1_img->file_handle->seek(track_offset, SEEK_SET);
			if (reply)
				return 1;
			/* read remnant of sector */
			reply = l1_img->file_handle->read((uint8_t *)dest + (track_len-sector_offset), 256-(track_len-sector_offset));
			if (reply != 256-(track_len-sector_offset))
				return 1;
		}
		break;

	case if_harddisk:
		/* not implemented */
		assert(1);
		/*return imghd_read(l1_img->harddisk_handle, ((address->cylinder*l1_img->geometry.heads) + address->side)*l1_img->geometry.secspertrack + address->sector, 1, dest) != 1;*/
		break;
	}

	return 0;
}

/*
    Write one 256-byte sector to a disk image

    l1_img (I/O): level-1 image handle
    address (I): physical sector address
    src (I): pointer to 256-byte source buffer

    Return non-zero on error
*/
static int write_sector(ti99_lvl1_imgref *l1_img, const ti99_sector_address *address, const void *src)
{
	int reply;
	uint32_t track_len, track_offset, sector_offset;

	switch (l1_img->img_format)
	{
	case if_mess:
		/* old MESS format */
	case if_v9t9:
		/* V9T9 format */
		/* seek to sector */
		reply = l1_img->file_handle->seek(sector_address_to_image_offset(l1_img, address), SEEK_SET);
		if (reply)
			return 1;
		/* write it */
		reply = l1_img->file_handle->write(src, 256);
		if (reply != 256)
			return 1;
		break;

	case if_pc99_fm:
	case if_pc99_mfm:
		/* pc99 format */
		track_len = l1_img->pc99_track_len;
		track_offset = (address->side*l1_img->geometry.cylinders + address->cylinder)*track_len;
		sector_offset = l1_img->pc99_data_offset_array[(address->side*l1_img->geometry.cylinders + address->cylinder)*l1_img->geometry.secspertrack + address->sector];

		if ((sector_offset + 256) <= track_len)
		{
			/* seek to sector */
			reply = l1_img->file_handle->seek(track_offset+sector_offset, SEEK_SET);
			if (reply)
				return 1;
			/* write it */
			reply = l1_img->file_handle->write(src, 256);
			if (reply != 256)
				return 1;
		}
		else
		{
			/* seek to sector */
			reply = l1_img->file_handle->seek(track_offset+sector_offset, SEEK_SET);
			if (reply)
				return 1;
			/* write first chunk (until end of track) */
			reply = l1_img->file_handle->write((uint8_t *)src, track_len-sector_offset);
			if (reply != track_len-sector_offset)
				return 1;

			/* wrap to start of track */
			reply = l1_img->file_handle->seek(track_offset, SEEK_SET);
			if (reply)
				return 1;
			/* write remnant of sector */
			reply = l1_img->file_handle->write((uint8_t *)src + (track_len-sector_offset), 256-(track_len-sector_offset));
			if (reply != 256-(track_len-sector_offset))
				return 1;
		}
		break;

	case if_harddisk:
		/* not implemented */
		assert(1);
		/*return imghd_write(l1_img->harddisk_handle, ((address->cylinder*l1_img->geometry.heads) + address->side)*l1_img->geometry.secspertrack + address->sector, 1, src) != 1;*/
		break;
	}

	return 0;
}

/*
    Convert physical record address to sector address (DSK format)

    aphysrec (I): absolute physrec address
    geometry (I): disk image geometry
    address (O): physical sector address
*/
static void dsk_aphysrec_to_sector_address(int aphysrec, const ti99_geometry *geometry, ti99_sector_address *address)
{
	address->sector = aphysrec % geometry->secspertrack;
	aphysrec /= geometry->secspertrack;
	address->cylinder = aphysrec % geometry->cylinders;
	address->side = aphysrec / geometry->cylinders;
	if (address->side & 1)
		/* on side 1, tracks are stored in the reverse order */
		address->cylinder = geometry->cylinders-1 - address->cylinder;
}

/*
    Convert physical record address to sector address (WIN format for HFDC)

    Note that physical address translation makes sense for HFDC, but not SCSI.

    aphysrec (I): absolute physrec address
    geometry (I): disk image geometry
    address (O): physical sector address
*/
[[maybe_unused]] static void win_aphysrec_to_sector_address(int aphysrec, const ti99_geometry &geometry, ti99_sector_address &address)
{
	address.sector = aphysrec % geometry.secspertrack;
	aphysrec /= geometry.secspertrack;
	address.side = aphysrec % geometry.heads;
	address.cylinder = aphysrec / geometry.heads;
}

/*
    Read one 256-byte physical record from a disk image

    l1_img (I/O): level-1 image handle
    aphysrec (I): absolute physrec address
    dest (O): pointer to 256-byte destination buffer

    Return non-zero on error
*/
static int read_absolute_physrec(ti99_lvl1_imgref *l1_img, unsigned aphysrec, void *dest)
{
	ti99_sector_address address;


	if (l1_img->img_format == if_harddisk)
	{
#if 0
		win_aphysrec_to_sector_address(aphysrec, l1_img->geometry, address);
		return read_sector(l1_img, & address, dest);
#endif

		return imghd_read(&l1_img->harddisk_handle, aphysrec, dest) != IMGTOOLERR_SUCCESS;
	}
	else
	{
		dsk_aphysrec_to_sector_address(aphysrec, & l1_img->geometry, & address);

		return read_sector(l1_img, & address, dest);
	}
}

/*
    Write one 256-byte physical record to a disk image

    l1_img (I/O): level-1 image handle
    aphysrec (I): absolute physrec address
    src (I): pointer to 256-byte source buffer

    Return non-zero on error
*/
static int write_absolute_physrec(ti99_lvl1_imgref *l1_img, unsigned aphysrec, const void *src)
{
	ti99_sector_address address;


	if (l1_img->img_format == if_harddisk)
	{
#if 0
		win_aphysrec_to_sector_address(aphysrec, & l1_img->geometry, & address);
		return write_sector(l1_img, & address, dest);
#endif

		return imghd_write(&l1_img->harddisk_handle, aphysrec, src) != IMGTOOLERR_SUCCESS;
	}
	else
	{
		dsk_aphysrec_to_sector_address(aphysrec, & l1_img->geometry, & address);

		return write_sector(l1_img, & address, src);
	}
}

#if 0
#pragma mark -
#pragma mark LEVEL 2 DISK ROUTINES
#endif

/*
    Level 2 implements files as a succession of 256-byte-long physical records.

    Level 2 implements allocation bitmap (and AU), disk catalog, etc.
*/

/*
    WIN VIB/DDR record
*/
struct win_vib_ddr
{
	char name[10];          /* disk volume name (10 characters, pad with spaces) */
	UINT16BE totAUs;        /* total number of AUs */
	uint8_t secspertrack;     /* HFDC: sectors per track (typically 32) */
							/* SCSI: reserved */
	union
	{
		struct
		{
			uint8_t id[3];    /* V1 VIB: 'WIN' */
		} vib_v1;

		struct              /* V2 VIB: extra params */
		{
			uint8_t res_AUs;  /* # AUs reserved for vib, bitmap, ddr, fdir and fdr, divided by 64 */
			uint8_t step_spd; /* HFDC: step speed (0-7) */
							/* SCSI: reserved */
			uint8_t red_w_cur;/* HFDC: reduced write current cylinder, divided by 8 */
							/* SCSI: reserved */
		} vib_v2;

		struct
		{
			uint8_t id[3];    /* DDR: 'DIR' */
		} ddr;
	} u;
	UINT16BE params;        /* bits 0-3: sectors/AU - 1 */
							/* HFDC: */
								/* bits 4-7: # heads - 1 */
								/* bit 8: V1: buffered head stepping flag */
								/*        V2: reserved */
								/* bit 9-15: write precompensation track, divided by 16 */
							/* SCSI: */
								/* bits 4-15: reserved */
	ti99_date_time creation;/* date and time of creation */
	uint8_t num_files;        /* number of files in directory */
	uint8_t num_subdirs;      /* number of subdirectories in directory */
	UINT16BE fdir_AU;       /* points to root directory fdir */
	union
	{
		struct
		{
			UINT16BE dsk1_AU;   /* HFDC: points to current dsk1 emulation image (0 if none) */
								/* SCSI: reserved */
		} vib;

		struct
		{
			UINT16BE parent_ddr_AU; /* points to parent directory DDR */
		} ddr;
	} u2;
	UINT16BE subdir_AU[114];/* points to all subdirectory DDRs */
};

/*
    AU format
*/
struct ti99_AUformat
{
	int totAUs;             /* total number of AUs */
	int physrecsperAU;      /* number of 256-byte physical records per AU */
};

/*
    DSK directory reference: 0 for root, 1 for 1st subdir, 2 for 2nd subdir, 3
    for 3rd subdir
*/
/*typedef int dir_ref;*/

/*
    catalog entry (used for in-memory catalog)
*/
struct dir_entry
{
	uint16_t dir_ptr;         /* DSK: unused */
							/* WIN: AU address of the DDR for this directory */
	char name[10];          /* name of this directory (copied from the VIB for DSK, DDR for WIN) */
};

struct file_entry
{
	uint16_t fdr_ptr;         /* DSK: aphysrec address of the FDR for this file */
							/* WIN: AU address of the FDR for this file */
	char name[10];          /* name of this file (copied from FDR) */
};

struct ti99_catalog
{
	int num_subdirs;        /* number of subdirectories */
	int num_files;          /* number of files */
	dir_entry subdirs[114]; /* description of each subdir */
	file_entry files[128];  /* description of each file */
};

/*
    level-2 disk image descriptor
*/
struct ti99_lvl2_imgref_dsk
{
	uint16_t totphysrecs;             /* total number of aphysrecs (extracted from vib record in aphysrec 0) */
	ti99_catalog catalogs[4];       /* catalog of root directory and up to 3 subdirectories */
	uint16_t fdir_aphysrec[4];        /* fdir aphysrec address for root directory
	                                    and up to 3 subdirectories */
};

enum win_vib_t
{
	win_vib_v1,
	win_vib_v2
};
struct ti99_lvl2_imgref_win
{
	win_vib_t vib_version;          /* version of the vib record in aphysrec 0 (see win_vib_ddr) */
};

enum l2i_t
{
	L2I_DSK,
	L2I_WIN
};

struct ti99_lvl2_imgref
{
	ti99_lvl1_imgref l1_img;/* image format, imgtool image handle, image geometry */
	ti99_AUformat AUformat; /* AU format */
	int data_offset;        /* In order to reduce seek times when searching the
	                            disk for a given file name, fdr (and ddr, and
	                            fdir) records are preferentially allocated in
	                            AUs n to data_offset, whereas data records are
	                            preferentially allocated in AUs starting at
	                            data_offset. */
							/* With the DSK disk structure, n is always 2 (if 1
							    physrec per AU) or 1 (if 2 physrecs per AU or
							    more), and data_offset is arbitrarily chosen as
							    34. */
							/* With the WIN disk structure, n depends on the
							    size of the volume bitmap, which itself depends
							    on the number of AUs on disk (we always have n
							    <= 33), and data_offset is read from the vib
							    record (except with the obsolete v1 VIB, where
							    we use a default value of 64). */
	char vol_name[10];      /* cached volume name (extracted from vib record in aphysrec 0) */

	uint8_t abm[8192];        /* allocation bitmap */

	l2i_t type;                 /* structure format */

	union
	{
		ti99_lvl2_imgref_dsk dsk;
		ti99_lvl2_imgref_win win;
	};                  /* structure-specific info */
};

/*
    file flags found in fdr (and tifiles)
*/
enum
{
	fdr99_f_program = 0x01, /* set for program files */
	fdr99_f_int     = 0x02, /* set for binary files */
	fdr99_f_wp      = 0x08, /* set if file is write-protected */
	/*fdr99_f_backup    = 0x10,*/   /* set if file has been modified since last backup */
	/*fdr99_f_dskimg    = 0x20,*/   /* set if file is a DSK image (HFDC HD only) */
	fdr99_f_var     = 0x80  /* set if file uses variable-length records*/
};

/*
    DSK FDR record
*/
struct dsk_fdr
{
	char name[10];          /* file name (10 characters, pad with spaces) */
	UINT16BE xreclen;       /* extended record len: if record len is >= 256, */
								/* reclen is set to 0 and the actual reclen is */
								/* stored here (Myarc HFDC only).  TI reserved */
								/* this field for data chain pointer extension, */
								/* but this was never implemented. */
	uint8_t flags;            /* file status flags (see enum above) */
	uint8_t recsperphysrec;   /* logical records per physrec */
								/* ignored for variable length record files and */
								/* program files */
	UINT16BE fphysrecs;     /* file length in physrecs */
								/* Note that the HFDC defines this field as the */
								/* number of allocated physrecs in the cluster */
								/* chain (i.e. rounded on the next AU */
								/* boundary), so level-3 routines should use */
								/* the fixrecs field instead to determine the */
								/* logical length of field.  IIRC, the HFDC */
								/* implementation is regarded as a bug because */
								/* program files do not define the fixrecs field */
								/* field, so program field saved by the HFDC */
								/* DSR may be larger than they should. */
	uint8_t eof;              /* EOF offset in last physrec for variable length */
								/* record files and program files (0->256) */
	uint8_t reclen;           /* logical record size in bytes ([1,255] 0->256) */
								/* Maximum allowable record size for variable */
								/* length record files.  Reserved for program */
								/* files (set to 0).  Set to 0 if reclen >=256 */
								/* (HFDC only). */
	UINT16LE fixrecs;       /* file length in logical records */
								/* For variable length record files, number of */
								/* 256-byte records actually used. */
	ti99_date_time creation;/* date and time of creation (HFDC and BwG only; */
								/* reserved in TI) */
	ti99_date_time update;  /* date and time of last write to file (HFDC and */
								/* BwG only; reserved in TI) */
	uint8_t clusters[76][3];  /* data cluster table: 0 through 76 entries (3 */
								/* bytes each), one entry for each file cluster. */
								/* 12 bits: address of first AU of cluster */
								/* 12 bits: offset of last 256-byte record in cluster */
};

/*
    WIN FDR record
*/
struct win_fdr
{
	char name[10];          /* file name (10 characters, pad with spaces) */
	UINT16BE xreclen;       /* extended record len: if record len is >= 256, */
								/* reclen is set to 0 and the actual reclen is */
								/* stored here (Myarc HFDC only).  TI reserved */
								/* this  field for data chain pointer extension, */
								/* but this was never implemented. */
	uint8_t flags;            /* file status flags (see enum above) */
	uint8_t recsperphysrec;   /* logical records per physrec */
								/* ignored for variable length record files and */
								/* program files */
	UINT16BE fphysrecs_LSW; /* eldest FDR: file length in physrecs */
								/* Note that the HFDC defines this field as the */
								/* number of allocated physrecs in the cluster */
								/* chain (i.e. rounded on the next AU */
								/* boundary), so level-3 routines should use */
								/* the fixrecs field instead to determine the */
								/* logical length of field.  IIRC, the HFDC */
								/* implementation is regarded as a bug because */
								/* program files do not define the fixrecs field */
								/* field, so program field saved by the HFDC */
								/* DSR may be larger than they should. */
							/* other sibling FDRs: index of the first file */
								/* physrec in this particular sibling FDR */
	uint8_t eof;              /* EOF offset in last physrec for variable length */
								/* record files and program files (0->256)*/
	uint8_t reclen;           /* logical record size in bytes ([1,255]) */
								/* Maximum allowable record size for variable */
								/* length record files.  Reserved for program */
								/* files (set to 0).  Set to 0 if reclen >=256 */
								/* (HFDC only). */
	UINT16LE fixrecs_LSW;   /* file length in logical records */
								/* For variable length record files, number of */
								/* 256-byte records actually used. */
	ti99_date_time creation;/* date and time of creation */
	ti99_date_time update;  /* date and time of last write to file */

	char id[2];             /* 'FI' */
	UINT16BE prevsibFDR_AU; /* address of the AU where previous sibling FDR is */
								/* (see also xinfo_LSB) */
	UINT16BE nextsibFDR_AU; /* address of the AU where next sibling FDR is */
								/* (see also xinfo_LSB) */
	UINT16BE sibFDR_AUlen;  /* total number of data AUs allocated in this particular sibling FDR */
	UINT16BE parent_FDIR_AU;/* FDIR the file is listed in */
	uint8_t xinfo_MSB;        /* extended information (MSByte) */
								/* bits 0-3: MSN of fphysrecs */
								/* bits 4-7: MSN of fixrecs */
	uint8_t xinfo_LSB;        /* extended information (LSByte) */
								/* bits 8-11: physrec offset within AU for */
									/* previous sibling FDR (see prevsibFDR_AU) */
								/* bits 12-15: physrec offset within AU for */
									/* next sibling FDR (see nextsibFDR_AU) */
	UINT16BE clusters[54][2];/* data cluster table: 0 through 54 entries (4 */
								/* bytes each), one entry for each file cluster. */
								/* 16 bits: address of first AU of cluster */
								/* 16 bits: address of last AU of cluster */
};

/*
    tifile header: stand-alone file
*/
struct tifile_header
{
	char tifiles[8];        /* always '\7TIFILES' */
	UINT16BE fphysrecs;     /* file length in physrecs */
	uint8_t flags;            /* see enum above */
	uint8_t recsperphysrec;   /* records per physrec */
	uint8_t eof;              /* current position of eof in last physrec (0->255)*/
	uint8_t reclen;           /* bytes per record ([1,255] 0->256) */
	UINT16BE fixrecs;       /* file length in records */
	uint8_t res[128-16];      /* reserved */
								/* * variant a: */
									/* 112 chars: 0xCA53 repeated 56 times */
								/* * variant b: */
									/* 4 chars: unknown */
									/* 108 chars: 0xCA53 repeated 54 times */
								/* * variant c: */
									/* 10 chars: original TI file name filed with spaces */
									/* 102 chars: spaces */
								/* * variant d: */
									/* 10 chars: original TI file name filed with spaces */
									/* 2 chars: CR+LF */
									/* 98 chars: spaces */
									/* 2 chars: CR+LF */
								/* * variant e: */
									/* 10 chars: original TI file name */
									/* 4 bytes: unknown */
									/* 4 bytes: time & date of creation */
									/* 4 bytes: time & date of last update */
									/* 90 chars: spaces */
								/* * variant f: */
									/* 6 bytes: 'MYTERM' */
									/* 4 bytes: time & date of creation */
									/* 4 bytes: time & date of last update */
									/* 2 bytes: unknown (always >0000) */
									/* 96 chars: 0xCA53 repeated 56 times */
};

/*
    level-2 file descriptor
*/
struct ti99_lvl2_fileref_dsk
{
	struct ti99_lvl2_imgref *l2_img;
	int fdr_aphysrec;
	dsk_fdr fdr;
};

struct ti99_lvl2_fileref_win
{
	struct ti99_lvl2_imgref *l2_img;
	unsigned fphysrecs;             /* copy of field in the eldest FDR */
	unsigned eldestfdr_aphysrec;    /* aphysrec address of the eldest FDR */
	unsigned curfdr_aphysrec;       /* aphysrec address of the currently open sibling FDR */
	win_fdr curfdr;                 /* buffer with currently open sibling FDR */
};

struct ti99_lvl2_fileref_tifiles
{
	imgtool::stream *file_handle;
	tifile_header hdr;
};

enum l2f_type_t
{
	L2F_DSK,
	L2F_WIN,
	L2F_TIFILES
};

struct ti99_lvl2_fileref
{
	l2f_type_t type;
	union
	{
		ti99_lvl2_fileref_dsk dsk;
		ti99_lvl2_fileref_win win;
		ti99_lvl2_fileref_tifiles tifiles;
	};
};

static struct ti99_lvl2_imgref *get_lvl2_imgref(imgtool::image &image)
{
	return (struct ti99_lvl2_imgref *) image.extra_bytes();
}

/*
    Compare two (possibly empty) catalog entry for qsort
*/
static int cat_file_compare_qsort(const void *p1, const void *p2)
{
	const file_entry *entry1 = (const file_entry *)p1;
	const file_entry *entry2 = (const file_entry *)p2;

	if ((entry1->fdr_ptr == 0) && (entry2->fdr_ptr == 0))
		return 0;
	else if (entry1->fdr_ptr == 0)
		return +1;
	else if (entry2->fdr_ptr == 0)
		return -1;
	else
		return memcmp(entry1->name, entry2->name, 10);
}

static int cat_dir_compare_qsort(const void *p1, const void *p2)
{
	const dir_entry *entry1 = (const dir_entry *)p1;
	const dir_entry *entry2 = (const dir_entry *)p2;

	if ((entry1->dir_ptr == 0) && (entry2->dir_ptr == 0))
		return 0;
	else if (entry1->dir_ptr == 0)
		return +1;
	else if (entry2->dir_ptr == 0)
		return -1;
	else
		return memcmp(entry1->name, entry2->name, 10);
}

/*
    Read a directory catalog from disk image

    l2_img: image reference
    aphysrec: physical record address of the FDIR
    dest: pointer to the destination buffer where the catalog should be written

    Return an error code if there was an error, 0 otherwise.
*/
static int dsk_read_catalog(struct ti99_lvl2_imgref *l2_img, int aphysrec, ti99_catalog *dest)
{
	int totphysrecs = l2_img->dsk.totphysrecs;
	UINT16BE fdir_buf[128];
	dsk_fdr fdr;
	int i;
	int reply;


	/* Read FDIR record */
	reply = read_absolute_physrec(& l2_img->l1_img, aphysrec, fdir_buf);
	if (reply)
		return IMGTOOLERR_READERROR;

	/* Copy FDIR info to catalog structure */
	for (i=0; i<128; i++)
		dest->files[i].fdr_ptr = get_UINT16BE(fdir_buf[i]);

	/* Check FDIR pointers and check and extract file names from DDRs */
	for (i=0; i<128; i++)
	{
		if (dest->files[i].fdr_ptr >= totphysrecs)
		{
			return IMGTOOLERR_CORRUPTIMAGE;
		}
		else if (dest->files[i].fdr_ptr)
		{
			reply = read_absolute_physrec(& l2_img->l1_img, dest->files[i].fdr_ptr, &fdr);
			if (reply)
				return IMGTOOLERR_READERROR;

			/* check and copy file name */
			if (check_fname(fdr.name))
				return IMGTOOLERR_CORRUPTIMAGE;
			memcpy(dest->files[i].name, fdr.name, 10);
		}
	}

	/* Check catalog */
	for (i=0; i<127; i++)
	{
		if (((! dest->files[i].fdr_ptr) && dest->files[i+1].fdr_ptr)
			|| ((dest->files[i].fdr_ptr && dest->files[i+1].fdr_ptr) && (memcmp(dest->files[i].name, dest->files[i+1].name, 10) >= 0)))
		{
			/* if the catalog is not sorted, we repair it */
			qsort(dest->files, std::size(dest->files), sizeof(dest->files[0]),
					cat_file_compare_qsort);
			break;
		}
	}

	/* Set file count */
	for (i=0; (i<128) && (dest->files[i].fdr_ptr != 0); i++)
		;
	dest->num_files = i;

	/* Set subdir count to 0 (subdirs are loaded elsewhere) */
	dest->num_subdirs = 0;

	return 0;
}

/*
    Read a directory catalog from disk image

    l2_img: image reference
    DDR_AU: AU address of the VIB/DDR
    dest: pointer to the destination buffer where the catalog should be written

    Return an error code if there was an error, 0 otherwise.
*/
static int win_read_catalog(struct ti99_lvl2_imgref *l2_img, int DDR_AU, ti99_catalog *dest)
{
	win_vib_ddr ddr_buf;
	UINT16BE fdir_buf[128];
	win_fdr fdr_buf;
	int i;
	int reply;


	/* Read DDR record */
	reply = read_absolute_physrec(& l2_img->l1_img, DDR_AU*l2_img->AUformat.physrecsperAU, &ddr_buf);
	if (reply)
		return IMGTOOLERR_READERROR;

	/* sanity checks */
	if ((ddr_buf.num_files > 127) || (ddr_buf.num_subdirs > 114) || (get_UINT16BE(ddr_buf.fdir_AU) > l2_img->AUformat.totAUs))
		return IMGTOOLERR_CORRUPTIMAGE;

	/* set file count and subdir count */
	dest->num_files = ddr_buf.num_files;
	dest->num_subdirs = ddr_buf.num_subdirs;

	/* Copy DDR info to catalog structure */
	for (i=0; i<ddr_buf.num_subdirs; i++)
		dest->subdirs[i].dir_ptr = get_UINT16BE(ddr_buf.subdir_AU[i]);

	/* Read FDIR record */
	reply = read_absolute_physrec(& l2_img->l1_img, get_UINT16BE(ddr_buf.fdir_AU)*l2_img->AUformat.physrecsperAU, fdir_buf);
	if (reply)
		return IMGTOOLERR_READERROR;

	/* Copy FDIR info to catalog structure */
	for (i=0; i<dest->num_files; i++)
		dest->files[i].fdr_ptr = get_UINT16BE(fdir_buf[i]);

	/* Check DDR pointers and check and extract file names from FDRs */
	for (i=0; i<dest->num_subdirs; i++)
	{
		if (dest->subdirs[i].dir_ptr >= l2_img->AUformat.totAUs)
		{
			return IMGTOOLERR_CORRUPTIMAGE;
		}
		else if (dest->subdirs[i].dir_ptr)
		{
			reply = read_absolute_physrec(& l2_img->l1_img, dest->subdirs[i].dir_ptr*l2_img->AUformat.physrecsperAU, &ddr_buf);
			if (reply)
				return IMGTOOLERR_READERROR;

			/* check and copy file name */
			if (check_fname(ddr_buf.name))
				return IMGTOOLERR_CORRUPTIMAGE;
			memcpy(dest->subdirs[i].name, ddr_buf.name, 10);
		}
	}

	/* Check FDIR pointers and check and extract file names from FDRs */
	for (i=0; i<dest->num_files; i++)
	{
		if (dest->files[i].fdr_ptr >= l2_img->AUformat.totAUs)
		{
			return IMGTOOLERR_CORRUPTIMAGE;
		}
		else if (dest->files[i].fdr_ptr)
		{
			reply = read_absolute_physrec(& l2_img->l1_img, dest->files[i].fdr_ptr*l2_img->AUformat.physrecsperAU, &fdr_buf);
			if (reply)
				return IMGTOOLERR_READERROR;

			/* check and copy file name */
			if (check_fname(fdr_buf.name))
				return IMGTOOLERR_CORRUPTIMAGE;
			memcpy(dest->files[i].name, fdr_buf.name, 10);
		}
	}

	/* Check catalog */

	/* Check subdir order */
	for (i=0; i<dest->num_subdirs-1; i++)
	{
		if (((! dest->subdirs[i].dir_ptr) && dest->subdirs[i+1].dir_ptr)
			|| ((dest->subdirs[i].dir_ptr && dest->subdirs[i+1].dir_ptr) && (memcmp(dest->subdirs[i].name, dest->subdirs[i+1].name, 10) >= 0)))
		{
			/* if the subdir catalog is not sorted, we repair it */
			qsort(dest->subdirs, dest->num_subdirs, sizeof(dest->subdirs[0]), cat_dir_compare_qsort);
			break;
		}
	}

	/* Fix subdir count */
	while (dest->num_subdirs && (dest->subdirs[dest->num_subdirs-1].dir_ptr == 0))
		dest->num_subdirs--;

	/* Check file order */
	for (i=0; i<dest->num_files-1; i++)
	{
		if (((! dest->files[i].fdr_ptr) && dest->files[i+1].fdr_ptr)
			|| ((dest->files[i].fdr_ptr && dest->files[i+1].fdr_ptr) && (memcmp(dest->files[i].name, dest->files[i+1].name, 10) >= 0)))
		{
			/* if the file catalog is not sorted, we repair it */
			qsort(dest->files, dest->num_files, sizeof(dest->files[0]), cat_file_compare_qsort);
			break;
		}
	}

	/* Fix file count */
	while (dest->num_files && (dest->files[dest->num_files-1].fdr_ptr == 0))
		dest->num_files--;

	return 0;
}

/*
    Search for a file path on a floppy image

    l2_img: image reference
    fpath: path of the file to search
    parent_ref_valid: set to true if either the file was found or the file was
        not found but its parent dir was
    parent_ref: reference to parent dir (0 for root)
    out_is_dir: true if element is a directory
    catalog_index: on output, index of file catalog entry (may be NULL)
*/
static int dsk_find_catalog_entry(struct ti99_lvl2_imgref *l2_img, const char *fpath, int *parent_ref_valid, int *parent_ref, int *out_is_dir, int *catalog_index)
{
	int i;
	const ti99_catalog *cur_catalog;
	const char *element_start, *element_end;
	int element_len;
	char element[10];
	int is_dir = false;


	cur_catalog = & l2_img->dsk.catalogs[0];
	if (parent_ref_valid)
		(* parent_ref_valid) = false;
	if (parent_ref)
		*parent_ref = 0;

	element_start = fpath;
	do
	{
		/* find next path element */
		element_end = strchr(element_start, '.');
		element_len = element_end ? (element_end - element_start) : strlen(element_start);
		if ((element_len > 10) || (element_len == 0))
			return IMGTOOLERR_BADFILENAME;
		/* last path element */
		if ((!element_end) && parent_ref_valid)
			(* parent_ref_valid) = true;

		/* generate file name */
		memcpy(element, element_start, element_len);
		memset(element+element_len, ' ', 10-element_len);

		/* search entry in subdirectories */
		for (i = 0; i<cur_catalog->num_subdirs; i++)
		{
			if (! memcmp(element, cur_catalog->subdirs[i].name, 10))
			{
				is_dir = true;
				break;
			}
		}

		/* if it failed, search entry in files */
		if (i == cur_catalog->num_subdirs)
		{
			for (i = 0; i<cur_catalog->num_files; i++)
			{
				if (! memcmp(element, cur_catalog->files[i].name, 10))
				{
					is_dir = false;
					break;
				}
			}
			/* exit if not found */
			if (i == cur_catalog->num_files)
			{
				return IMGTOOLERR_FILENOTFOUND;
			}
		}

		/* iterate */
		if (element_end)
		{
			element_start = element_end+1;

			if (! is_dir)
				/* this is not a directory */
				return IMGTOOLERR_BADFILENAME;

			/* initialize cur_catalog */
			cur_catalog = & l2_img->dsk.catalogs[i+1];
			if (parent_ref)
				*parent_ref = i+1;
		}
		else
			element_start = NULL;
	}
	while (element_start);

	if (out_is_dir)
		*out_is_dir = is_dir;

	if (catalog_index)
		*catalog_index = i;

	return 0;
}

/*
    Search for a file path on a harddisk image

    l2_img: image reference
    fpath: path of the file to search
    parent_ref_valid: set to true if either the file was found or the file was
        not found but its parent dir was
    parent_ddr_AU: parent DDR AU address (0 for root)
    parent_catalog: catalog of parent dir (cannot be NULL)
    out_is_dir: true if element is a directory
    catalog_index: on output, index of file catalog entry (may be NULL)
*/
static int win_find_catalog_entry(struct ti99_lvl2_imgref *l2_img, const char *fpath,
									int *parent_ref_valid, int *parent_ddr_AU, ti99_catalog *parent_catalog,
									int *out_is_dir, int *catalog_index)
{
	int i;
	const char *element_start, *element_end;
	int element_len;
	char element[10];
	int is_dir = false;
	int errorcode;

	if (parent_ref_valid)
		(* parent_ref_valid) = false;
	if (parent_ddr_AU)
		*parent_ddr_AU = 0;

	errorcode = win_read_catalog(l2_img, 0, parent_catalog);
	if (errorcode)
		return errorcode;

	element_start = fpath;
	do
	{
		/* find next path element */
		element_end = strchr(element_start, '.');
		element_len = element_end ? (element_end - element_start) : strlen(element_start);
		if ((element_len > 10) || (element_len == 0))
			return IMGTOOLERR_BADFILENAME;
		/* last path element */
		if ((!element_end) && parent_ref_valid)
			(* parent_ref_valid) = true;

		/* generate file name */
		memcpy(element, element_start, element_len);
		memset(element+element_len, ' ', 10-element_len);

		/* search entry in subdirectories */
		for (i = 0; i<parent_catalog->num_subdirs; i++)
		{
			if (! memcmp(element, parent_catalog->subdirs[i].name, 10))
			{
				is_dir = true;
				break;
			}
		}

		/* if it failed, search entry in files */
		if (i == parent_catalog->num_subdirs)
		{
			for (i = 0; i<parent_catalog->num_files; i++)
			{
				if (! memcmp(element, parent_catalog->files[i].name, 10))
				{
					is_dir = false;
					break;
				}
			}
			/* exit if not found */
			if (i == parent_catalog->num_files)
			{
				return IMGTOOLERR_FILENOTFOUND;
			}
		}

		/* iterate */
		if (element_end)
		{
			element_start = element_end+1;

			if (! is_dir)
				/* this is not a directory */
				return IMGTOOLERR_BADFILENAME;

			if (parent_ddr_AU)
				*parent_ddr_AU = parent_catalog->subdirs[i].dir_ptr;

			errorcode = win_read_catalog(l2_img, parent_catalog->subdirs[i].dir_ptr, parent_catalog);
			if (errorcode)
				return errorcode;
		}
		else
			element_start = NULL;
	}
	while (element_start);

	if (out_is_dir)
		*out_is_dir = is_dir;

	if (catalog_index)
		*catalog_index = i;

	return 0;
}

/*
    Allocate one AU on disk, for use as a fdr record

    l2_img: image reference
    fdr_AU: on output, address of allocated AU
*/
static int alloc_fdr_AU(struct ti99_lvl2_imgref *l2_img, unsigned *fdr_AU)
{
	int totAUs = l2_img->AUformat.totAUs;
	int i;

	for (i=0; i<totAUs; i++)
	{
		if (! (l2_img->abm[i >> 3] & (1 << (i & 7))))
		{
			*fdr_AU = i;
			l2_img->abm[i >> 3] |= 1 << (i & 7);

			return 0;
		}
	}

	return IMGTOOLERR_NOSPACE;
}

static inline int get_dsk_fdr_cluster_baseAU(struct ti99_lvl2_imgref *l2_img, dsk_fdr *fdr, int cluster_index)
{
	int reply;

	/* read base AU/physrec for this cluster */
	reply = ((fdr->clusters[cluster_index][1] & 0xf) << 8) | fdr->clusters[cluster_index][0];
	/* convert to AU address */
	if (l2_img->AUformat.physrecsperAU <= 2)
		reply /= l2_img->AUformat.physrecsperAU;

	return reply;
}

static inline int get_dsk_fdr_cluster_baseaphysrec(struct ti99_lvl2_imgref *l2_img, dsk_fdr *fdr, int cluster_index)
{
	int reply;

	/* read base AU/physrec for this cluster */
	reply = ((fdr->clusters[cluster_index][1] & 0xf) << 8) | fdr->clusters[cluster_index][0];
	/* convert to physrec address */
	if (l2_img->AUformat.physrecsperAU > 2)
		reply *= l2_img->AUformat.physrecsperAU;

	return reply;
}

static inline int get_dsk_fdr_cluster_lastfphysrec(dsk_fdr *fdr, int cluster_index)
{
	return (fdr->clusters[cluster_index][2] << 4) | (fdr->clusters[cluster_index][1] >> 4);
}

static inline void set_dsk_fdr_cluster_lastfphysrec(dsk_fdr *fdr, int cluster_index, int data)
{
	fdr->clusters[cluster_index][1] = (fdr->clusters[cluster_index][1] & 0x0f) | (data << 4);
	fdr->clusters[cluster_index][2] = data >> 4;
}

static inline void set_dsk_fdr_cluster(struct ti99_lvl2_imgref *l2_img, dsk_fdr *fdr, int cluster_index, int baseAU, int lastfphysrec)
{
	/* convert AU address to FDR value */
	if (l2_img->AUformat.physrecsperAU <= 2)
		baseAU *= l2_img->AUformat.physrecsperAU;

	/* write cluster entry */
	fdr->clusters[cluster_index][0] = baseAU;
	fdr->clusters[cluster_index][1] = ((baseAU >> 8) & 0x0f) | (lastfphysrec << 4);
	fdr->clusters[cluster_index][2] = lastfphysrec >> 4;
}

static inline unsigned get_win_fdr_fphysrecs(win_fdr *fdr)
{
	return (((unsigned) fdr->xinfo_MSB << 12) & 0xf0000) | get_UINT16BE(fdr->fphysrecs_LSW);
}

static inline void set_win_fdr_fphysrecs(win_fdr *fdr, unsigned data)
{
	fdr->xinfo_MSB = (fdr->xinfo_MSB & 0x0f) | ((data >> 12) & 0xf0);
	set_UINT16BE(&fdr->fphysrecs_LSW, data & 0xffff);
}

static inline unsigned get_win_fdr_fixrecs(win_fdr *fdr)
{
	return (((unsigned) fdr->xinfo_MSB << 16) & 0xf0000) | get_UINT16LE(fdr->fixrecs_LSW);
}

static inline void set_win_fdr_fixrecs(win_fdr *fdr, unsigned data)
{
	fdr->xinfo_MSB = (fdr->xinfo_MSB & 0xf0) | ((data >> 16) & 0x0f);
	set_UINT16LE(&fdr->fixrecs_LSW, data & 0xffff);
}

static inline unsigned get_win_fdr_prevsibFDR_aphysrec(struct ti99_lvl2_imgref *l2_img, win_fdr *fdr)
{
	unsigned prevsibFDR_AU = get_UINT16BE(fdr->prevsibFDR_AU);

	return prevsibFDR_AU
			? (prevsibFDR_AU * l2_img->AUformat.physrecsperAU + ((fdr->xinfo_LSB >> 4) & 0xf))
			: 0;
}

static inline unsigned get_win_fdr_nextsibFDR_aphysrec(struct ti99_lvl2_imgref *l2_img, win_fdr *fdr)
{
	unsigned nextsibFDR_AU = get_UINT16BE(fdr->nextsibFDR_AU);

	return nextsibFDR_AU
			? (nextsibFDR_AU * l2_img->AUformat.physrecsperAU + (fdr->xinfo_LSB & 0xf))
			: 0;
}

static inline unsigned get_win_fdr_cursibFDR_basefphysrec(win_fdr *fdr)
{
	return get_UINT16BE(fdr->prevsibFDR_AU) ? get_win_fdr_fphysrecs(fdr) : 0;
}

/*
    Advance to next sibling FDR
*/
static int win_goto_next_sibFDR(ti99_lvl2_fileref_win *win_file)
{
	if (get_UINT16BE(win_file->curfdr.nextsibFDR_AU) == 0)
		return IMGTOOLERR_UNEXPECTED;

	win_file->curfdr_aphysrec = get_win_fdr_nextsibFDR_aphysrec(win_file->l2_img, &win_file->curfdr);
	if (read_absolute_physrec(& win_file->l2_img->l1_img, win_file->curfdr_aphysrec, &win_file->curfdr))
		return IMGTOOLERR_READERROR;

	return 0;
}

/*
    Back to previous sibling FDR
*/
static int win_goto_prev_sibFDR(ti99_lvl2_fileref_win *win_file)
{
	if (get_UINT16BE(win_file->curfdr.prevsibFDR_AU) == 0)
		return IMGTOOLERR_UNEXPECTED;

	win_file->curfdr_aphysrec = get_win_fdr_prevsibFDR_aphysrec(win_file->l2_img, &win_file->curfdr);
	if (read_absolute_physrec(& win_file->l2_img->l1_img, win_file->curfdr_aphysrec, &win_file->curfdr))
		return IMGTOOLERR_READERROR;

	return 0;
}

/*
    Append a new sibling FDR at the end of the sibling FDR list, and open it.

    You must have gone to the end of the list.
*/
static int win_alloc_sibFDR(ti99_lvl2_fileref_win *win_file)
{
	unsigned oldfdr_AU, oldfdr_physrecinAU;
	unsigned newfdr_AU, newfdr_physrecinAU;
	int allocated = false;
	int errorcode;
	unsigned cursibFDR_basefphysrec;

	if (get_UINT16BE(win_file->curfdr.nextsibFDR_AU))
		return IMGTOOLERR_UNEXPECTED;

	oldfdr_AU = win_file->curfdr_aphysrec / win_file->l2_img->AUformat.physrecsperAU;
	oldfdr_physrecinAU = win_file->curfdr_aphysrec % win_file->l2_img->AUformat.physrecsperAU;

	if (oldfdr_physrecinAU != (win_file->l2_img->AUformat.physrecsperAU - 1))
	{   /* current AU is not full */
		newfdr_AU = oldfdr_AU;
		newfdr_physrecinAU = oldfdr_physrecinAU + 1;
	}
	else
	{   /* current AU is full: allocate another */
		errorcode = alloc_fdr_AU(win_file->l2_img, &newfdr_AU);
		if (errorcode)
			return errorcode;
		newfdr_physrecinAU = 0;
		allocated = true;
	}

	set_UINT16BE(&win_file->curfdr.nextsibFDR_AU, newfdr_AU);
	win_file->curfdr.xinfo_LSB = (win_file->curfdr.xinfo_LSB & 0xf0) | newfdr_physrecinAU;

	/* save current sibling FDR */
	if (write_absolute_physrec(& win_file->l2_img->l1_img, win_file->curfdr_aphysrec, &win_file->curfdr))
	{
		/* clear pointer */
		set_UINT16BE(&win_file->curfdr.nextsibFDR_AU, 0);
		win_file->curfdr.xinfo_LSB = win_file->curfdr.xinfo_LSB & 0xf0;
		if (allocated)
			/* free AU */
			win_file->l2_img->abm[newfdr_AU >> 3] |= 1 << (newfdr_AU & 7);
		return IMGTOOLERR_WRITEERROR;
	}

	/* now update in-memory structure to describe new sibling FDR */
	cursibFDR_basefphysrec = get_win_fdr_cursibFDR_basefphysrec(&win_file->curfdr)
								+ get_UINT16BE(win_file->curfdr.sibFDR_AUlen) * win_file->l2_img->AUformat.physrecsperAU;

	set_UINT16BE(&win_file->curfdr.nextsibFDR_AU, 0);
	set_UINT16BE(&win_file->curfdr.prevsibFDR_AU, oldfdr_AU);
	win_file->curfdr.xinfo_LSB = oldfdr_physrecinAU << 4;

	win_file->curfdr_aphysrec = newfdr_AU * win_file->l2_img->AUformat.physrecsperAU + newfdr_physrecinAU;

	set_win_fdr_fphysrecs(&win_file->curfdr, cursibFDR_basefphysrec);
	set_UINT16BE(&win_file->curfdr.sibFDR_AUlen, 0);
	memset(win_file->curfdr.clusters, 0, sizeof(win_file->curfdr.clusters));

	return 0;
}

/*
    Extend a file with nb_alloc_physrecs extra physrecs

    dsk_file: file reference
    nb_alloc_physrecs: number of physical records to allocate
*/
static int dsk_alloc_file_physrecs(ti99_lvl2_fileref_dsk *dsk_file, int nb_alloc_physrecs)
{
	int totAUs = dsk_file->l2_img->AUformat.totAUs;
	int free_physrecs;
	int fphysrecs;
	int i;
	int cluster_index;
	int last_sec, p_last_sec = 0;
	int cur_block_seclen;
	int cluster_baseAU, cluster_AUlen;
	int first_best_block_baseAU = 0, first_best_block_seclen;
	int second_best_block_baseAU = 0, second_best_block_seclen;
	int search_start;

	/* compute free space */
	free_physrecs = 0;
	for (i=0; i<totAUs; i++)
	{
		if (! (dsk_file->l2_img->abm[i >> 3] & (1 << (i & 7))))
			free_physrecs += dsk_file->l2_img->AUformat.physrecsperAU;
	}

	/* check we have enough free space */
	if (free_physrecs < nb_alloc_physrecs)
		return IMGTOOLERR_NOSPACE;

	/* current number of data physrecs in file */
	fphysrecs = get_UINT16BE(dsk_file->fdr.fphysrecs);

	if (fphysrecs == 0)
	{   /* cluster array must be empty */
		cluster_index = 0;
	}
	else
	{   /* try to extend last block */
		last_sec = -1;
		for (cluster_index=0; cluster_index<76; cluster_index++)
		{
			p_last_sec = last_sec;
			last_sec = get_dsk_fdr_cluster_lastfphysrec(&dsk_file->fdr, cluster_index);
			if (last_sec >= (fphysrecs-1))
				break;
		}
		if (cluster_index == 76)
			/* that sucks */
			return IMGTOOLERR_CORRUPTIMAGE;

		if (last_sec > (fphysrecs-1))
		{   /* some extra space has already been allocated */
			cur_block_seclen = last_sec - (fphysrecs-1);
			if (cur_block_seclen > nb_alloc_physrecs)
				cur_block_seclen = nb_alloc_physrecs;

			fphysrecs += cur_block_seclen;
			set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);
			nb_alloc_physrecs -= cur_block_seclen;
			if (! nb_alloc_physrecs)
				return 0;   /* done */
		}

		/* round up to next AU boundary */
		last_sec = last_sec + dsk_file->l2_img->AUformat.physrecsperAU - (last_sec % dsk_file->l2_img->AUformat.physrecsperAU) - 1;

		if (last_sec > (fphysrecs-1))
		{   /* some extra space has already been allocated */
			cur_block_seclen = last_sec - (fphysrecs-1);
			if (cur_block_seclen > nb_alloc_physrecs)
				cur_block_seclen = nb_alloc_physrecs;

			fphysrecs += cur_block_seclen;
			set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);
			set_dsk_fdr_cluster_lastfphysrec(&dsk_file->fdr, cluster_index, fphysrecs-1);
			nb_alloc_physrecs -= cur_block_seclen;
			if (! nb_alloc_physrecs)
				return 0;   /* done */
		}

		/* read base AU address for this cluster */
		cluster_baseAU = get_dsk_fdr_cluster_baseAU(dsk_file->l2_img, &dsk_file->fdr, cluster_index);
		/* point past cluster end */
		cluster_baseAU += (last_sec-p_last_sec/*+file->l2_img->AUformat.physrecsperAU-1*/) / dsk_file->l2_img->AUformat.physrecsperAU;
		/* count free physrecs after last block */
		cur_block_seclen = 0;
		for (i=cluster_baseAU; (! (dsk_file->l2_img->abm[i >> 3] & (1 << (i & 7)))) && (cur_block_seclen < nb_alloc_physrecs) && (i < totAUs); i++)
			cur_block_seclen += dsk_file->l2_img->AUformat.physrecsperAU;
		if (cur_block_seclen)
		{   /* extend last block */
			if (cur_block_seclen > nb_alloc_physrecs)
				cur_block_seclen = nb_alloc_physrecs;

			fphysrecs += cur_block_seclen;
			set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);
			last_sec += cur_block_seclen;
			nb_alloc_physrecs -= cur_block_seclen;
			set_dsk_fdr_cluster_lastfphysrec(&dsk_file->fdr, cluster_index, last_sec);
			cluster_AUlen = (cur_block_seclen + dsk_file->l2_img->AUformat.physrecsperAU - 1) / dsk_file->l2_img->AUformat.physrecsperAU;
			for (i=0; i<cluster_AUlen; i++)
				dsk_file->l2_img->abm[(i+cluster_baseAU) >> 3] |= 1 << ((i+cluster_baseAU) & 7);
			if (! nb_alloc_physrecs)
				return 0;   /* done */
		}
		cluster_index++;
		if (cluster_index == 76)
			/* that sucks */
			return IMGTOOLERR_NOSPACE;
	}

	search_start = dsk_file->l2_img->data_offset;   /* initially, search for free space only in data space */
	while (nb_alloc_physrecs)
	{
		/* find smallest data block at least nb_alloc_physrecs in length, and largest data block less than nb_alloc_physrecs in length */
		first_best_block_seclen = INT_MAX;
		second_best_block_seclen = 0;
		for (i=search_start; i<totAUs; i++)
		{
			if (! (dsk_file->l2_img->abm[i >> 3] & (1 << (i & 7))))
			{   /* found one free block */
				/* compute its length */
				cluster_baseAU = i;
				cur_block_seclen = 0;
				while ((i<totAUs) && (! (dsk_file->l2_img->abm[i >> 3] & (1 << (i & 7)))))
				{
					cur_block_seclen += dsk_file->l2_img->AUformat.physrecsperAU;
					i++;
				}
				/* compare to previous best and second-best blocks */
				if ((cur_block_seclen < first_best_block_seclen) && (cur_block_seclen >= nb_alloc_physrecs))
				{
					first_best_block_baseAU = cluster_baseAU;
					first_best_block_seclen = cur_block_seclen;
					if (cur_block_seclen == nb_alloc_physrecs)
						/* no need to search further */
						break;
				}
				else if ((cur_block_seclen > second_best_block_seclen) && (cur_block_seclen < nb_alloc_physrecs))
				{
					second_best_block_baseAU = cluster_baseAU;
					second_best_block_seclen = cur_block_seclen;
				}
			}
		}

		if (first_best_block_seclen != INT_MAX)
		{   /* found one contiguous block which can hold it all */
			fphysrecs += nb_alloc_physrecs;
			set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);

			set_dsk_fdr_cluster(dsk_file->l2_img, &dsk_file->fdr, cluster_index, first_best_block_baseAU, fphysrecs-1);
			cluster_AUlen = (nb_alloc_physrecs + dsk_file->l2_img->AUformat.physrecsperAU - 1) / dsk_file->l2_img->AUformat.physrecsperAU;
			for (i=0; i<cluster_AUlen; i++)
				dsk_file->l2_img->abm[(i+first_best_block_baseAU) >> 3] |= 1 << ((i+first_best_block_baseAU) & 7);

			nb_alloc_physrecs = 0;
		}
		else if (second_best_block_seclen != 0)
		{   /* jeez, we need to fragment it.  We use the largest smaller block to limit fragmentation. */
			fphysrecs += second_best_block_seclen;
			set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);

			set_dsk_fdr_cluster(dsk_file->l2_img, &dsk_file->fdr, cluster_index, second_best_block_baseAU, fphysrecs-1);
			cluster_AUlen = (second_best_block_seclen + dsk_file->l2_img->AUformat.physrecsperAU - 1) / dsk_file->l2_img->AUformat.physrecsperAU;
			for (i=0; i<cluster_AUlen; i++)
				dsk_file->l2_img->abm[(i+second_best_block_baseAU) >> 3] |= 1 << ((i+second_best_block_baseAU) & 7);

			nb_alloc_physrecs -= second_best_block_seclen;

			cluster_index++;
			if (cluster_index == 76)
				/* that sucks */
				return IMGTOOLERR_NOSPACE;
		}
		else if (search_start != 0)
		{   /* we did not find any free physrec in the data section of the disk */
			search_start = 0;   /* time to fall back to fdr space */
		}
		else
			return IMGTOOLERR_NOSPACE;  /* This should never happen, as we pre-check that there is enough free space */
	}

	return 0;
}

/*
    Extend a file with nb_alloc_physrecs extra physrecs

    win_file: file reference
    nb_alloc_physrecs: number of physical records to allocate
*/
static int win_alloc_file_physrecs(ti99_lvl2_fileref_win *win_file, int nb_alloc_physrecs)
{
	int totAUs = win_file->l2_img->AUformat.totAUs;
	int free_physrecs;
	int fphysrecs;
	int i;
	int cluster_index;
	int num_fphysrec;
	int cur_block_seclen;
	int cluster_baseAU, cluster_AUlen;
	int first_best_block_baseAU = 0, first_best_block_seclen;
	int second_best_block_baseAU = 0, second_best_block_seclen;
	int search_start;
	int errorcode;

	/* compute free space */
	free_physrecs = 0;
	for (i=0; i<totAUs; i++)
	{
		if (! (win_file->l2_img->abm[i >> 3] & (1 << (i & 7))))
			free_physrecs += win_file->l2_img->AUformat.physrecsperAU;
	}

	/* check we have enough free space */
	if (free_physrecs < nb_alloc_physrecs)
		return IMGTOOLERR_NOSPACE;

	/* move to last sibling non-empty FDR */
	while ((get_UINT16BE(win_file->curfdr.nextsibFDR_AU) != 0) &&
				(get_UINT16BE(win_file->curfdr.clusters[53][0]) != 0))
	{
		errorcode = win_goto_next_sibFDR(win_file);
		if (errorcode)
			return errorcode;
	}
	if ((get_UINT16BE(win_file->curfdr.clusters[0][0]) == 0) && (get_UINT16BE(win_file->curfdr.prevsibFDR_AU) != 0))
	{   /* this is annoying: we have found a sibling FDR filled with 0s: rewind
	    to last non-empty sibling if applicable */
		errorcode = win_goto_prev_sibFDR(win_file);
		if (errorcode)
			return errorcode;
	}

	/* current number of data physrecs in file */
	fphysrecs = win_file->fphysrecs;

	/* current number of allocated physrecs */
	num_fphysrec = get_win_fdr_cursibFDR_basefphysrec(&win_file->curfdr)
						+ get_UINT16BE(win_file->curfdr.sibFDR_AUlen) * win_file->l2_img->AUformat.physrecsperAU;

	if (num_fphysrec > fphysrecs)
	{   /* some extra space has already been allocated */
		cur_block_seclen = num_fphysrec - fphysrecs;
		if (cur_block_seclen > nb_alloc_physrecs)
			cur_block_seclen = nb_alloc_physrecs;

		fphysrecs += cur_block_seclen;
		win_file->fphysrecs = fphysrecs;
		/* TODO: update eldest FDR fphysrecs field */
		/*set_win_fdr_fphysrecs(& win_file->rootfdr.fphysrecs, fphysrecs);*/
		nb_alloc_physrecs -= cur_block_seclen;
		if (! nb_alloc_physrecs)
			return 0;   /* done */
	}

	/* find last non-empty cluster */
	for (cluster_index=0; (cluster_index<54) && (get_UINT16BE(win_file->curfdr.clusters[cluster_index][0]) != 0); cluster_index++)
		;
	/* if we are dealing with an empty file, we will have (cluster_index == 0)... */
	if (cluster_index != 0)
	{
		cluster_index--;
		/* try to extend last cluster */
		/* point past cluster end */
		cluster_baseAU = get_UINT16BE(win_file->curfdr.clusters[cluster_index][1]) + 1;
		/* count free physrecs after last block */
		cur_block_seclen = 0;
		for (i=cluster_baseAU; (! (win_file->l2_img->abm[i >> 3] & (1 << (i & 7)))) && (cur_block_seclen < nb_alloc_physrecs) && (i < totAUs); i++)
			cur_block_seclen += win_file->l2_img->AUformat.physrecsperAU;
		if (cur_block_seclen)
		{   /* extend last block */
			if (cur_block_seclen > nb_alloc_physrecs)
				cur_block_seclen = nb_alloc_physrecs;

			fphysrecs += cur_block_seclen;
			cluster_AUlen = (cur_block_seclen + win_file->l2_img->AUformat.physrecsperAU - 1) / win_file->l2_img->AUformat.physrecsperAU;
			win_file->fphysrecs = fphysrecs;
			/* TODO: update eldest FDR fphysrecs field */
			/*set_win_fdr_fphysrecs(& win_file->rootfdr.fphysrecs, fphysrecs);*/
			set_UINT16BE(&win_file->curfdr.sibFDR_AUlen,
							get_UINT16BE(win_file->curfdr.sibFDR_AUlen)+cluster_AUlen);
			set_UINT16BE(&win_file->curfdr.clusters[cluster_index][1],
							get_UINT16BE(win_file->curfdr.clusters[cluster_index][1])+cluster_AUlen);
			for (i=0; i<cluster_AUlen; i++)
				win_file->l2_img->abm[(i+cluster_baseAU) >> 3] |= 1 << ((i+cluster_baseAU) & 7);
			nb_alloc_physrecs -= cur_block_seclen;
			if (! nb_alloc_physrecs)
				return 0;   /* done */
		}
		/* now point to first free entry in cluster table */
		cluster_index++;
	}

	search_start = win_file->l2_img->data_offset;   /* initially, search for free space only in data space */
	while (nb_alloc_physrecs)
	{
		/* find smallest data block at least nb_alloc_physrecs in length, and largest data block less than nb_alloc_physrecs in length */
		first_best_block_seclen = INT_MAX;
		second_best_block_seclen = 0;
		for (i=search_start; i<totAUs; i++)
		{
			if (! (win_file->l2_img->abm[i >> 3] & (1 << (i & 7))))
			{   /* found one free block */
				/* compute its length */
				cluster_baseAU = i;
				cur_block_seclen = 0;
				while ((i<totAUs) && (! (win_file->l2_img->abm[i >> 3] & (1 << (i & 7)))))
				{
					cur_block_seclen += win_file->l2_img->AUformat.physrecsperAU;
					i++;
				}
				/* compare to previous best and second-best blocks */
				if ((cur_block_seclen < first_best_block_seclen) && (cur_block_seclen >= nb_alloc_physrecs))
				{
					first_best_block_baseAU = cluster_baseAU;
					first_best_block_seclen = cur_block_seclen;
					if (cur_block_seclen == nb_alloc_physrecs)
						/* no need to search further */
						break;
				}
				else if ((cur_block_seclen > second_best_block_seclen) && (cur_block_seclen < nb_alloc_physrecs))
				{
					second_best_block_baseAU = cluster_baseAU;
					second_best_block_seclen = cur_block_seclen;
				}
			}
		}

		if ((first_best_block_seclen != INT_MAX) || (second_best_block_seclen != 0))
		{
			if (cluster_index == 54)
			{
				/* end of cluster list: go to next sibling FDR */
				if (write_absolute_physrec(& win_file->l2_img->l1_img, win_file->curfdr_aphysrec, &win_file->curfdr))
					return IMGTOOLERR_WRITEERROR;
				if (get_UINT16BE(win_file->curfdr.nextsibFDR_AU) != 0)
				{   /* read next sibling FDR */
					errorcode = win_goto_next_sibFDR(win_file);
					if (errorcode)
						return errorcode;
				}
				else
				{   /* allocate new sibling FDR */
					errorcode = win_alloc_sibFDR(win_file);
					if (errorcode)
						return errorcode;
				}
				cluster_index = 0;
			}
		}

		if (first_best_block_seclen != INT_MAX)
		{   /* found one contiguous block which can hold it all */
			fphysrecs += nb_alloc_physrecs;
			cluster_AUlen = (nb_alloc_physrecs + win_file->l2_img->AUformat.physrecsperAU - 1) / win_file->l2_img->AUformat.physrecsperAU;
			win_file->fphysrecs = fphysrecs;
			/* TODO: update eldest FDR fphysrecs field */
			/*set_win_fdr_fphysrecs(& win_file->rootfdr.fphysrecs, fphysrecs);*/
			set_UINT16BE(&win_file->curfdr.sibFDR_AUlen,
								get_UINT16BE(win_file->curfdr.sibFDR_AUlen)+cluster_AUlen);
			set_UINT16BE(&win_file->curfdr.clusters[cluster_index][0], first_best_block_baseAU);
			set_UINT16BE(&win_file->curfdr.clusters[cluster_index][1],
								first_best_block_baseAU+cluster_AUlen-1);

			for (i=0; i<cluster_AUlen; i++)
				win_file->l2_img->abm[(i+first_best_block_baseAU) >> 3] |= 1 << ((i+first_best_block_baseAU) & 7);

			nb_alloc_physrecs = 0;
		}
		else if (second_best_block_seclen != 0)
		{   /* jeez, we need to fragment it.  We use the largest smaller block to limit fragmentation. */
			fphysrecs += second_best_block_seclen;
			cluster_AUlen = (second_best_block_seclen + win_file->l2_img->AUformat.physrecsperAU - 1) / win_file->l2_img->AUformat.physrecsperAU;
			win_file->fphysrecs = fphysrecs;
			/* TODO: update eldest FDR fphysrecs field */
			/*set_win_fdr_fphysrecs(& win_file->rootfdr.fphysrecs, fphysrecs);*/
			set_UINT16BE(&win_file->curfdr.sibFDR_AUlen,
								get_UINT16BE(win_file->curfdr.sibFDR_AUlen)+cluster_AUlen);
			set_UINT16BE(&win_file->curfdr.clusters[cluster_index][0], second_best_block_baseAU);
			set_UINT16BE(&win_file->curfdr.clusters[cluster_index][1],
								second_best_block_baseAU+cluster_AUlen-1);

			for (i=0; i<cluster_AUlen; i++)
				win_file->l2_img->abm[(i+second_best_block_baseAU) >> 3] |= 1 << ((i+second_best_block_baseAU) & 7);

			nb_alloc_physrecs -= second_best_block_seclen;

			/* now point to first free entry in cluster table */
			cluster_index++;
		}
		else if (search_start != 0)
		{   /* we did not find any free physrec in the data section of the disk */
			search_start = 0;   /* time to fall back to fdr space */
		}
		else
			return IMGTOOLERR_NOSPACE;  /* This should never happen, as we pre-check that there is enough free space */
	}

	return 0;
}

/*
    Allocate a new (empty) file
*/
static int new_file_lvl2_dsk(struct ti99_lvl2_imgref *l2_img, int parent_ref, char filename[10], struct ti99_lvl2_fileref *l2_file)
{
	ti99_catalog *catalog = &l2_img->dsk.catalogs[parent_ref];
	unsigned fdr_AU, fdr_aphysrec;
	int catalog_index, i;
	int reply = 0;
	int errorcode;


	if (catalog->num_files >= 127)
		/* if num_files == 128, catalog is full */
		/* if num_files == 127, catalog is not full, but we don't want to write
		a 128th entry for compatibility with some existing DSRs that detect the
		end of the FDIR array with a 0 entry (and do not check that the index
		has not reached 128) */
		return IMGTOOLERR_NOSPACE;

	/* find insertion point in catalog */
	for (i=0; (i < catalog->num_files) && ((reply = memcmp(catalog->files[i].name, filename, 10)) < 0); i++)
		;

	if ((i<catalog->num_files) && (reply == 0))
		/* file already exists */
		return IMGTOOLERR_BADFILENAME;
	else
	{
		/* otherwise insert new entry */
		catalog_index = i;
		errorcode = alloc_fdr_AU(l2_img, &fdr_AU);
		if (errorcode)
			return errorcode;
		fdr_aphysrec = fdr_AU * l2_img->AUformat.physrecsperAU;

		/* shift catalog entries until the insertion point */
		for (i=catalog->num_files; i>catalog_index; i--)
			catalog->files[i] = catalog->files[i-1];

		/* write new catalog entry */
		catalog->files[catalog_index].fdr_ptr = fdr_aphysrec;
		memcpy(catalog->files[catalog_index].name, filename, 10);

		/* update catalog len */
		catalog->num_files++;
	}

	/* set up file handle */
	l2_file->type = L2F_DSK;
	l2_file->dsk.l2_img = l2_img;
	l2_file->dsk.fdr_aphysrec = fdr_aphysrec;
	memset(&l2_file->dsk.fdr, 0, sizeof(l2_file->dsk.fdr));
	memcpy(l2_file->dsk.fdr.name, filename, 10);

	return 0;
}

/*
    Allocate a new (empty) file
*/
static int new_file_lvl2_win(struct ti99_lvl2_imgref *l2_img, ti99_catalog *parent_catalog, char filename[10], struct ti99_lvl2_fileref *l2_file)
{
	unsigned fdr_AU;
	int catalog_index, i;
	int reply = 0;
	int errorcode;


	if (parent_catalog->num_files >= 127)
		/* if num_files == 127, catalog is full */
		return IMGTOOLERR_NOSPACE;

	/* find insertion point in catalog */
	for (i=0; (i < parent_catalog->num_files) && ((reply = memcmp(parent_catalog->files[i].name, filename, 10)) < 0); i++)
		;

	if ((i<parent_catalog->num_files) && (reply == 0))
		/* file already exists */
		return IMGTOOLERR_BADFILENAME;
	else
	{
		/* otherwise insert new entry */
		catalog_index = i;
		errorcode = alloc_fdr_AU(l2_img, &fdr_AU);
		if (errorcode)
			return errorcode;

		/* shift catalog entries until the insertion point */
		for (i=parent_catalog->num_files; i>catalog_index; i--)
			parent_catalog->files[i] = parent_catalog->files[i-1];

		/* write new catalog entry */
		parent_catalog->files[catalog_index].fdr_ptr = fdr_AU;
		memcpy(parent_catalog->files[catalog_index].name, filename, 10);

		/* update catalog len */
		parent_catalog->num_files++;
	}

	/* set up file handle */
	l2_file->type = L2F_WIN;
	l2_file->win.l2_img = l2_img;
	l2_file->win.fphysrecs = 0;
	l2_file->win.eldestfdr_aphysrec = fdr_AU * l2_img->AUformat.physrecsperAU;
	l2_file->win.curfdr_aphysrec = l2_file->win.eldestfdr_aphysrec;
	memset(&l2_file->win.curfdr, 0, sizeof(l2_file->win.curfdr));
	memcpy(l2_file->win.curfdr.name, filename, 10);

	return 0;
}

/*
    Allocate a new (empty) file
*/
static int new_file_lvl2_tifiles(imgtool::stream &file_handle, struct ti99_lvl2_fileref *l2_file)
{
	/* set up file handle */
	l2_file->type = L2F_TIFILES;
	l2_file->tifiles.file_handle = &file_handle;
	memset(&l2_file->tifiles.hdr, 0, sizeof(l2_file->tifiles.hdr));
	l2_file->tifiles.hdr.tifiles[0] = '\7';
	l2_file->tifiles.hdr.tifiles[1] = 'T';
	l2_file->tifiles.hdr.tifiles[2] = 'I';
	l2_file->tifiles.hdr.tifiles[3] = 'F';
	l2_file->tifiles.hdr.tifiles[4] = 'I';
	l2_file->tifiles.hdr.tifiles[5] = 'L';
	l2_file->tifiles.hdr.tifiles[6] = 'E';
	l2_file->tifiles.hdr.tifiles[7] = 'S';

	return 0;
}

/*
    Open an existing file on a floppy image

    l2_img: level 2 image the file is located on
    fpath: access path to the file
    file: set up if open is successful
*/
static int open_file_lvl2_dsk(struct ti99_lvl2_imgref *l2_img, const char *fpath, struct ti99_lvl2_fileref *l2_file)
{
	int parent_ref, is_dir, catalog_index;
	int reply;


	reply = dsk_find_catalog_entry(l2_img, fpath, NULL, &parent_ref, &is_dir, &catalog_index);
	if (reply)
		return reply;

	if (is_dir)
		/* this is not a file */
		return IMGTOOLERR_BADFILENAME;

	l2_file->type = L2F_DSK;
	l2_file->dsk.l2_img = l2_img;
	l2_file->dsk.fdr_aphysrec = l2_img->dsk.catalogs[parent_ref].files[catalog_index].fdr_ptr;
	if (read_absolute_physrec(& l2_img->l1_img, l2_file->dsk.fdr_aphysrec, &l2_file->dsk.fdr))
		return IMGTOOLERR_READERROR;

	return 0;
}

/*
    Open an existing file on a harddisk image

    l2_img: level 2 image the file is located on
    fpath: access path to the file
    file: set up if open is successful
*/
static int open_file_lvl2_win(struct ti99_lvl2_imgref *l2_img, const char *fpath, struct ti99_lvl2_fileref *l2_file)
{
	int parent_ref, is_dir, catalog_index;
	ti99_catalog catalog;
	int reply;

	reply = win_find_catalog_entry(l2_img, fpath, NULL, &parent_ref, &catalog, &is_dir, &catalog_index);
	if (reply)
		return reply;

	if (is_dir)
		/* this is not a file */
		return IMGTOOLERR_BADFILENAME;

	l2_file->type = L2F_WIN;
	l2_file->win.l2_img = l2_img;
	l2_file->win.eldestfdr_aphysrec = catalog.files[catalog_index].fdr_ptr * l2_img->AUformat.physrecsperAU;
	l2_file->win.curfdr_aphysrec = l2_file->win.eldestfdr_aphysrec;
	if (read_absolute_physrec(& l2_img->l1_img, l2_file->win.curfdr_aphysrec, &l2_file->win.curfdr))
		return IMGTOOLERR_READERROR;
	l2_file->win.fphysrecs = get_win_fdr_fphysrecs(&l2_file->win.curfdr);

	/* check integrity of FDR sibling chain */
	/* note that as we check that the back chain is consistent with the forward
	chain, we will also detect any cycle in the sibling chain, so we do not
	need to check against them explicitely */
	if (get_UINT16BE(l2_file->win.curfdr.prevsibFDR_AU) != 0)
		return IMGTOOLERR_CORRUPTIMAGE;

	{
		int i, pastendoflist_flag;
		unsigned cur_fphysrec, sibFDR_AUlen;
		win_fdr *cur_fdr, fdr_buf;
		unsigned curfdr_aphysrec, prevfdr_aphysrec;

		cur_fphysrec = 0;
		pastendoflist_flag = 0;
		cur_fdr = &l2_file->win.curfdr;
		curfdr_aphysrec = l2_file->win.eldestfdr_aphysrec;

		while (1)
		{
			sibFDR_AUlen = 0;
			i=0;
			if (! pastendoflist_flag)
			{
				/* compute number of allocated AUs and check number of AUs */
				for (; i<54; i++)
				{
					if (get_UINT16BE(cur_fdr->clusters[i][0]) == 0)
					{
						pastendoflist_flag = true;
						break;
					}
					sibFDR_AUlen += get_UINT16BE(cur_fdr->clusters[i][1])
									- get_UINT16BE(cur_fdr->clusters[i][0])
									+ 1;
				}
			}
			/* clear remainder of cluster table */
			for (; i<54; i++)
			{
#if 0
				set_UINT16BE(&cur_fdr->clusters[i][0], 0);
				set_UINT16BE(&cur_fdr->clusters[i][1], 0);
#endif
				if ((get_UINT16BE(cur_fdr->clusters[i][0]) != 0) || (get_UINT16BE(cur_fdr->clusters[i][1]) != 0))
					return IMGTOOLERR_CORRUPTIMAGE;
			}

			/* check sibFDR_AUlen field */
			if (get_UINT16BE(cur_fdr->sibFDR_AUlen) != sibFDR_AUlen)
				return IMGTOOLERR_CORRUPTIMAGE;

			/* update current file physrec position to point to end of sibling FDR */
			cur_fphysrec += sibFDR_AUlen * l2_file->win.l2_img->AUformat.physrecsperAU;

			/* exit loop if end of sibling chain */
			if (! get_UINT16BE(cur_fdr->nextsibFDR_AU))
				break;

			/* otherwise read next FDR */
			if (get_UINT16BE(cur_fdr->nextsibFDR_AU) >= l2_file->win.l2_img->AUformat.totAUs)
				return IMGTOOLERR_CORRUPTIMAGE;

			prevfdr_aphysrec = curfdr_aphysrec;
			curfdr_aphysrec = get_win_fdr_nextsibFDR_aphysrec(l2_file->win.l2_img, cur_fdr);
			if (read_absolute_physrec(& l2_file->win.l2_img->l1_img, curfdr_aphysrec, &fdr_buf))
				return IMGTOOLERR_READERROR;
			cur_fdr = &fdr_buf;

			/* check that back chaining is consistent with forward chaining */
			if (get_win_fdr_prevsibFDR_aphysrec(l2_file->win.l2_img, &fdr_buf) != prevfdr_aphysrec)
				return IMGTOOLERR_CORRUPTIMAGE;
			/*  check fphysrecs field */
			if (get_win_fdr_fphysrecs(&fdr_buf) != cur_fphysrec)
				return IMGTOOLERR_CORRUPTIMAGE;

			/* check consistency of informative fields (name, record format, flags, etc) */
			if (memcmp(fdr_buf.name, l2_file->win.curfdr.name, 10)
					|| (get_UINT16BE(fdr_buf.xreclen) != get_UINT16BE(l2_file->win.curfdr.xreclen))
					|| (fdr_buf.flags != l2_file->win.curfdr.flags)
					|| (fdr_buf.recsperphysrec != l2_file->win.curfdr.recsperphysrec)
					|| (fdr_buf.eof != l2_file->win.curfdr.eof)
					|| (fdr_buf.reclen != l2_file->win.curfdr.reclen)
					|| (get_UINT16LE(fdr_buf.fixrecs_LSW) != get_UINT16LE(l2_file->win.curfdr.fixrecs_LSW))
					|| memcmp(&fdr_buf.creation, &l2_file->win.curfdr.creation, 4)
					|| memcmp(&fdr_buf.update, &l2_file->win.curfdr.update, 4)
					/*|| memcmp(fdr_buf.id, l2_file->win.curfdr.id, 2)*/
					|| (get_UINT16BE(fdr_buf.parent_FDIR_AU) != get_UINT16BE(l2_file->win.curfdr.parent_FDIR_AU))
					|| ((fdr_buf.xinfo_MSB & 0xf) != (l2_file->win.curfdr.xinfo_MSB & 0xf)))
				return IMGTOOLERR_CORRUPTIMAGE;
		}
		if (cur_fphysrec < l2_file->win.fphysrecs)
			return IMGTOOLERR_CORRUPTIMAGE;
	}

	return 0;
}

/*
    Open an existing file in TIFILES format
*/
static int open_file_lvl2_tifiles(imgtool::stream &file_handle, struct ti99_lvl2_fileref *l2_file)
{
	/* set up file handle */
	l2_file->type = L2F_TIFILES;
	l2_file->tifiles.file_handle = &file_handle;

	/* seek to header */
	if (l2_file->tifiles.file_handle->seek(0, SEEK_SET))
		return IMGTOOLERR_READERROR;
	/* read it */
	if (l2_file->tifiles.file_handle->read(&l2_file->tifiles.hdr, sizeof(l2_file->tifiles.hdr)) != sizeof(l2_file->tifiles.hdr))
		return IMGTOOLERR_READERROR;

	return 0;
}

/*
    compute the aphysrec address for a given file physical record (fphysrec)

    l2_img: image where the file is located
*/
static int dsk_fphysrec_to_aphysrec(ti99_lvl2_fileref_dsk *dsk_file, unsigned fphysrec, unsigned *aphysrec)
{
	int cluster_index;
	int cluster_firstfphysrec, cluster_lastfphysrec;
	int cluster_baseaphysrec;


	/* check parameter */
	if (fphysrec >= get_UINT16BE(dsk_file->fdr.fphysrecs))
		return IMGTOOLERR_UNEXPECTED;


	/* search for the cluster in the data chain pointers array */
	cluster_firstfphysrec = 0;
	for (cluster_index=0; cluster_index<76; cluster_index++)
	{
		/* read curent file block table entry */
		cluster_lastfphysrec = get_dsk_fdr_cluster_lastfphysrec(&dsk_file->fdr, cluster_index);
		if (cluster_lastfphysrec >= fphysrec)
			break;
		cluster_firstfphysrec = cluster_lastfphysrec+1;
	}
	if (cluster_index == 76)
		/* if not found, the file is corrupt */
		return IMGTOOLERR_CORRUPTIMAGE;

	/* read base aphysrec address for this cluster */
	cluster_baseaphysrec = get_dsk_fdr_cluster_baseaphysrec(dsk_file->l2_img, &dsk_file->fdr, cluster_index);
	/* return absolute physrec address */
	*aphysrec = cluster_baseaphysrec + (fphysrec - cluster_firstfphysrec);
	return 0;
}

/*
    compute the aphysrec address for a given file physical record (fphysrec)

    l2_img: image where the file is located
*/
static int win_fphysrec_to_aphysrec(ti99_lvl2_fileref_win *win_file, unsigned fphysrec, unsigned *aphysrec)
{
	int cluster_index;
	int cluster_firstfphysrec, cluster_lastfphysrec;
	int cluster_baseaphysrec;
	int errorcode;


	/* check parameter */
	if (fphysrec >= win_file->fphysrecs)
		return IMGTOOLERR_UNEXPECTED;

	/* look for correct sibling */
	if (fphysrec < get_win_fdr_cursibFDR_basefphysrec(& win_file->curfdr))
	{
		while (fphysrec < get_win_fdr_cursibFDR_basefphysrec(& win_file->curfdr))
		{
			if (get_UINT16BE(win_file->curfdr.prevsibFDR_AU) == 0)
				return IMGTOOLERR_CORRUPTIMAGE;
			errorcode = win_goto_prev_sibFDR(win_file);
			if (errorcode)
				return errorcode;
		}
	}
	else /*if (fphysrec >= get_win_fdr_cursibFDR_basefphysrec(& dsk_file->curfdr))*/
	{
		while (fphysrec >= (get_win_fdr_cursibFDR_basefphysrec(& win_file->curfdr)
								+ get_UINT16BE(win_file->curfdr.sibFDR_AUlen) * win_file->l2_img->AUformat.physrecsperAU))
		{
			if (get_UINT16BE(win_file->curfdr.nextsibFDR_AU) == 0)
				return IMGTOOLERR_CORRUPTIMAGE;
			errorcode = win_goto_next_sibFDR(win_file);
			if (errorcode)
				return errorcode;
		}
	}


	/* search for the cluster in the data chain pointers array */
	cluster_firstfphysrec = get_win_fdr_cursibFDR_basefphysrec(& win_file->curfdr);
	for (cluster_index = 0; cluster_index<54; cluster_index++)
	{
		cluster_lastfphysrec = cluster_firstfphysrec
									+ (get_UINT16BE(win_file->curfdr.clusters[cluster_index][1])
											- get_UINT16BE(win_file->curfdr.clusters[cluster_index][0])
											+ 1)
										* win_file->l2_img->AUformat.physrecsperAU;
		if (fphysrec < cluster_lastfphysrec)
			break;

		cluster_firstfphysrec = cluster_lastfphysrec;
	}

	if (cluster_index == 54)
		return IMGTOOLERR_CORRUPTIMAGE;


	/* read base aphysrec address for this cluster */
	cluster_baseaphysrec = get_UINT16BE(win_file->curfdr.clusters[cluster_index][0]) * win_file->l2_img->AUformat.physrecsperAU;
	/* return absolute physrec address */
	*aphysrec = cluster_baseaphysrec + (fphysrec - cluster_firstfphysrec);
	return 0;
}

/*
    read a 256-byte physical record from a file
*/
static int read_file_physrec(struct ti99_lvl2_fileref *l2_file, unsigned fphysrec, void *dest)
{
	int errorcode;
	unsigned aphysrec;

	switch (l2_file->type)
	{
	case L2F_DSK:
		/* compute absolute physrec address */
		errorcode = dsk_fphysrec_to_aphysrec(&l2_file->dsk, fphysrec, &aphysrec);
		if (errorcode)
			return errorcode;
		/* read physrec */
		if (read_absolute_physrec(& l2_file->dsk.l2_img->l1_img, aphysrec, dest))
			return IMGTOOLERR_READERROR;
		break;

	case L2F_WIN:
		/* compute absolute physrec address */
		errorcode = win_fphysrec_to_aphysrec(&l2_file->win, fphysrec, &aphysrec);
		if (errorcode)
			return errorcode;
		/* read physrec */
		if (read_absolute_physrec(& l2_file->win.l2_img->l1_img, aphysrec, dest))
			return IMGTOOLERR_READERROR;
		break;

	case L2F_TIFILES:
		/* seek to physrec */
		if (l2_file->tifiles.file_handle->seek(128+256*fphysrec, SEEK_SET))
			return IMGTOOLERR_READERROR;
		/* read it */
		if (l2_file->tifiles.file_handle->read(dest, 256) != 256)
			return IMGTOOLERR_READERROR;
		break;
	}

	return 0;
}

/*
    read a 256-byte physical record from a file
*/
static int write_file_physrec(struct ti99_lvl2_fileref *l2_file, unsigned fphysrec, const void *src)
{
	int errorcode;
	unsigned aphysrec;

	switch (l2_file->type)
	{
	case L2F_DSK:
		/* compute absolute physrec address */
		errorcode = dsk_fphysrec_to_aphysrec(&l2_file->dsk, fphysrec, &aphysrec);
		if (errorcode)
			return errorcode;
		/* write physrec */
		if (write_absolute_physrec(& l2_file->dsk.l2_img->l1_img, aphysrec, src))
			return IMGTOOLERR_WRITEERROR;
		break;

	case L2F_WIN:
		/* compute absolute physrec address */
		errorcode = win_fphysrec_to_aphysrec(&l2_file->win, fphysrec, &aphysrec);
		if (errorcode)
			return errorcode;
		/* write physrec */
		if (write_absolute_physrec(& l2_file->win.l2_img->l1_img, aphysrec, src))
			return IMGTOOLERR_WRITEERROR;
		break;

	case L2F_TIFILES:
		/* seek to physrec */
		if (l2_file->tifiles.file_handle->seek(128+256*fphysrec, SEEK_SET))
			return IMGTOOLERR_WRITEERROR;
		/* write it */
		if (l2_file->tifiles.file_handle->write(src, 256) != 256)
			return IMGTOOLERR_WRITEERROR;
		break;
	}

	return 0;
}

/*
    Write a field in every fdr record associated to a file
*/
[[maybe_unused]] static int set_win_fdr_field(struct ti99_lvl2_fileref *l2_file, size_t offset, size_t size, void *data)
{
	win_fdr fdr_buf;
	unsigned fdr_aphysrec;
	int errorcode = 0;

	for (fdr_aphysrec = l2_file->win.eldestfdr_aphysrec;
			fdr_aphysrec && ((errorcode = (read_absolute_physrec(&l2_file->win.l2_img->l1_img, fdr_aphysrec, &fdr_buf) ? IMGTOOLERR_READERROR : 0)) == 0);
			fdr_aphysrec = get_win_fdr_nextsibFDR_aphysrec(l2_file->win.l2_img, &fdr_buf))
	{
		memcpy(((uint8_t *) &fdr_buf) + offset, data, size);
		if (write_absolute_physrec(&l2_file->win.l2_img->l1_img, fdr_aphysrec, &fdr_buf))
		{
			errorcode = IMGTOOLERR_WRITEERROR;
			break;
		}
	}

	return errorcode;
}

static uint8_t get_file_flags(struct ti99_lvl2_fileref *l2_file)
{
	int reply = 0;

	switch (l2_file->type)
	{
	case L2F_DSK:
		reply = l2_file->dsk.fdr.flags;
		break;

	case L2F_WIN:
		reply = l2_file->win.curfdr.flags;
		break;

	case L2F_TIFILES:
		reply = l2_file->tifiles.hdr.flags;
		break;
	}

	return reply;
}

static void set_file_flags(struct ti99_lvl2_fileref *l2_file, uint8_t data)
{
	switch (l2_file->type)
	{
	case L2F_DSK:
		l2_file->dsk.fdr.flags = data;
		break;

	case L2F_WIN:
		l2_file->win.curfdr.flags = data;
		break;

	case L2F_TIFILES:
		l2_file->tifiles.hdr.flags = data;
		break;
	}
}

static uint8_t get_file_recsperphysrec(struct ti99_lvl2_fileref *l2_file)
{
	int reply = 0;

	switch (l2_file->type)
	{
	case L2F_DSK:
		reply = l2_file->dsk.fdr.recsperphysrec;
		break;

	case L2F_WIN:
		reply = l2_file->win.curfdr.recsperphysrec;
		break;

	case L2F_TIFILES:
		reply = l2_file->tifiles.hdr.recsperphysrec;
		break;
	}

	return reply;
}

static void set_file_recsperphysrec(struct ti99_lvl2_fileref *l2_file, uint8_t data)
{
	switch (l2_file->type)
	{
	case L2F_DSK:
		l2_file->dsk.fdr.recsperphysrec = data;
		break;

	case L2F_WIN:
		l2_file->win.curfdr.recsperphysrec = data;
		break;

	case L2F_TIFILES:
		l2_file->tifiles.hdr.recsperphysrec = data;
		break;
	}
}

static unsigned get_file_fphysrecs(struct ti99_lvl2_fileref *l2_file)
{
	int reply = 0;

	switch (l2_file->type)
	{
	case L2F_DSK:
		reply = get_UINT16BE(l2_file->dsk.fdr.fphysrecs);
		break;

	case L2F_WIN:
		reply = l2_file->win.fphysrecs;
		break;

	case L2F_TIFILES:
		reply = get_UINT16BE(l2_file->tifiles.hdr.fphysrecs);
		break;
	}

	return reply;
}

static int set_file_fphysrecs(struct ti99_lvl2_fileref *l2_file, unsigned data)
{
	switch (l2_file->type)
	{
	case L2F_DSK:
		if (data >= 65536)
			return IMGTOOLERR_UNIMPLEMENTED;
		set_UINT16BE(&l2_file->dsk.fdr.fphysrecs, data);
		break;

	case L2F_WIN:
		l2_file->win.fphysrecs = data;
		break;

	case L2F_TIFILES:
		if (data >= 65536)
			return IMGTOOLERR_UNIMPLEMENTED;
		set_UINT16BE(&l2_file->tifiles.hdr.fphysrecs, data);
		break;
	}

	return 0;
}

static uint8_t get_file_eof(struct ti99_lvl2_fileref *l2_file)
{
	int reply = 0;

	switch (l2_file->type)
	{
	case L2F_DSK:
		reply = l2_file->dsk.fdr.eof;
		break;

	case L2F_WIN:
		reply = l2_file->win.curfdr.eof;
		break;

	case L2F_TIFILES:
		reply = l2_file->tifiles.hdr.eof;
		break;
	}

	return reply;
}

static void set_file_eof(struct ti99_lvl2_fileref *l2_file, uint8_t data)
{
	switch (l2_file->type)
	{
	case L2F_DSK:
		l2_file->dsk.fdr.eof = data;
		break;

	case L2F_WIN:
		l2_file->win.curfdr.eof = data;
		break;

	case L2F_TIFILES:
		l2_file->tifiles.hdr.eof = data;
		break;
	}
}

static uint16_t get_file_reclen(struct ti99_lvl2_fileref *l2_file)
{
	int reply = 0;

	switch (l2_file->type)
	{
	case L2F_DSK:
		reply = l2_file->dsk.fdr.reclen;
		if ((reply == 0) && (! (l2_file->dsk.fdr.flags & (fdr99_f_program /*| fdr99_f_var*/))))
			reply = get_UINT16BE(l2_file->dsk.fdr.xreclen);
		break;

	case L2F_WIN:
		reply = l2_file->win.curfdr.reclen;
		if ((reply == 0) && (! (l2_file->win.curfdr.flags & (fdr99_f_program /*| fdr99_f_var*/))))
			reply = get_UINT16BE(l2_file->win.curfdr.xreclen);
		break;

	case L2F_TIFILES:
		reply = l2_file->tifiles.hdr.reclen;
		break;
	}

	return reply;
}

static int set_file_reclen(struct ti99_lvl2_fileref *l2_file, uint16_t data)
{
	switch (l2_file->type)
	{
	case L2F_DSK:
		if (data < 256)
		{
			l2_file->dsk.fdr.reclen = data;
			set_UINT16BE(&l2_file->dsk.fdr.xreclen, 0);
		}
		else
		{
			l2_file->dsk.fdr.reclen = 0;
			set_UINT16BE(&l2_file->dsk.fdr.xreclen, data);
		}
		break;

	case L2F_WIN:
		if (data < 256)
		{
			l2_file->win.curfdr.reclen = data;
			set_UINT16BE(&l2_file->win.curfdr.xreclen, 0);
		}
		else
		{
			l2_file->win.curfdr.reclen = 0;
			set_UINT16BE(&l2_file->win.curfdr.xreclen, data);
		}
		break;

	case L2F_TIFILES:
		if (data >= 256)
			return IMGTOOLERR_UNIMPLEMENTED;
		l2_file->tifiles.hdr.reclen = data;
		break;
	}

	return 0;
}

static unsigned get_file_fixrecs(struct ti99_lvl2_fileref *l2_file)
{
	int reply = 0;

	switch (l2_file->type)
	{
	case L2F_DSK:
		reply = get_UINT16LE(l2_file->dsk.fdr.fixrecs);
		break;

	case L2F_WIN:
		reply = get_win_fdr_fixrecs(&l2_file->win.curfdr);
		break;

	case L2F_TIFILES:
		reply = get_UINT16BE(l2_file->tifiles.hdr.fixrecs);
		break;
	}

	return reply;
}

static int set_file_fixrecs(struct ti99_lvl2_fileref *l2_file, unsigned data)
{
	switch (l2_file->type)
	{
	case L2F_DSK:
		if (data >= 65536)
			return IMGTOOLERR_UNIMPLEMENTED;
		set_UINT16LE(&l2_file->dsk.fdr.fixrecs, data);
		break;

	case L2F_WIN:
		set_win_fdr_fixrecs(&l2_file->win.curfdr, data);
		break;

	case L2F_TIFILES:
		if (data >= 65536)
			return IMGTOOLERR_UNIMPLEMENTED;
		set_UINT16BE(&l2_file->tifiles.hdr.fixrecs, data);
		break;
	}

	return 0;
}

static void get_file_creation_date(struct ti99_lvl2_fileref *l2_file, ti99_date_time *reply)
{
	switch (l2_file->type)
	{
	case L2F_DSK:
		*reply = l2_file->dsk.fdr.creation;
		break;

	case L2F_WIN:
		*reply = l2_file->win.curfdr.creation;
		break;

	case L2F_TIFILES:
		memset(reply, 0, sizeof(*reply));
		break;
	}
}

static void set_file_creation_date(struct ti99_lvl2_fileref *l2_file, ti99_date_time data)
{
	switch (l2_file->type)
	{
	case L2F_DSK:
		l2_file->dsk.fdr.creation = data;
		break;

	case L2F_WIN:
		l2_file->win.curfdr.creation = data;
		break;

	case L2F_TIFILES:
		break;
	}
}

static void get_file_update_date(struct ti99_lvl2_fileref *l2_file, ti99_date_time *reply)
{
	switch (l2_file->type)
	{
	case L2F_DSK:
		*reply = l2_file->dsk.fdr.update;
		break;

	case L2F_WIN:
		*reply = l2_file->win.curfdr.update;
		break;

	case L2F_TIFILES:
		memset(reply, 0, sizeof(*reply));
		break;
	}
}

static void set_file_update_date(struct ti99_lvl2_fileref *l2_file, ti99_date_time data)
{
	switch (l2_file->type)
	{
	case L2F_DSK:
		l2_file->dsk.fdr.update = data;
		break;

	case L2F_WIN:
		l2_file->win.curfdr.update = data;
		break;

	case L2F_TIFILES:
		break;
	}
}

[[maybe_unused]] static void current_date_time(ti99_date_time *reply)
{
	/* All these functions should be ANSI */
	time_t cur_time = time(nullptr);
	struct tm expanded_time = *localtime(& cur_time);

	reply->time_MSB = (expanded_time.tm_hour << 3) | (expanded_time.tm_min >> 3);
	reply->time_LSB = (expanded_time.tm_min << 5) | (expanded_time.tm_sec >> 1);
	reply->date_MSB = ((expanded_time.tm_year % 100) << 1) | ((expanded_time.tm_mon+1) >> 3);
	reply->date_LSB = ((expanded_time.tm_mon+1) << 5) | expanded_time.tm_mday;
}

#if 0
#pragma mark -
#pragma mark LEVEL 3 DISK ROUTINES
#endif

/*
    Level 3 implements files as a succession of logical records.

    There are three types of files:
    * program files that are not implemented at level 3 (no logical record)
    * files with fixed-size records (random-access files)
    * files with variable-size records (sequential-access)
*/

struct ti99_lvl3_fileref
{
	ti99_lvl2_fileref l2_file;

	int cur_log_rec;
	int cur_phys_rec;
	int cur_pos_in_phys_rec;
};

/*
    Open a file on level 3.

    To open a file on level 3, you must open (or create) the file on level 2,
    then pass the file reference to open_file_lvl3.
*/
[[maybe_unused]] static int open_file_lvl3(ti99_lvl3_fileref *l3_file)
{
	l3_file->cur_log_rec = 0;
	l3_file->cur_phys_rec = 0;
	l3_file->cur_pos_in_phys_rec = 0;

	/*if ()*/

	return 0;
}

/*
    Test a file for EOF
*/
static int is_eof(ti99_lvl3_fileref *l3_file)
{
	int flags = get_file_flags(&l3_file->l2_file);
	int fphysrecs = get_file_fphysrecs(&l3_file->l2_file);
	int fdr_eof = get_file_eof(&l3_file->l2_file);

	if (flags & fdr99_f_var)
	{
		return (l3_file->cur_phys_rec >= fphysrecs);
	}
	else
	{
		return ((l3_file->cur_phys_rec >= fphysrecs)
				|| ((l3_file->cur_phys_rec == (fphysrecs-1))
					&& (l3_file->cur_pos_in_phys_rec >= (fdr_eof ? fdr_eof : 256))));
	}
}

/*
    Read next record from a file
*/
[[maybe_unused]] static int read_next_record(ti99_lvl3_fileref *l3_file, void *dest, int *out_reclen)
{
	int errorcode;
	uint8_t physrec_buf[256];
	int reclen;
	int flags = get_file_flags(&l3_file->l2_file);
	int fphysrecs = get_file_fphysrecs(&l3_file->l2_file);
	int fdr_eof = get_file_eof(&l3_file->l2_file);

	if (flags & fdr99_f_program)
	{
		/* program files have no level-3 record */
		return IMGTOOLERR_UNEXPECTED;
	}
	else if (flags & fdr99_f_var)
	{
		/* variable-length records */
		if (is_eof(l3_file))
			return IMGTOOLERR_UNEXPECTED;
		errorcode = read_file_physrec(&l3_file->l2_file, l3_file->cur_phys_rec, physrec_buf);
		if (errorcode)
			return errorcode;
		/* read reclen */
		reclen = physrec_buf[l3_file->cur_pos_in_phys_rec];
		/* check integrity */
		if ((reclen == 0xff) || (reclen > get_file_reclen(&l3_file->l2_file))
				|| ((l3_file->cur_pos_in_phys_rec + 1 + reclen) > 256))
			return IMGTOOLERR_CORRUPTIMAGE;
		/* copy to buffer */
		memcpy(dest, physrec_buf + l3_file->cur_pos_in_phys_rec + 1, reclen);
		l3_file->cur_pos_in_phys_rec += reclen + 1;
		/* skip to next physrec if needed */
		if ((l3_file->cur_pos_in_phys_rec == 256)
				|| (physrec_buf[l3_file->cur_pos_in_phys_rec] == 0xff))
		{
			l3_file->cur_pos_in_phys_rec = 0;
			l3_file->cur_phys_rec++;
		}
		(* out_reclen) = reclen;
	}
	else
	{
		/* fixed len records */
		reclen = get_file_reclen(&l3_file->l2_file);
		if (is_eof(l3_file))
			return IMGTOOLERR_UNEXPECTED;
		if ((l3_file->cur_pos_in_phys_rec + reclen) > 256)
		{
			l3_file->cur_pos_in_phys_rec = 0;
			l3_file->cur_phys_rec++;
		}
		if ((l3_file->cur_phys_rec >= fphysrecs)
				|| ((l3_file->cur_phys_rec == (fphysrecs-1))
					&& ((l3_file->cur_pos_in_phys_rec + reclen) >= (fdr_eof ? fdr_eof : 256))))
			return IMGTOOLERR_CORRUPTIMAGE;
		errorcode = read_file_physrec(&l3_file->l2_file, l3_file->cur_phys_rec, physrec_buf);
		if (errorcode)
			return errorcode;
		memcpy(dest, physrec_buf + l3_file->cur_pos_in_phys_rec, reclen);
		l3_file->cur_pos_in_phys_rec += reclen;
		if (l3_file->cur_pos_in_phys_rec == 256)
		{
			l3_file->cur_pos_in_phys_rec = 0;
			l3_file->cur_phys_rec++;
		}
		(* out_reclen) = reclen;
	}

	return 0;
}

#if 0
#pragma mark -
#pragma mark IMGTOOL MODULE IMPLEMENTATION
#endif

/*
    ti99 catalog iterator, used when imgtool reads the catalog
*/
struct dsk_iterator
{
	struct ti99_lvl2_imgref *image;
	int level;
	int listing_subdirs;        /* true if we are listing subdirectories at current level */
	int index[2];               /* current index in the disk catalog */
	ti99_catalog *cur_catalog;  /* current catalog */
};

struct win_iterator
{
	struct ti99_lvl2_imgref *image;
	int level;
	int listing_subdirs;        /* true if we are listing subdirectories at current level */
	int index[MAX_DIR_LEVEL];   /* current index in the disk catalog */
	ti99_catalog catalog[MAX_DIR_LEVEL];    /* current catalog */
};


static imgtoolerr_t dsk_image_init_mess(imgtool::image &image, imgtool::stream::ptr &&stream);
static imgtoolerr_t dsk_image_init_v9t9(imgtool::image &image, imgtool::stream::ptr &&stream);
static imgtoolerr_t dsk_image_init_pc99_fm(imgtool::image &image, imgtool::stream::ptr &&stream);
static imgtoolerr_t dsk_image_init_pc99_mfm(imgtool::image &image, imgtool::stream::ptr &&stream);
static imgtoolerr_t win_image_init(imgtool::image &image, imgtool::stream::ptr &&stream);
static void ti99_image_exit(imgtool::image &img);
static void ti99_image_info(imgtool::image &img, std::ostream &stream);
static imgtoolerr_t dsk_image_beginenum(imgtool::directory &enumeration, const char *path);
static imgtoolerr_t dsk_image_nextenum(imgtool::directory &enumeration, imgtool_dirent &ent);
static imgtoolerr_t win_image_beginenum(imgtool::directory &enumeration, const char *path);
static imgtoolerr_t win_image_nextenum(imgtool::directory &enumeration, imgtool_dirent &ent);
static imgtoolerr_t ti99_image_freespace(imgtool::partition &partition, uint64_t *size);
static imgtoolerr_t ti99_image_readfile(imgtool::partition &partition, const char *fpath, const char *fork, imgtool::stream &destf);
static imgtoolerr_t ti99_image_writefile(imgtool::partition &partition, const char *fpath, const char *fork, imgtool::stream &sourcef, util::option_resolution *writeoptions);
static imgtoolerr_t dsk_image_deletefile(imgtool::partition &partition, const char *fpath);
static imgtoolerr_t win_image_deletefile(imgtool::partition &partition, const char *fpath);
static imgtoolerr_t dsk_image_create_mess(imgtool::image &image, imgtool::stream::ptr &&stream, util::option_resolution *createoptions);
static imgtoolerr_t dsk_image_create_v9t9(imgtool::image &image, imgtool::stream::ptr &&stream, util::option_resolution *createoptions);

enum
{
	dsk_createopts_volname = 'A',
	dsk_createopts_sides = 'B',
	dsk_createopts_tracks = 'C',
	dsk_createopts_sectors = 'D',
	dsk_createopts_protection = 'E',
	dsk_createopts_density = 'F'
};

OPTION_GUIDE_START( dsk_create_optionguide )
	OPTION_STRING(dsk_createopts_volname, "label",  "Volume name" )
	OPTION_INT(dsk_createopts_sides, "sides", "Sides" )
	OPTION_INT(dsk_createopts_tracks, "tracks", "Tracks" )
	OPTION_INT(dsk_createopts_sectors, "sectors",   "Sectors (1->9 for SD, 1->18 for DD, 1->36 for HD)" )
	OPTION_INT(dsk_createopts_protection, "protection", "Protection (0 for normal, 1 for protected)" )
	OPTION_ENUM_START(dsk_createopts_density, "density", "Density" )
		OPTION_ENUM(    0,      "Auto",             "Auto" )
		OPTION_ENUM(    1,      "SD",               "Single Density" )
		OPTION_ENUM(    2,      "DD",               "Double Density" )
		OPTION_ENUM(    3,      "HD",               "High Density" )
	OPTION_ENUM_END
OPTION_GUIDE_END

#define dsk_create_optionspecs "B1-[2];C1-[40]-80;D1-[18]-36;E[0]-1;F[0]-3"

static void ti99_getinfo(const imgtool_class *imgclass, uint32_t state, union imgtoolinfo *info)
{
	switch(state)
	{
		case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:             info->i = sizeof(ti99_lvl2_imgref); break;
		case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:             info->i = sizeof(dsk_iterator); break;

		case IMGTOOLINFO_STR_EOLN:                          strcpy(info->s = imgtool_temp_str(), "\r"); break;
		case IMGTOOLINFO_PTR_CLOSE:                         info->close = ti99_image_exit; break;
		case IMGTOOLINFO_PTR_INFO:                          info->info = ti99_image_info; break;
		case IMGTOOLINFO_PTR_FREE_SPACE:                    info->free_space = ti99_image_freespace; break;
		case IMGTOOLINFO_PTR_READ_FILE:                     info->read_file = ti99_image_readfile; break;
		case IMGTOOLINFO_PTR_WRITE_FILE:                    info->write_file = ti99_image_writefile; break;
	}
}

static void ti99_dsk_getinfo(const imgtool_class *imgclass, uint32_t state, union imgtoolinfo *info)
{
	switch(state)
	{
		case IMGTOOLINFO_STR_FILE_EXTENSIONS:               strcpy(info->s = imgtool_temp_str(), "dsk"); break;
		case IMGTOOLINFO_PTR_BEGIN_ENUM:                    info->begin_enum = dsk_image_beginenum; break;
		case IMGTOOLINFO_PTR_NEXT_ENUM:                     info->next_enum = dsk_image_nextenum; break;
		case IMGTOOLINFO_PTR_DELETE_FILE:                   info->delete_file = dsk_image_deletefile; break;
		default:                                            ti99_getinfo(imgclass, state, info);
	}
}

void ti99_old_get_info(const imgtool_class *imgclass, uint32_t state, union imgtoolinfo *info)
{
	switch(state)
	{
		case IMGTOOLINFO_STR_NAME:                  strcpy(info->s = imgtool_temp_str(), "ti99_old"); break;
		case IMGTOOLINFO_STR_DESCRIPTION:           strcpy(info->s = imgtool_temp_str(), "TI99 Diskette (old MESS format)"); break;
		case IMGTOOLINFO_PTR_OPEN:                  info->open = dsk_image_init_mess; break;
		case IMGTOOLINFO_PTR_CREATE:                info->create = dsk_image_create_mess; break;
		case IMGTOOLINFO_PTR_CREATEIMAGE_OPTGUIDE:  info->createimage_optguide = &dsk_create_optionguide; break;
		case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:   strcpy(info->s = imgtool_temp_str(), dsk_create_optionspecs); break;
		default:                                    ti99_dsk_getinfo(imgclass, state, info); break;
	}
}

void ti99_v9t9_get_info(const imgtool_class *imgclass, uint32_t state, union imgtoolinfo *info)
{
	switch(state)
	{
		case IMGTOOLINFO_STR_NAME:                  strcpy(info->s = imgtool_temp_str(), "v9t9"); break;
		case IMGTOOLINFO_STR_DESCRIPTION:           strcpy(info->s = imgtool_temp_str(), "TI99 Diskette (V9T9 format)"); break;
		case IMGTOOLINFO_PTR_OPEN:                  info->open = dsk_image_init_v9t9; break;
		case IMGTOOLINFO_PTR_CREATE:                info->create = dsk_image_create_v9t9; break;
		case IMGTOOLINFO_PTR_CREATEIMAGE_OPTGUIDE:  info->createimage_optguide = &dsk_create_optionguide; break;
		case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:   strcpy(info->s = imgtool_temp_str(), dsk_create_optionspecs); break;
		default:                                    ti99_dsk_getinfo(imgclass, state, info); break;
	}
}

void ti99_pc99fm_get_info(const imgtool_class *imgclass, uint32_t state, union imgtoolinfo *info)
{
	switch(state)
	{
		case IMGTOOLINFO_STR_NAME:                  strcpy(info->s = imgtool_temp_str(), "pc99fm"); break;
		case IMGTOOLINFO_STR_DESCRIPTION:           strcpy(info->s = imgtool_temp_str(), "TI99 Diskette (PC99 FM format)"); break;
		case IMGTOOLINFO_PTR_OPEN:                  info->open = dsk_image_init_pc99_fm; break;
		case IMGTOOLINFO_PTR_CREATE:                /* info->create = dsk_image_create_pc99fm; */ break;
		default:                                    ti99_dsk_getinfo(imgclass, state, info); break;
	}
}

void ti99_pc99mfm_get_info(const imgtool_class *imgclass, uint32_t state, union imgtoolinfo *info)
{
	switch(state)
	{
		case IMGTOOLINFO_STR_NAME:                  strcpy(info->s = imgtool_temp_str(), "pc99mfm"); break;
		case IMGTOOLINFO_STR_DESCRIPTION:           strcpy(info->s = imgtool_temp_str(), "TI99 Diskette (PC99 MFM format)"); break;
		case IMGTOOLINFO_PTR_OPEN:                  info->open = dsk_image_init_pc99_mfm; break;
		case IMGTOOLINFO_PTR_CREATE:                /* info->create = dsk_image_create_pc99mfm; */ break;
		default:                                    ti99_dsk_getinfo(imgclass, state, info); break;
	}
}

void ti99_ti99hd_get_info(const imgtool_class *imgclass, uint32_t state, union imgtoolinfo *info)
{
	switch(state)
	{
		case IMGTOOLINFO_STR_NAME:                  strcpy(info->s = imgtool_temp_str(), "ti99hd"); break;
		case IMGTOOLINFO_STR_DESCRIPTION:           strcpy(info->s = imgtool_temp_str(), "TI99 Harddisk"); break;
		case IMGTOOLINFO_PTR_OPEN:                  info->open = win_image_init; break;
		case IMGTOOLINFO_PTR_CREATE:                /* info->create = hd_image_create; */ break;

		case IMGTOOLINFO_STR_FILE_EXTENSIONS:       strcpy(info->s = imgtool_temp_str(), "hd"); break;
		case IMGTOOLINFO_PTR_BEGIN_ENUM:            info->begin_enum = win_image_beginenum; break;
		case IMGTOOLINFO_PTR_NEXT_ENUM:             info->next_enum = win_image_nextenum; break;
		case IMGTOOLINFO_PTR_DELETE_FILE:           info->delete_file = win_image_deletefile; break;
		default:                                    ti99_getinfo(imgclass, state, info);
	}
}



/*
    Open a file as a ti99_image (common code).
*/
static imgtoolerr_t dsk_image_init(imgtool::image &img, imgtool::stream::ptr &&stream, ti99_img_format img_format)
{
	struct ti99_lvl2_imgref *image = get_lvl2_imgref(img);
	dsk_vib vib;
	imgtoolerr_t reply;
	int totphysrecs;
	unsigned fdir_aphysrec;
	int i;

	/* open disk image at level 1 */
	reply = open_image_lvl1(std::move(stream), img_format, &image->l1_img, &vib);
	if (reply)
		return reply;

	/* open disk image at level 2 */
	image->type = L2I_DSK;

	/* @BN@ */
	/* Copy in the allocation bit map! */
	memcpy(image->abm, vib.abm, 200);
	/* first compute AU size and number of AUs */
	totphysrecs = get_UINT16BE(vib.totphysrecs);

	image->AUformat.physrecsperAU = (totphysrecs + 1599) / 1600;
	/* round to next larger power of 2 */
	for (i = 1; i < image->AUformat.physrecsperAU; i <<= 1)
		;
	image->AUformat.physrecsperAU = i;
	image->AUformat.totAUs = totphysrecs / image->AUformat.physrecsperAU;

	/* extract number of physrecs */
	image->dsk.totphysrecs = get_UINT16BE(vib.totphysrecs);

	/* read and check main volume catalog */
	reply = (imgtoolerr_t)dsk_read_catalog(image, 1, &image->dsk.catalogs[0]);
	if (reply)
		return reply;

	image->dsk.fdir_aphysrec[0] = 1;

	/* read and check subdirectory catalogs */
	/* Note that the reserved areas used for HFDC subdirs may be used for other
	purposes by other FDRs, so, if we get any error, we will assume there is no
	subdir after all... */
	image->dsk.catalogs[0].num_subdirs = 0;
	for (i=0; i<3; i++)
	{
		fdir_aphysrec = get_UINT16BE(vib.subdir[i].fdir_aphysrec);
		if ((! memcmp(vib.subdir[i].name, "\0\0\0\0\0\0\0\0\0\0", 10))
				|| (! memcmp(vib.subdir[i].name, "          ", 10)))
		{
			/* name is empty: fine with us unless there is a fdir pointer */
			if (fdir_aphysrec != 0)
			{
				image->dsk.catalogs[0].num_subdirs = 0;
				break;
			}
		}
		else if (check_fname(vib.subdir[i].name))
		{
			/* name is invalid: this is not an HFDC format floppy */
			image->dsk.catalogs[0].num_subdirs = 0;
			break;
		}
		else
		{
			/* there is a non-empty name */
			if ((fdir_aphysrec == 0) || (fdir_aphysrec >= totphysrecs))
			{
				/* error: fdir pointer is invalid or NULL */
				image->dsk.catalogs[0].num_subdirs = 0;
				break;
			}
			/* fill in descriptor fields */
			image->dsk.fdir_aphysrec[image->dsk.catalogs[0].num_subdirs+1] = fdir_aphysrec;
			/*image->dsk.catalogs[0].subdirs[image->dsk.catalogs[0].num_subdirs].dir_ptr = fdir_aphysrec;*/
			memcpy(image->dsk.catalogs[0].subdirs[image->dsk.catalogs[0].num_subdirs].name, vib.subdir[i].name, 10);
			reply = (imgtoolerr_t) dsk_read_catalog(image, fdir_aphysrec, &image->dsk.catalogs[image->dsk.catalogs[0].num_subdirs+1]);
			if (reply)
			{
				/* error: invalid fdir */
				image->dsk.catalogs[0].num_subdirs = 0;
				break;
			}
			/* found valid subdirectory: increment subdir count */
			image->dsk.catalogs[0].num_subdirs++;
		}
	}

	/* extract volume name */
	memcpy(image->vol_name, vib.name, 10);

	/* initialize default data_offset */
	image->data_offset = 32+2;

	return (imgtoolerr_t)0;
}

/*
    Open a file as a ti99_image (MESS format).
*/
static imgtoolerr_t dsk_image_init_mess(imgtool::image &image, imgtool::stream::ptr &&stream)
{
	return dsk_image_init(image, std::move(stream), if_mess);
}

/*
    Open a file as a ti99_image (V9T9 format).
*/
static imgtoolerr_t dsk_image_init_v9t9(imgtool::image &image, imgtool::stream::ptr &&stream)
{
	return dsk_image_init(image, std::move(stream), if_v9t9);
}

/*
    Open a file as a ti99_image (PC99 FM format).
*/
static imgtoolerr_t dsk_image_init_pc99_fm(imgtool::image &image, imgtool::stream::ptr &&stream)
{
	return dsk_image_init(image, std::move(stream), if_pc99_fm);
}

/*
    Open a file as a ti99_image (PC99 MFM format).
*/
static imgtoolerr_t dsk_image_init_pc99_mfm(imgtool::image &image, imgtool::stream::ptr &&stream)
{
	return dsk_image_init(image, std::move(stream), if_pc99_mfm);
}

/*
    Open a file as a ti99_image (harddisk format).
*/
static imgtoolerr_t win_image_init(imgtool::image &img, imgtool::stream::ptr &&stream)
{
	struct ti99_lvl2_imgref *image = get_lvl2_imgref(img);
	win_vib_ddr vib;
	int reply;
	int i;

	/* open disk image at level 1 */
	reply = open_image_lvl1(std::move(stream), if_harddisk, & image->l1_img, NULL);
	if (reply)
		return (imgtoolerr_t)reply;

	/* open disk image at level 2 */
	image->type = L2I_WIN;

	/* read VIB */
	reply = read_absolute_physrec(&image->l1_img, 0, &vib);
	if (reply)
		return (imgtoolerr_t)reply;

	/* guess VIB version */
	image->win.vib_version = memcmp(vib.u.vib_v1.id, "WIN", 3) ? win_vib_v2 : win_vib_v1;

	/* extract AU size and number of AUs */
	image->AUformat.physrecsperAU = ((get_UINT16BE(vib.params) >> 12) & 0xf) + 1;
	image->AUformat.totAUs = get_UINT16BE(vib.totAUs);

	/* extract volume name */
	memcpy(image->vol_name, vib.name, 10);

	/* extract data_offset */
	switch (image->win.vib_version)
	{
	case win_vib_v1:
		image->data_offset = 64;
		break;

	case win_vib_v2:
		image->data_offset = vib.u.vib_v2.res_AUs * 64;
		break;
	}

	/* read allocation bitmap (aphysrecs 1 through n, n<=33) */
	for (i=0; i < (image->AUformat.totAUs+2047)/2048; i++)
	{
		reply = read_absolute_physrec(&image->l1_img, i+1, image->abm+i*256);
		if (reply)
			return (imgtoolerr_t)reply;
	}

	return (imgtoolerr_t)0;
}

/*
    close a ti99_image
*/
static void ti99_image_exit(imgtool::image &img)
{
	struct ti99_lvl2_imgref *image = get_lvl2_imgref(img);

	close_image_lvl1(&image->l1_img);
}

/*
    get basic information on a ti99_image

    Currently returns the volume name
*/
static void ti99_image_info(imgtool::image &img, std::ostream &stream)
{
	struct ti99_lvl2_imgref *image = get_lvl2_imgref(img);
	char vol_name[11];

	fname_to_str(vol_name, image->vol_name, 11);

	stream << vol_name;
}

/*
    Open the disk catalog for enumeration
*/
static imgtoolerr_t dsk_image_beginenum(imgtool::directory &enumeration, const char *path)
{
	struct ti99_lvl2_imgref *image = get_lvl2_imgref(enumeration.image());
	dsk_iterator *iter = (dsk_iterator *) enumeration.extra_bytes();

	iter->image = image;
	iter->level = 0;
	iter->listing_subdirs = 1;
	iter->index[0] = 0;
	iter->cur_catalog = &iter->image->dsk.catalogs[0];

	return (imgtoolerr_t)0;
}

/*
    Enumerate disk catalog next entry
*/
static imgtoolerr_t dsk_image_nextenum(imgtool::directory &enumeration, imgtool_dirent &ent)
{
	dsk_iterator *iter = (dsk_iterator*) enumeration.extra_bytes();
	dsk_fdr fdr;
	int reply;
	unsigned fdr_aphysrec;


	ent.corrupt = 0;
	ent.eof = 0;

	/* iterate through catalogs to next file or dir entry */
	while ((iter->level >= 0)
			&& (iter->index[iter->level] >= (iter->listing_subdirs
												? iter->cur_catalog->num_subdirs
												: iter->cur_catalog->num_files)))
	{
		if (iter->listing_subdirs)
		{
			iter->listing_subdirs = 0;
			iter->index[iter->level] = 0;
		}
		else
		{
			iter->listing_subdirs = 1;
			if (! iter->level)
				iter->level = -1;
			else
			{
				iter->level = 0;
				iter->index[0]++;
				iter->cur_catalog = &iter->image->dsk.catalogs[0];
			}
		}
	}

	if (iter->level < 0)
	{
		ent.eof = 1;
	}
	else
	{
		if (iter->listing_subdirs)
		{
			fname_to_str(ent.filename, iter->image->dsk.catalogs[0].subdirs[iter->index[iter->level]].name, std::size(ent.filename));

			/* set type of DIR */
			snprintf(ent.attr, std::size(ent.attr), "DIR");

			/* len in physrecs */
			/* @BN@ return length in bytes */
			/* ent.filesize = 1; */
			ent.filesize = 256;

			/* recurse subdirectory */
			iter->listing_subdirs = 0;  /* no need to list subdirs as only the
			                            root dir has subdirs in DSK format */
			iter->level = 1;
			iter->cur_catalog = &iter->image->dsk.catalogs[iter->index[0]+1];
			iter->index[iter->level] = 0;
		}
		else
		{
			fdr_aphysrec = iter->cur_catalog->files[iter->index[iter->level]].fdr_ptr;
			reply = read_absolute_physrec(& iter->image->l1_img, fdr_aphysrec, & fdr);
			if (reply)
				return IMGTOOLERR_READERROR;
#if 0
			fname_to_str(ent.filename, fdr.name, std::size(ent.filename));
#else
			{
				char buf[11];

				ent.filename[0] = '\0';
				if (iter->level)
				{
					fname_to_str(ent.filename, iter->image->dsk.catalogs[0].subdirs[iter->index[0]].name, std::size(ent.filename));
					strncat(ent.filename, ".", std::size(ent.filename) - 1);
				}
				fname_to_str(buf, fdr.name, 11);
				strncat(ent.filename, buf, std::size(ent.filename) - 1);
			}
#endif
			/* parse flags */
			if (fdr.flags & fdr99_f_program)
				snprintf(ent.attr, std::size(ent.attr), "PGM%s",
							(fdr.flags & fdr99_f_wp) ? " R/O" : "");
			else
				snprintf(ent.attr, std::size(ent.attr), "%c/%c %d%s",
							(fdr.flags & fdr99_f_int) ? 'I' : 'D',
							(fdr.flags & fdr99_f_var) ? 'V' : 'F',
							fdr.reclen,
							(fdr.flags & fdr99_f_wp) ? " R/O" : "");
			/* len in physrecs */
			/* @BN@ return length in bytes */
			/* ent.filesize = get_UINT16BE(fdr.fphysrecs); */
			ent.filesize = (get_UINT16BE(fdr.fphysrecs)+1)*256;

			iter->index[iter->level]++;
		}
	}

	return (imgtoolerr_t)0;
}

/*
    Open the disk catalog for enumeration
*/
static imgtoolerr_t win_image_beginenum(imgtool::directory &enumeration, const char *path)
{
	struct ti99_lvl2_imgref *image = get_lvl2_imgref(enumeration.image());
	win_iterator *iter = (win_iterator *) enumeration.extra_bytes();
	imgtoolerr_t errorcode;

	iter->image = image;
	iter->level = 0;
	iter->listing_subdirs = 1;
	iter->index[0] = 0;
	errorcode = (imgtoolerr_t)win_read_catalog(image, 0, &iter->catalog[0]);
	if (errorcode)
		return errorcode;

	return (imgtoolerr_t)0;
}

/*
    Enumerate disk catalog next entry
*/
static imgtoolerr_t win_image_nextenum(imgtool::directory &enumeration, imgtool_dirent &ent)
{
	win_iterator *iter = (win_iterator *) enumeration.extra_bytes();
	unsigned fdr_aphysrec;
	win_fdr fdr;
	int reply;
	int i;


	ent.corrupt = 0;
	ent.eof = 0;

	/* iterate through catalogs to next file or dir entry */
	while ((iter->level >= 0)
			&& (iter->index[iter->level] >= (iter->listing_subdirs
												? iter->catalog[iter->level].num_subdirs
												: iter->catalog[iter->level].num_files)))
	{
		if (iter->listing_subdirs)
		{
			iter->listing_subdirs = 0;
			iter->index[iter->level] = 0;
		}
		else
		{
			iter->listing_subdirs = 1;
			iter->level--;
			iter->index[iter->level]++;
		}
	}

	if (iter->level < 0)
	{
		ent.eof = 1;
	}
	else
	{
		if (iter->listing_subdirs)
		{
#if 0
			fname_to_str(ent.filename, iter->catalog[iter->level].subdirs[iter->index[iter->level]].name, std::size(ent.filename));
#else
			{
				char buf[11];

				ent.filename[0] = '\0';
				for (i=0; i<iter->level; i++)
				{
					fname_to_str(buf, iter->catalog[i].subdirs[iter->index[i]].name, 11);
					strncat(ent.filename, buf, std::size(ent.filename) - 1);
					strncat(ent.filename, ".", std::size(ent.filename) - 1);
				}
				fname_to_str(buf, iter->catalog[iter->level].subdirs[iter->index[iter->level]].name, 11);
				strncat(ent.filename, buf, std::size(ent.filename) - 1);
			}
#endif

			/* set type of DIR */
			snprintf(ent.attr, std::size(ent.attr), "DIR");

			/* len in physrecs */
			/* @BN@ return length in bytes */
			/* ent.filesize = 2; */
			ent.filesize = 512;

			/* recurse subdirectory */
			/*iter->listing_subdirs = 1;*/
			iter->level++;
			iter->index[iter->level] = 0;
			reply = win_read_catalog(iter->image, iter->catalog[iter->level-1].subdirs[iter->index[iter->level-1]].dir_ptr, &iter->catalog[iter->level]);
			if (reply)
			{
				ent.corrupt = 1;
				return (imgtoolerr_t)reply;
			}
		}
		else
		{
			fdr_aphysrec = iter->catalog[iter->level].files[iter->index[iter->level]].fdr_ptr*iter->image->AUformat.physrecsperAU;
			reply = read_absolute_physrec(& iter->image->l1_img, fdr_aphysrec, & fdr);
			if (reply)
				return IMGTOOLERR_READERROR;
#if 0
			fname_to_str(ent.filename, iter->catalog[iter->level].files[iter->index[iter->level]].name, std::size(ent.filename));
#else
			{
				char buf[11];

				ent.filename[0] = '\0';
				for (i=0; i<iter->level; i++)
				{
					fname_to_str(buf, iter->catalog[i].subdirs[iter->index[i]].name, 11);
					strncat(ent.filename, buf, std::size(ent.filename) - 1);
					strncat(ent.filename, ".", std::size(ent.filename) - 1);
				}
				fname_to_str(buf, iter->catalog[iter->level].files[iter->index[iter->level]].name, 11);
				strncat(ent.filename, buf, std::size(ent.filename) - 1);
			}
#endif
			/* parse flags */
			if (fdr.flags & fdr99_f_program)
				snprintf(ent.attr, std::size(ent.attr), "PGM%s",
							(fdr.flags & fdr99_f_wp) ? " R/O" : "");
			else
				snprintf(ent.attr, std::size(ent.attr), "%c/%c %d%s",
							(fdr.flags & fdr99_f_int) ? 'I' : 'D',
							(fdr.flags & fdr99_f_var) ? 'V' : 'F',
							fdr.reclen,
							(fdr.flags & fdr99_f_wp) ? " R/O" : "");
			/* len in physrecs */
			/* @BN@ return length in bytes */
			/* ent.filesize = get_win_fdr_fphysrecs(&fdr); */
			ent.filesize = (get_win_fdr_fphysrecs(&fdr)+1)*256;

			iter->index[iter->level]++;
		}
	}

	return (imgtoolerr_t)0;
}

/*
    Compute free space on disk image (in AUs)
*/
static imgtoolerr_t ti99_image_freespace(imgtool::partition &partition, uint64_t *size)
{
	imgtool::image &img(partition.image());
	struct ti99_lvl2_imgref *image = get_lvl2_imgref(img);
	size_t freeAUs;
	int i;

	freeAUs = 0;
	for (i=0; i<image->AUformat.totAUs; i++)
	{
		if (! (image->abm[i >> 3] & (1 << (i & 7))))
			freeAUs++;
	}

	/* @BN@ return free space in bytes */
	/*    *size = freeAUs; */
	*size = freeAUs*256;

	return IMGTOOLERR_SUCCESS;
}

/*
    Extract a file from a ti99_image.  The file is saved in tifile format.
*/
static imgtoolerr_t ti99_image_readfile(imgtool::partition &partition, const char *fpath, const char *fork, imgtool::stream &destf)
{
	imgtool::image &img(partition.image());
#if 1

	/* extract data as TIFILES */
	struct ti99_lvl2_imgref *image = get_lvl2_imgref(img);
	ti99_lvl2_fileref src_file;
	ti99_lvl2_fileref dst_file;
	ti99_date_time date_time;
	int fphysrecs;
	int i;
	uint8_t buf[256];
	imgtoolerr_t errorcode;


	if (check_fpath(fpath))
		return IMGTOOLERR_BADFILENAME;

	/* open file on TI image */
	switch (image->type)
	{
	case L2I_DSK:
		errorcode = (imgtoolerr_t)open_file_lvl2_dsk(image, fpath, &src_file);
		break;

	case L2I_WIN:
		errorcode = (imgtoolerr_t)open_file_lvl2_win(image, fpath, &src_file);
		break;

	default:
		errorcode = (imgtoolerr_t)-1;
		break;
	}
	if (errorcode)
		return errorcode;

	errorcode = (imgtoolerr_t)new_file_lvl2_tifiles(destf, &dst_file);
	if (errorcode)
		return errorcode;

	/* write TIFILE header */
	/* set up parameters */
	set_file_flags(&dst_file, get_file_flags(&src_file));
	set_file_recsperphysrec(&dst_file, get_file_recsperphysrec(&src_file));
	errorcode = (imgtoolerr_t)set_file_fphysrecs(&dst_file, get_file_fphysrecs(&src_file));
	if (errorcode)
		return errorcode;
	set_file_eof(&dst_file, get_file_eof(&src_file));
	errorcode = (imgtoolerr_t)set_file_reclen(&dst_file, get_file_reclen(&src_file));
	if (errorcode)
		return errorcode;
	errorcode = (imgtoolerr_t)set_file_fixrecs(&dst_file, get_file_fixrecs(&src_file));
	if (errorcode)
		return errorcode;

	get_file_creation_date(&src_file, &date_time);
#if 0
	if ((date_time.time_MSB == 0) || (date_time.time_LSB == 0)
			|| (date_time.date_MSB == 0) || (date_time.date_LSB == 0))
		current_date_time(&date_time);
#endif
	set_file_creation_date(&dst_file, date_time);

	get_file_update_date(&src_file, &date_time);
#if 0
	if ((date_time.time_MSB == 0) || (date_time.time_LSB == 0)
			|| (date_time.date_MSB == 0) || (date_time.date_LSB == 0))
		current_date_time(&date_time);
#endif
	set_file_update_date(&dst_file, date_time);

	if (destf.write(& dst_file.tifiles.hdr, 128) != 128)
		return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;

	/* copy data to TIFILE */
	fphysrecs = get_file_fphysrecs(&src_file);

	for (i=0; i<fphysrecs; i++)
	{
		errorcode = (imgtoolerr_t)read_file_physrec(& src_file, i, buf);
		if (errorcode)
			return errorcode;

		errorcode = (imgtoolerr_t)write_file_physrec(& dst_file, i, buf);
		if (errorcode)
			return errorcode;
	}

	return (imgtoolerr_t)0;

#else

	struct ti99_lvl2_imgref *image = get_lvl2_imgref(img);
	ti99_lvl3_fileref src_file;
	uint8_t buf[256];
	int reclen;
	char lineend = '\r';
	int errorcode;


	if (check_fpath(fpath))
		return IMGTOOLERR_BADFILENAME;

	/* open file on TI image */
	switch (image->type)
	{
	case L2I_DSK:
		errorcode = open_file_lvl2_dsk(image, fpath, &src_file.l2_file);
		break;

	case L2I_WIN:
		errorcode = open_file_lvl2_win(image, fpath, &src_file.l2_file);
		break;
	}
	if (errorcode)
		return errorcode;

	errorcode = open_file_lvl3(& src_file);
	if (errorcode)
		return errorcode;

	/* write text data */
	while (! is_eof(& src_file))
	{
		errorcode = read_next_record(& src_file, buf, & reclen);
		if (errorcode)
			return errorcode;
		if (destf.write(buf, reclen) != reclen)
			return IMGTOOLERR_WRITEERROR;
		if (destf.write(&lineend, 1) != 1)
			return IMGTOOLERR_WRITEERROR;
	}

	return 0;

#endif
}

/*
    Add a file to a ti99_image.  The file must be in tifile format.
*/
static imgtoolerr_t ti99_image_writefile(imgtool::partition &partition, const char *fpath, const char *fork, imgtool::stream &sourcef, util::option_resolution *writeoptions)
{
	imgtool::image &img(partition.image());
	struct ti99_lvl2_imgref *image = get_lvl2_imgref(img);
	const char *filename;
	char ti_fname[10];
	ti99_lvl2_fileref src_file;
	ti99_lvl2_fileref dst_file;
	ti99_date_time date_time;
	int i;
	int fphysrecs;
	uint8_t buf[256];
	imgtoolerr_t errorcode;
	int parent_ref_valid, parent_ref = 0;
	ti99_catalog *catalog, catalog_buf = {0, };


	(void) writeoptions;

	if (check_fpath(fpath))
		return IMGTOOLERR_BADFILENAME;

	switch (image->type)
	{
	case L2I_DSK:
		errorcode = (imgtoolerr_t)dsk_find_catalog_entry(image, fpath, &parent_ref_valid, &parent_ref, NULL, NULL);
		if (errorcode == 0)
			/* file already exists: causes an error for now */
			return (imgtoolerr_t)IMGTOOLERR_UNEXPECTED;
		else if ((! parent_ref_valid) || (errorcode != IMGTOOLERR_FILENOTFOUND))
			return (imgtoolerr_t)errorcode;
		break;

	case L2I_WIN:
		errorcode = (imgtoolerr_t)win_find_catalog_entry(image, fpath, &parent_ref_valid, &parent_ref, &catalog_buf, NULL, NULL);
		if (errorcode == 0)
			/* file already exists: causes an error for now */
			return (imgtoolerr_t)IMGTOOLERR_UNEXPECTED;
		else if ((! parent_ref_valid) || (errorcode != IMGTOOLERR_FILENOTFOUND))
			return (imgtoolerr_t)errorcode;
		break;
	}

	errorcode =(imgtoolerr_t) open_file_lvl2_tifiles(sourcef, & src_file);
	if (errorcode)
		return (imgtoolerr_t)errorcode;

	/* create new file */
	filename = strrchr(fpath, '.');
	if (filename)
		filename++;
	else
		filename = fpath;
	str_to_fname(ti_fname, filename);
	switch (image->type)
	{
	case L2I_DSK:
		errorcode = (imgtoolerr_t)new_file_lvl2_dsk(image, parent_ref, ti_fname, &dst_file);
		if (errorcode)
			return (imgtoolerr_t)errorcode;
		break;

	case L2I_WIN:
		errorcode = (imgtoolerr_t)new_file_lvl2_win(image, &catalog_buf, ti_fname, &dst_file);
		if (errorcode)
			return (imgtoolerr_t)errorcode;
		break;
	}

	/* set up parameters */
	set_file_flags(&dst_file, get_file_flags(&src_file));
	set_file_recsperphysrec(&dst_file, get_file_recsperphysrec(&src_file));
	errorcode = (imgtoolerr_t)set_file_fphysrecs(&dst_file, /*get_file_fphysrecs(&src_file)*/0);
	if (errorcode)
		return (imgtoolerr_t)errorcode;
	set_file_eof(&dst_file, get_file_eof(&src_file));
	errorcode = (imgtoolerr_t)set_file_reclen(&dst_file, get_file_reclen(&src_file));
	if (errorcode)
		return (imgtoolerr_t)errorcode;
	errorcode = (imgtoolerr_t)set_file_fixrecs(&dst_file, get_file_fixrecs(&src_file));
	if (errorcode)
		return (imgtoolerr_t)errorcode;

	get_file_creation_date(&src_file, &date_time);
#if 0
	if ((date_time.time_MSB == 0) || (date_time.time_LSB == 0)
			|| (date_time.date_MSB == 0) || (date_time.date_LSB == 0))
		current_date_time(&date_time);
#endif
	set_file_creation_date(&dst_file, date_time);

	get_file_update_date(&src_file, &date_time);
#if 0
	if ((date_time.time_MSB == 0) || (date_time.time_LSB == 0)
			|| (date_time.date_MSB == 0) || (date_time.date_LSB == 0))
		current_date_time(&date_time);
#endif
	set_file_update_date(&dst_file, date_time);

	/* alloc data physrecs */
	fphysrecs = get_file_fphysrecs(&src_file);
	switch (dst_file.type)
	{
	case L2F_DSK:
		errorcode = (imgtoolerr_t)dsk_alloc_file_physrecs(&dst_file.dsk, fphysrecs);
		if (errorcode)
			return (imgtoolerr_t)errorcode;
		break;

	case L2F_WIN:
		errorcode = (imgtoolerr_t)win_alloc_file_physrecs(&dst_file.win, fphysrecs);
		if (errorcode)
			return (imgtoolerr_t)errorcode;
		break;

	case L2F_TIFILES:
		break;
	}

	/* copy data */
	for (i=0; i<fphysrecs; i++)
	{
		if (sourcef.read(buf, 256) != 256)
			return (imgtoolerr_t)IMGTOOLERR_READERROR;

		errorcode = (imgtoolerr_t)write_file_physrec(& dst_file, i, buf);
		if (errorcode)
			return (imgtoolerr_t)errorcode;
	}

	/* write fdr */
	switch (image->type)
	{
	case L2I_DSK:
		if (write_absolute_physrec(& image->l1_img, dst_file.dsk.fdr_aphysrec, &dst_file.dsk.fdr))
			return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;
		break;

	case L2I_WIN:
		/* save fphysrecs field as well */
		if (dst_file.win.curfdr_aphysrec == dst_file.win.eldestfdr_aphysrec)
			set_win_fdr_fphysrecs(&dst_file.win.curfdr, dst_file.win.fphysrecs);
		if (write_absolute_physrec(& image->l1_img, dst_file.win.curfdr_aphysrec, &dst_file.win.curfdr))
			return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;
		if (dst_file.win.curfdr_aphysrec != dst_file.win.eldestfdr_aphysrec)
		{
			dst_file.win.curfdr_aphysrec = dst_file.win.eldestfdr_aphysrec;
			if (read_absolute_physrec(& image->l1_img, dst_file.win.curfdr_aphysrec, &dst_file.win.curfdr))
				return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;
			set_win_fdr_fphysrecs(&dst_file.win.curfdr, dst_file.win.fphysrecs);
			if (write_absolute_physrec(& image->l1_img, dst_file.win.curfdr_aphysrec, &dst_file.win.curfdr))
				return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;
		}
		break;
	}

	/* update catalog */
	switch (image->type)
	{
	case L2I_DSK:
		catalog = &image->dsk.catalogs[parent_ref];
		for (i=0; i<128; i++)
		{
			buf[2*i] = catalog->files[i].fdr_ptr >> 8;
			buf[2*i+1] = catalog->files[i].fdr_ptr & 0xff;
		}
		if (write_absolute_physrec(& image->l1_img, image->dsk.fdir_aphysrec[parent_ref], buf))
			return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;
		break;

	case L2I_WIN:
		{
			win_vib_ddr parent_ddr;
			int fdir_AU;

			/* update VIB/DDR and get FDIR AU address */
			if (read_absolute_physrec(& image->l1_img, parent_ref * image->AUformat.physrecsperAU, &parent_ddr))
				return (imgtoolerr_t)IMGTOOLERR_READERROR;
			parent_ddr.num_files = catalog_buf.num_files;
			if (write_absolute_physrec(& image->l1_img, parent_ref * image->AUformat.physrecsperAU, &parent_ddr))
				return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;
			fdir_AU = get_UINT16BE(parent_ddr.fdir_AU);

			/* generate FDIR and save it */
			for (i=0; i<127; i++)
			{
				buf[2*i] = catalog_buf.files[i].fdr_ptr >> 8;
				buf[2*i+1] = catalog_buf.files[i].fdr_ptr & 0xff;
			}
			buf[254] = parent_ref >> 8;
			buf[255] = parent_ref & 0xff;
			if (write_absolute_physrec(& image->l1_img, fdir_AU * image->AUformat.physrecsperAU, buf))
				return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;
		}
		break;
	}

	/* update bitmap */
	switch (image->type)
	{
	case L2I_DSK:
		{
			dsk_vib vib;

			if (read_absolute_physrec(& image->l1_img, 0, &vib))
				return (imgtoolerr_t)IMGTOOLERR_READERROR;
			memcpy(vib.abm, image->abm, 200);
			if (write_absolute_physrec(& image->l1_img, 0, &vib))
				return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;
		}
		break;

	case L2I_WIN:
		/* save allocation bitmap (aphysrecs 1 through n, n<=33) */
		for (i=0; i < (image->AUformat.totAUs+2047)/2048; i++)
			if (write_absolute_physrec(&image->l1_img, i+1, image->abm+i*256))
				return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;
		break;
	}

	return (imgtoolerr_t)0;
}

/*
    Delete a file from a ti99_image.
*/
static imgtoolerr_t dsk_image_deletefile(imgtool::partition &partition, const char *fpath)
{
	imgtool::image &img(partition.image());
	struct ti99_lvl2_imgref *image = get_lvl2_imgref(img);
	dsk_fdr fdr;
	int i, cluster_index;
	unsigned cur_AU, cluster_lastfphysrec;
//  int fphysrecs;
	int parent_ref, is_dir, catalog_index;
	imgtoolerr_t errorcode;
	uint8_t buf[256];
	ti99_catalog *catalog;


	if (check_fpath(fpath))
		return IMGTOOLERR_BADFILENAME;

	errorcode = (imgtoolerr_t)dsk_find_catalog_entry(image, fpath, NULL, &parent_ref, &is_dir, &catalog_index);
	if (errorcode)
		return errorcode;

	if (is_dir)
	{
		catalog = &image->dsk.catalogs[catalog_index+1];

		if ((catalog->num_files != 0) || (catalog->num_subdirs != 0))
			return IMGTOOLERR_UNIMPLEMENTED;

		catalog = &image->dsk.catalogs[0];

		/* free fdir AU */
		cur_AU = image->dsk.fdir_aphysrec[catalog_index+1] / image->AUformat.physrecsperAU;
		image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));

		/* delete catalog entry */
		for (i=catalog_index; i<2; i++)
		{
			catalog->subdirs[i] = catalog->subdirs[i+1];
			image->dsk.fdir_aphysrec[i+1] = image->dsk.fdir_aphysrec[i+2];
		}
		memset(catalog->subdirs[2].name, 0, 10);
		catalog->subdirs[2].dir_ptr = 0;
		image->dsk.fdir_aphysrec[3] = 0;
		catalog->num_subdirs--;

		/* update directory and bitmap in vib */
		{
			dsk_vib vib;

			if (read_absolute_physrec(& image->l1_img, 0, &vib))
				return IMGTOOLERR_READERROR;

			for (i=0; i<3; i++)
			{
				memcpy(vib.subdir[i].name, catalog->subdirs[i].name, 10);
				set_UINT16BE(&vib.subdir[i].fdir_aphysrec, image->dsk.fdir_aphysrec[i+1]);
			}

			memcpy(vib.abm, image->abm, 200);

			if (write_absolute_physrec(& image->l1_img, 0, &vib))
				return IMGTOOLERR_WRITEERROR;
		}
	}
	else
	{
		catalog = &image->dsk.catalogs[parent_ref];

		if (read_absolute_physrec(& image->l1_img, catalog->files[catalog_index].fdr_ptr, &fdr))
			return IMGTOOLERR_READERROR;

		/* free data AUs */
//      fphysrecs =
		get_UINT16BE(fdr.fphysrecs);

		i = 0;
		cluster_index = 0;
		while (cluster_index < 76)
		{
			cur_AU = get_dsk_fdr_cluster_baseAU(image, & fdr, cluster_index);
			if (cur_AU == 0)
				/* end of cluster list */
				break;
			cluster_lastfphysrec = get_dsk_fdr_cluster_lastfphysrec(& fdr, cluster_index);

			while (i<=cluster_lastfphysrec)
			{
				/* the condition below is an error, but it should not prevent
				us from deleting the file */
				if (cur_AU >= image->AUformat.totAUs)
					/*return IMGTOOLERR_CORRUPTIMAGE;*/
					break;

				image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));

				i += image->AUformat.physrecsperAU;
				cur_AU++;
			}

			cluster_index++;
		}
		/* the condition below is an error, but it should not prevent us from
		deleting the file */
#if 0
		if (i<fphysrecs)
			return IMGTOOLERR_CORRUPTIMAGE;
#endif

		/* free fdr AU */
		cur_AU = catalog->files[catalog_index].fdr_ptr / image->AUformat.physrecsperAU;
		image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));

		/* delete catalog entry */
		for (i=catalog_index; i<127; i++)
			catalog->files[i] = catalog->files[i+1];
		catalog->files[127].fdr_ptr = 0;
		catalog->num_files--;

		/* update parent fdir */
		for (i=0; i<128; i++)
		{
			buf[2*i] = catalog->files[i].fdr_ptr >> 8;
			buf[2*i+1] = catalog->files[i].fdr_ptr & 0xff;
		}
		if (write_absolute_physrec(& image->l1_img, image->dsk.fdir_aphysrec[parent_ref], buf))
			return IMGTOOLERR_WRITEERROR;

		/* update bitmap */
		{
			dsk_vib vib;

			if (read_absolute_physrec(& image->l1_img, 0, &vib))
				return IMGTOOLERR_READERROR;
			memcpy(vib.abm, image->abm, 200);
			if (write_absolute_physrec(& image->l1_img, 0, &vib))
				return IMGTOOLERR_WRITEERROR;
		}
	}

	return (imgtoolerr_t)0;
}

static imgtoolerr_t win_image_deletefile(imgtool::partition &partition, const char *fpath)
{
	imgtool::image &img(partition.image());
	struct ti99_lvl2_imgref *image = get_lvl2_imgref(img);
	int parent_ddr_AU, is_dir, catalog_index;
	win_fdr fdr;
	int i;
	unsigned cur_AU, end_AU;
	unsigned curfdr_aphysrec;
	unsigned cursibFDR_index, endsibFDR_index = 0;
	int errorcode;
	uint8_t buf[256];
	ti99_catalog catalog;


	if (check_fpath(fpath))
		return (imgtoolerr_t)IMGTOOLERR_BADFILENAME;

	errorcode = win_find_catalog_entry(image, fpath, NULL, &parent_ddr_AU, &catalog, &is_dir, &catalog_index);
	if (errorcode)
		return (imgtoolerr_t)errorcode;

	if (is_dir)
	{
		unsigned DDR_AU;
		win_vib_ddr ddr_buf;

		/* Read DDR record */
		DDR_AU = catalog.subdirs[catalog_index].dir_ptr;
		if (read_absolute_physrec(& image->l1_img, DDR_AU*image->AUformat.physrecsperAU, &ddr_buf))
			return (imgtoolerr_t)IMGTOOLERR_READERROR;

		/* read FDIR AU pointer */
		cur_AU = get_UINT16BE(ddr_buf.fdir_AU);

		/* sanity checks */
		if ((ddr_buf.num_files > 127) || (ddr_buf.num_subdirs > 114) || (cur_AU > image->AUformat.totAUs))
			return (imgtoolerr_t)IMGTOOLERR_CORRUPTIMAGE;

		if ((ddr_buf.num_files != 0) || (ddr_buf.num_subdirs != 0))
			return (imgtoolerr_t)IMGTOOLERR_UNIMPLEMENTED;

		/* free fdir AU */
		image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));

		/* free ddr AU */
		image->abm[DDR_AU >> 3] &= ~ (1 << (DDR_AU & 7));

		/* delete parent catalog entry */
		for (i=catalog_index; i<113; i++)
			catalog.subdirs[i] = catalog.subdirs[i+1];
		catalog.subdirs[113].dir_ptr = 0;
		catalog.num_subdirs--;

		/* update parent VIB/DDR */
		if (read_absolute_physrec(& image->l1_img, parent_ddr_AU * image->AUformat.physrecsperAU, &ddr_buf))
			return (imgtoolerr_t)IMGTOOLERR_READERROR;
		ddr_buf.num_subdirs = catalog.num_subdirs;
		for (i=0; i<114; i++)
			set_UINT16BE(&ddr_buf.subdir_AU[i], catalog.subdirs[i].dir_ptr);
		if (write_absolute_physrec(& image->l1_img, parent_ddr_AU * image->AUformat.physrecsperAU, &ddr_buf))
			return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;

		/* save allocation bitmap (aphysrecs 1 through n, n<=33) */
		for (i=0; i < (image->AUformat.totAUs+2047)/2048; i++)
			if (write_absolute_physrec(&image->l1_img, i+1, image->abm+i*256))
				return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;
	}
	else
	{
		/* check integrity of FDR sibling chain, and go to last sibling */
		/* note that as we check that the back chain is consistent with the forward
		chain, we will also detect any cycle in the sibling chain, so we do not
		need to check against them explicitly */
		{
			int pastendoflist_flag;
			unsigned prevfdr_aphysrec;


			pastendoflist_flag = 0;
			cursibFDR_index = 0;
			curfdr_aphysrec = catalog.files[catalog_index].fdr_ptr * image->AUformat.physrecsperAU;
			if (read_absolute_physrec(& image->l1_img, curfdr_aphysrec, &fdr))
				return (imgtoolerr_t)IMGTOOLERR_READERROR;

			if (get_UINT16BE(fdr.prevsibFDR_AU) != 0)
				return (imgtoolerr_t)IMGTOOLERR_CORRUPTIMAGE;

			while (1)
			{
				if (! pastendoflist_flag)
				{
					/* look for end of list */
					for (i=0; i<54; i++)
					{
						if (get_UINT16BE(fdr.clusters[i][0]) == 0)
						{
							endsibFDR_index = cursibFDR_index;
							pastendoflist_flag = true;
							break;
						}
					}
				}

				/* exit loop if end of sibling chain */
				if (! get_UINT16BE(fdr.nextsibFDR_AU))
					break;

				/* otherwise read next FDR */
				if (get_UINT16BE(fdr.nextsibFDR_AU) >= image->AUformat.totAUs)
					return (imgtoolerr_t)IMGTOOLERR_CORRUPTIMAGE;

				prevfdr_aphysrec = curfdr_aphysrec;
				curfdr_aphysrec = get_win_fdr_nextsibFDR_aphysrec(image, &fdr);
				if (read_absolute_physrec(& image->l1_img, curfdr_aphysrec, &fdr))
					return (imgtoolerr_t)IMGTOOLERR_READERROR;
				cursibFDR_index++;

				/* check that back chaining is consistent with forward chaining */
				if (get_win_fdr_prevsibFDR_aphysrec(image, &fdr) != prevfdr_aphysrec)
					return (imgtoolerr_t)IMGTOOLERR_CORRUPTIMAGE;
			}
			if (! pastendoflist_flag)
				endsibFDR_index = cursibFDR_index;
		}


		while (1)
		{
			if (cursibFDR_index <= endsibFDR_index)
			{
				for (i = 0; i < 54; i++)
				{
					cur_AU = get_UINT16BE(fdr.clusters[i][0]);
					if (cur_AU == 0)
						/* end of cluster list */
						break;
					end_AU = get_UINT16BE(fdr.clusters[i][1]);

					while (cur_AU<=end_AU)
					{
						/* the condition below is an error, but it should not prevent
						us from deleting the file */
						if (cur_AU >= image->AUformat.totAUs)
							/*return IMGTOOLERR_CORRUPTIMAGE;*/
							break;

						image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));

						cur_AU++;
					}
				}
			}

			/* free fdr AU if applicable */
			if ((curfdr_aphysrec % image->AUformat.physrecsperAU) == 0)
			{
				cur_AU = curfdr_aphysrec / image->AUformat.physrecsperAU;
				image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));
			}

			if (cursibFDR_index == 0)
				break;
			curfdr_aphysrec = get_win_fdr_prevsibFDR_aphysrec(image, &fdr);
			if (read_absolute_physrec(& image->l1_img, curfdr_aphysrec, &fdr))
				return (imgtoolerr_t)IMGTOOLERR_READERROR;
			cursibFDR_index--;
		}


		/* delete catalog entry */
		for (i=catalog_index; i<127; i++)
			catalog.files[i] = catalog.files[i+1];
		catalog.files[127].fdr_ptr = 0;
		catalog.num_files--;


		/* update VIB/DDR and get FDIR AU address */
		{
			win_vib_ddr parent_ddr;

			if (read_absolute_physrec(& image->l1_img, parent_ddr_AU * image->AUformat.physrecsperAU, &parent_ddr))
				return (imgtoolerr_t)IMGTOOLERR_READERROR;
			parent_ddr.num_files = catalog.num_files;
			if (write_absolute_physrec(& image->l1_img, parent_ddr_AU * image->AUformat.physrecsperAU, &parent_ddr))
				return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;
			cur_AU = get_UINT16BE(parent_ddr.fdir_AU);
		}

		/* generate FDIR and save it */
		for (i=0; i<127; i++)
		{
			buf[2*i] = catalog.files[i].fdr_ptr >> 8;
			buf[2*i+1] = catalog.files[i].fdr_ptr & 0xff;
		}
		buf[254] = parent_ddr_AU >> 8;
		buf[255] = parent_ddr_AU & 0xff;
		if (write_absolute_physrec(& image->l1_img, cur_AU * image->AUformat.physrecsperAU, buf))
			return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;

		/* save allocation bitmap (aphysrecs 1 through n, n<=33) */
		for (i=0; i < (image->AUformat.totAUs+2047)/2048; i++)
			if (write_absolute_physrec(&image->l1_img, i+1, image->abm+i*256))
				return (imgtoolerr_t)IMGTOOLERR_WRITEERROR;
	}

	return (imgtoolerr_t)0;
}

/*
    Create a blank ti99_image (common code).

    Supports MESS and V9T9 formats only
*/
static imgtoolerr_t dsk_image_create(imgtool::image &image, imgtool::stream::ptr &&stream, util::option_resolution *createoptions, ti99_img_format img_format)
{
	const char *volname;
	int density;
	ti99_lvl1_imgref l1_img;
	int protected_var;

	int totphysrecs, physrecsperAU, totAUs;

	dsk_vib vib;
	uint8_t empty_sec[256];

	int i;

	l1_img.img_format = img_format;
	l1_img.file_handle = stream.get();  // can't release here

	/* read options */
	volname = createoptions->lookup_string(dsk_createopts_volname).c_str();
	l1_img.geometry.heads = createoptions->lookup_int(dsk_createopts_sides);
	l1_img.geometry.cylinders = createoptions->lookup_int(dsk_createopts_tracks);
	l1_img.geometry.secspertrack = createoptions->lookup_int(dsk_createopts_sectors);
	protected_var = createoptions->lookup_int(dsk_createopts_protection);
	density = createoptions->lookup_int(dsk_createopts_density);

	/* NPW 03-DEC-2003 - Fixes a crash if volname is NULL */
	if (!volname)
		volname = "";

	totphysrecs = l1_img.geometry.secspertrack * l1_img.geometry.cylinders * l1_img.geometry.heads;
	physrecsperAU = (totphysrecs + 1599) / 1600;
	/* round to next larger power of 2 */
	for (i = 1; i < physrecsperAU; i <<= 1)
		;
	physrecsperAU = i;
	totAUs = totphysrecs / physrecsperAU;

	/* auto-density */
	if (density == 0)
	{
		if (l1_img.geometry.secspertrack <= 9)
			density = 1;
		else if (l1_img.geometry.secspertrack <= 18)
			density = 2;
		else
			density = 3;
	}

	/* check volume name */
	if (strchr(volname, '.') || strchr(volname, ' ') || (strlen(volname) > 10))
		return /*IMGTOOLERR_BADFILENAME*/IMGTOOLERR_PARAMCORRUPT;

	/* FM disks can hold fewer sector per track than MFM disks */
	if ((density == 1) && (l1_img.geometry.secspertrack > 9))
		return IMGTOOLERR_PARAMTOOLARGE;

	/* DD disks can hold fewer sector per track than HD disks */
	if ((density == 2) && (l1_img.geometry.secspertrack > 18))
		return IMGTOOLERR_PARAMTOOLARGE;

	/* check total disk size */
	if (totphysrecs < 2)
		return IMGTOOLERR_PARAMTOOSMALL;

	/* initialize vib in aphysrec 0 */

	/* set volume name */
	str_to_fname(vib.name, volname);

	/* set every header field */
	set_UINT16BE(& vib.totphysrecs, totphysrecs);
	vib.secspertrack = l1_img.geometry.secspertrack;
	vib.id[0] = 'D';
	vib.id[1] = 'S';
	vib.id[2] = 'K';
	vib.protection = protected_var ? 'P' : ' ';
	vib.cylinders = l1_img.geometry.cylinders;
	vib.heads = l1_img.geometry.heads;
	vib.density = density;
	for (i=0; i<3; i++)
	{
		memset(vib.subdir[i].name, '\0', 10);
		set_UINT16BE(& vib.subdir[i].fdir_aphysrec, 0);
	}

	/* clear bitmap */
	for (i=0; i < (totAUs>>3); i++)
		vib.abm[i] = 0;

	if (totAUs & 7)
	{
		vib.abm[i] = 0xff << (totAUs & 7);
		i++;
	}

	for (; i < 200; i++)
		vib.abm[i] = 0xff;

	/* mark first 2 aphysrecs (vib and fdir) as used */
	vib.abm[0] |= (physrecsperAU == 1) ? 3 : 1;

	/* write aphysrec 0 */
	if (write_absolute_physrec(&l1_img, 0, &vib))
		return IMGTOOLERR_WRITEERROR;


	/* now clear every other physrecs, including the FDIR record */
	memset(empty_sec, 0, sizeof(empty_sec));

	for (i=1; i<totphysrecs; i++)
		if (write_absolute_physrec(& l1_img, i, empty_sec))
			return IMGTOOLERR_WRITEERROR;


	return dsk_image_init(image, std::move(stream), img_format);
}

/*
    Create a blank ti99_image (MESS format).
*/
static imgtoolerr_t dsk_image_create_mess(imgtool::image &image, imgtool::stream::ptr &&stream, util::option_resolution *createoptions)
{
	return dsk_image_create(image, std::move(stream), createoptions, if_mess);
}

/*
    Create a blank ti99_image (V9T9 format).
*/
static imgtoolerr_t dsk_image_create_v9t9(imgtool::image &image, imgtool::stream::ptr &&stream, util::option_resolution *createoptions)
{
	return dsk_image_create(image, std::move(stream), createoptions, if_v9t9);
}