summaryrefslogtreecommitdiff
path: root/trs_disk.c
blob: adad588b4eabf2856e2b7e0453d0c47689a921b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
/* Copyright (c) 1996-97, Timothy Mann */

/* This software may be copied, modified, and used for any purpose
 * without fee, provided that (1) the above copyright notice is
 * retained, and (2) modified versions are clearly marked as having
 * been modified, with the modifier's name and the date included.  */

/* Last modified on Tue May  1 20:34:56 PDT 2001 by mann */

/*
 * Emulate Model I or III/4 disk controller
 */

/*
 * Debug flags.  Update help_message in debug.c if these change.
 */
#define DISKDEBUG_FDCREG   (1<<0)  /* FDC register reads and writes */
#define DISKDEBUG_FDCCMD   (1<<1)  /* FDC commands */
#define DISKDEBUG_VTOS3    (1<<2)  /* VTOS 3.0 JV3 kludges */
#define DISKDEBUG_GAPS     (1<<3)  /* Gaps and real_writetrk */
#define DISKDEBUG_REALSIZE (1<<4)  /* REAL sector size detection */
#define DISKDEBUG_READADR  (1<<5)  /* Read Address timing */
#define DISKDEBUG_DMK      (1<<6)  /* DMK support */
#define DISKDEBUG_REALERR  (1<<7)  /* ioctl errors accessing real disks */

#define TSTATEREV 1       /* Index holes timed by T-states, not real time */
#define SIZERETRY 1       /* Retry in different sizes on real_read */
#define DMK_MARK_IAM 0    /* Mark IAMs in track header; poor idea */

#include "z80.h"
#include "trs.h"
#include "trs_disk.h"
#include "trs_hard.h"
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>

#include "crc.c"

#if __linux
#include <sys/types.h>
#include <fcntl.h>
#include <linux/fd.h>
#include <linux/fdreg.h>
#include <sys/ioctl.h>
#endif

#define NDRIVES 8

int trs_disk_nocontroller = 0;
int trs_disk_doubler = TRSDISK_BOTH;
char *trs_disk_dir = DISKDIR;
unsigned short trs_disk_changecount = 0;
static int trs_disk_needchange = 0;
float trs_disk_holewidth = 0.01;
int trs_disk_truedam = 0;
int trs_disk_debug_flags = 0;

typedef struct {
  /* Registers */
  unsigned char status;
  unsigned char track;
  unsigned char sector;
  unsigned char data;
  /* Other state */
  unsigned char currcommand;
  int lastdirection;
  int bytecount;		/* bytes left to transfer this command */
  int format;			/* write track state machine */
  int format_bytecount;         /* bytes left in this part of write track */
  int format_sec;               /* current sector number or id_index */
  int format_gapcnt;            /* measure requested gaps */
  int format_gap[5];
  unsigned short crc;
  unsigned curdrive;
  unsigned curside;
  unsigned density;		/* sden=0, dden=1 */
  unsigned char controller;	/* TRSDISK_P1771 or TRSDISK_P1791 */
  int last_readadr;             /* id index found by last readadr */
  tstate_t motor_timeout;       /* 0 if stopped, else time when it stops */
} FDCState;

FDCState state, other_state;

/* Format states - what is expected next? */
#define FMT_GAP0    0
#define FMT_IAM     1
#define FMT_GAP1    2
#define FMT_IDAM    3
#define FMT_TRACKID 4
#define FMT_HEADID  5
#define FMT_SECID   6
#define FMT_SIZEID  7
#define FMT_IDCRC   8
#define FMT_GAP2    9
#define FMT_DAM     10
#define FMT_DATA    11
#define FMT_DCRC    12
#define FMT_GAP3    13
#define FMT_GAP4    14
#define FMT_DONE    15
#define FMT_PREAM   16  /* DDEN DMK only -- just saw preamble to an AM */
#define FMT_IPREAM  17  /* DDEN DMK only -- just saw preamble to an IAM */


/* Gap 0+1 and gap 4 angular size, used in Read Address timing emulation.
   Units: fraction of a complete circle. */
#define GAP1ANGLE 0.020 
#define GAP4ANGLE 0.050

/* How long does emulated motor stay on after drive selected? (us of
   emulated time) */
#define MOTOR_USEC 2000000

/* Heuristic: how often are we willing to check whether real drive
   has a disk in it?  (seconds of real time) */
#define EMPTY_TIMEOUT 3

/*
 * The following rather quirky data structure is designed to be
 * compatible with what Jeff Vavasour's Model III/4 emulator uses to
 * represent disk formatting information.  My interpretation is based
 * on reading his documentation, looking at some disk images, and
 * experimenting with his emulator to generate odd cases, so the
 * compatibility should be excellent.
 *
 * I have compatibly extended the format to allow for more sectors, so
 * that 8" DSDD drives can be supported, by adding a second block of
 * ids after the block of data sectors that is described by the first
 * block.  JV himself says that sounds like a good idea.  Matthew
 * Reed's emulators now support this extension.
 *
 * I've further extended the format to add a flag bit for non-IBM
 * sectors. Only a subset of the non-IBM functionality is supported,
 * rigged to make the VTOS 3.0 copy-protection system work.  Non-IBM
 * sectors were a feature of the 1771 only. Using this feature, you
 * could have a sector of any length from 16 to 4096 bytes in
 * multiples of 16. xtrs supports only 16-byte non-IBM sectors (with
 * their data stored in a 256-byte field), and has some special kludges
 * to detect and support VTOS's trick of formatting these sectors with
 * inadequate gaps between so that writing to one would smash the
 * index block of the next one.
 *
 * Finally, I've extended the format to support (IBM) sector lengths
 * other than 256 bytes. The standard lengths 128, 256, 512, and 1024
 * are supported, using the last two available bits in the header
 * flags byte. The data area of a floppy image thus becomes an array
 * of *variable length* sectors, making it more complicated to find
 * the sector data corresponding to a given header and to manage freed
 * sectors.
 *
 * NB: JV's model I emulator uses no auxiliary data structure for disk
 * format.  It simply assumes that all disks are single density, 256
 * bytes/sector, 10 sectors/track, single sided, with nonstandard FA
 * data address mark on all sectors on track 17.  */

/* Values for flags below */
#define JV3_DENSITY     0x80  /* 1=dden, 0=sden */
#define JV3_DAM         0x60  /* data address mark; values follow */
#define JV3_DAMSDFB     0x00
#define JV3_DAMSDFA     0x20
#define JV3_DAMSDF9     0x40
#define JV3_DAMSDF8     0x60
#define JV3_DAMDDFB     0x00
#define JV3_DAMDDF8     0x20
#define JV3_SIDE        0x10  /* 0=side 0, 1=side 1 */
#define JV3_ERROR       0x08  /* 0=ok, 1=CRC error */
#define JV3_NONIBM      0x04  /* 0=normal, 1=short (for VTOS 3.0, xtrs only) */
#define JV3_SIZE        0x03  /* in used sectors: 0=256,1=128,2=1024,3=512
				 in free sectors: 0=512,1=1024,2=128,3=256 */

#define JV3_FREE        0xff  /* in track/sector fields */
#define JV3_FREEF       0xfc  /* in flags field, or'd with size code */

typedef struct {
  unsigned char track;
  unsigned char sector;
  unsigned char flags;
} SectorId;

#define MAXTRACKS   255
#define JV1_SECSIZE 256
#define MAXSECSIZE 1024

/* Max bytes per unformatted track. */
/* Select codes 1, 2, 4, 8 are emulated 5" drives, disk?-0 to disk?-3 */
#define TRKSIZE_SD    3125  /* 250kHz / 5 Hz [300rpm] / (2 * 8) */
                         /* or 300kHz / 6 Hz [360rpm] / (2 * 8) */
#define TRKSIZE_DD    6250  /* 250kHz / 5 Hz [300rpm] / 8 */
                         /* or 300kHz / 6 Hz [360rpm] / 8 */
/* Select codes 3, 5, 6, 7 are emulated 8" drives, disk?-4 to disk?-7 */
#define TRKSIZE_8SD   5208  /* 500kHz / 6 Hz [360rpm] / (2 * 8) */
#define TRKSIZE_8DD  10416  /* 500kHz / 6 Hz [360rpm] / 8 */
/* TRS-80 software has no concept of HD, so these constants are unused,
 * but expanded JV3 would be big enough even for 3.5" HD. */
#define TRKSIZE_5HD  10416  /* 500kHz / 6 Hz [360rpm] / 8 */
#define TRKSIZE_3HD  12500  /* 500kHz / 5 Hz [300rpm] / 8 */

#define JV3_SIDES      2
#define JV3_IDSTART    0
#define JV3_SECSTART   (34*256) /* start of sectors within file */
#define JV3_SECSPERBLK ((int)(JV3_SECSTART/3))
#define JV3_SECSMAX    (2*JV3_SECSPERBLK)

#define JV1_SECPERTRK 10

/* Values for emulated disk image type (emutype) below */
#define JV1 1 /* compatible with Vavasour Model I emulator */
#define JV3 3 /* compatible with Vavasour Model III/4 emulator */
#define DMK 4 /* compatible with Keil Model III/4 emulator */
#define REAL 100 /* real floppy drive, PC controller */
#define CATW 101 /* real floppy drive, Catweasel controller (future) */
#define NONE 0

typedef struct {
  int free_id[4];		  /* first free id, if any, of each size */
  int last_used_id;		  /* last used index */
  int nblocks;                    /* number of blocks of ids, 1 or 2 */
  int sorted_valid;               /* sorted_id array valid */
  SectorId id[JV3_SECSMAX + 1];   /* extra one is a loop sentinel */
  int offset[JV3_SECSMAX + 1];    /* offset into file for each id */
  short sorted_id[JV3_SECSMAX + 1];
  short track_start[MAXTRACKS][JV3_SIDES];
} JV3State;

typedef struct {
  int rps;                        /* phys rotations/sec; emutype REAL only */
  int size_code;                  /* most recent sector size; REAL only */
  int empty;                      /* 1=emulate empty drive */
  time_t empty_timeout;           /* real_empty valid until this time */
  int fmt_nbytes;                 /* number of PC format command bytes */
  int fmt_fill;                   /* fill byte for data sectors */
  unsigned char buf[MAXSECSIZE];
} RealState;

/* Some constants for DMK format */
#define DMK_WRITEPROT     0
#define DMK_NTRACKS       1
#define DMK_TRACKLEN      2
#define DMK_TRACKLEN_SIZE 2
#define DMK_OPTIONS       4
#define DMK_FORMAT        0x0c
#define DMK_FORMAT_SIZE   4
#define DMK_HDR_SIZE      0x10
#define DMK_TKHDR_SIZE    0x80    /* Space reserved for IDAM pointers */
#define DMK_TRACKLEN_MAX  0x4000

/* Bit assignments in options */
#define DMK_SSIDE_OPT     0x10
#define DMK_SDEN_OPT      0x40
#define DMK_IGNDEN_OPT    0x80

/* Bit assignments in IDAM pointers */
#define DMK_DDEN_FLAG     0x8000
#define DMK_EXTRA_FLAG    0x4000  /* unused */
#define DMK_IDAMP_BITS    0x3fff

#define dmk_incr(d) \
  (((d)->u.dmk.ignden || (d)->u.dmk.sden || state.density) ? 1 : 2)

typedef struct {
  int ntracks;                    /* max number of tracks formatted */
  int tracklen;                   /* bytes reserved per track in file */
  int nsides;                     /* 1 or 2 (single-sided flag in header) */
  int sden;                       /* single-density-only flag in header */
  int ignden;                     /* ignore-density flag in header */
  int curtrack, curside;          /* track/side in track buffer, or -1/-1 */
  int curbyte;                    /* index in buf for current op */
  int nextidam;                   /* index in buf to put next idam */
  unsigned char buf[DMK_TRACKLEN_MAX];
} DMKState;

typedef struct {
  int writeprot;		  /* emulated write protect tab */
  int phytrack;			  /* where are we really? */
  int emutype;
  int inches;                     /* 5 or 8, as seen by TRS-80 */
  int real_step;                  /* 1=normal, 2=double-step if REAL */
  FILE* file;
  union {
    JV3State jv3;                 /* valid if emutype = JV3 */
    RealState real;               /* valid if emutype = REAL */
    DMKState dmk;                 /* valid if emutype = DMK */
  } u;
} DiskState;

DiskState disk[NDRIVES];

/* Emulate interleave in JV1 mode */
unsigned char jv1_interleave[10] = {0, 5, 1, 6, 2, 7, 3, 8, 4, 9};

/* Forward */
void real_verify();
void real_restore(int curdrive);
void real_seek();
void real_read();
void real_write();
void real_readadr();
void real_readtrk();
void real_writetrk();
int real_check_empty(DiskState *d);

/* Entry point for the zbx debugger */
void
trs_disk_debug()
{
  int i;
  printf("Floppy disk controller state:\n");
  printf("  status 0x%02x, track %d (0x%02x), sector %d (0x%02x), "
	 "data 0x%02x\n", state.status, state.track, state.track,
	 state.sector, state.sector, state.data);
  printf("  currcommand 0x%02x, bytecount left %d, last step direction %d\n",
	 state.currcommand, state.bytecount, state.lastdirection);
  printf("  curdrive %d, curside %d, density %d, controller %s\n",
	 state.curdrive, state.curside, state.density,
	 state.controller == TRSDISK_P1771 ? "WD1771" : "WD1791/93");
  printf("  crc state 0x%04x, last_readadr %d, motor timeout %ld\n",
	 state.crc, state.last_readadr,
	 (long) (state.motor_timeout - z80_state.t_count));
  printf("  last (non-DMK) format gaps %d %d %d %d %d\n",
	 state.format_gap[0], state.format_gap[1], state.format_gap[2],
	 state.format_gap[3], state.format_gap[4]);
  printf("  debug flags: %#x\n", trs_disk_debug_flags);
  for (i=0; i<NDRIVES; i++) {
    DiskState *d = &disk[i];
    printf("Drive %d state: "
	   "writeprot %d, phytrack %d (0x%02x), inches %d, step %d, type ",
	   i, d->writeprot, d->phytrack, d->phytrack, d->inches, d->real_step);
    if (d->file == NULL) {
      printf("EMPTY\n");
    } else {
      switch (d->emutype) {
      case JV1:
	printf("JV1\n");
	break;
      case JV3:
	printf("JV3\n");
	printf("  last used id %d, id blocks %d\n",
	       d->u.jv3.last_used_id, d->u.jv3.nblocks);
	break;
      case DMK:
	printf("DMK\n");
	printf("  ntracks %d (0x%02x), tracklen 0x%04x, nsides %d, sden %d, "
	       "ignden %d\n", d->u.dmk.ntracks, d->u.dmk.ntracks,
	       d->u.dmk.tracklen, d->u.dmk.nsides, d->u.dmk.sden,
	       d->u.dmk.ignden);
	printf("  buffered track %d, side %d, curbyte %d, nextidam %d\n",
	       d->u.dmk.curtrack, d->u.dmk.curside, d->u.dmk.curbyte,
	       d->u.dmk.nextidam);
	break;
      case REAL:
	printf("REAL\n");
	printf("  rpm %d, empty %d, last size code %d, last fmt fill 0x%02x\n",
	       d->u.real.rps * 60, d->u.real.empty, d->u.real.size_code,
	       d->u.real.fmt_fill);
	break;
      default:
	printf("UNKNOWN\n");
	break;
      }
    }
  }
}

void
trs_disk_setsize(int unit, int value)
{
  if (unit < 0 || unit > 7) return;
  disk[unit].inches = (value == 8) ? 8 : 5;
}

void
trs_disk_setstep(int unit, int value)
{
  if (unit < 0 || unit > 7) return;
  disk[unit].real_step = (value == 2) ? 2 : 1;
}

int
trs_disk_getsize(int unit)
{
  if (unit < 0 || unit > 7) return 0;
  return disk[unit].inches;
}

int
trs_disk_getstep(int unit)
{
  if (unit < 0 || unit > 7) return 0;
  return disk[unit].real_step;
}

void
trs_sigusr1(int signo)
{
  trs_disk_needchange = 1;
}

void
trs_disk_init(int reset_button)
{
  int i;
  struct sigaction sa;

  state.status = TRSDISK_NOTRDY|TRSDISK_TRKZERO;
  state.track = 0;
  state.sector = 0;
  state.data = 0;
  state.currcommand = TRSDISK_RESTORE;
  state.lastdirection = 1;
  state.bytecount = 0;
  state.format = FMT_DONE;
  state.format_bytecount = 0;
  state.format_sec = 0;
  state.curdrive = state.curside = 0;
  state.density = 0;
  state.controller = (trs_model == 1) ? TRSDISK_P1771 : TRSDISK_P1791;
  state.last_readadr = -1;
  state.motor_timeout = 0;
  if (!reset_button) {
    for (i=0; i<NDRIVES; i++) {
      disk[i].phytrack = 0;
      disk[i].emutype = NONE;
    }
  }
  trs_disk_change_all();
  trs_cancel_event();

  trs_disk_nocontroller = (trs_model < 5 && disk[0].file == NULL);

  sa.sa_handler = trs_sigusr1;
  sigemptyset(&sa.sa_mask);
  sigaddset(&sa.sa_mask, SIGUSR1);
  sa.sa_flags = SA_RESTART;
  sigaction(SIGUSR1, &sa, NULL);
}

void
trs_disk_change_all()
{
  int i;
  for (i=0; i<NDRIVES; i++) {
    trs_disk_change(i);
  }
  trs_disk_changecount++;
  trs_hard_init(1);
}


/* trs_event_func used for delayed command completion.  Clears BUSY,
   sets any additional bits specified, and generates a command
   completion interrupt */
static void
trs_disk_done(int bits)
{
  state.status &= ~TRSDISK_BUSY;
  state.status |= bits;
  trs_disk_intrq_interrupt(1);
}


/* trs_event_func to abort the last command with LOSTDATA if it is
   still in progress */
static void
trs_disk_lostdata(int cmd)
{
  if (state.currcommand == cmd) {
    state.status &= ~TRSDISK_BUSY;
    state.status |= TRSDISK_LOSTDATA;
    state.bytecount = 0;
    trs_disk_intrq_interrupt(1);
  }
}

/* trs_event_func used as a delayed command start.  Sets DRQ,
   generates a DRQ interrupt, sets any additional bits specified, and
   schedules a trs_disk_lostdata event. */
static void
trs_disk_firstdrq(int bits)
{
  state.status |= TRSDISK_DRQ | bits;
  trs_disk_drq_interrupt(1);
  trs_schedule_event(trs_disk_lostdata, state.currcommand,
		     500000 * z80_state.clockMHz);
}

static void
trs_disk_unimpl(unsigned char cmd, char* more)
{
  state.status = TRSDISK_NOTRDY|TRSDISK_WRITEFLT|TRSDISK_NOTFOUND;
  state.bytecount = state.format_bytecount = 0;
  state.format = FMT_DONE;
  trs_disk_drq_interrupt(0);
  trs_schedule_event(trs_disk_done, 0, 0);
  error("trs_disk_command(0x%02x) not implemented - %s", cmd, more);
}

/* Sort first by track, second by side, third by position in emulated-disk
   sector array (i.e., physical sector order on track).  */
static int
jv3_id_compare(const void* p1, const void* p2)
{
  DiskState *d = &disk[state.curdrive];
  int i1 = *(short*)p1;
  int i2 = *(short*)p2;
  int r = d->u.jv3.id[i1].track - d->u.jv3.id[i2].track;
  if (r != 0) return r;
  r = (d->u.jv3.id[i1].flags & JV3_SIDE) - (d->u.jv3.id[i2].flags & JV3_SIDE);
  if (r != 0) return r;
  return i1 - i2;
}

/* (Re-)create the sorted_id data structure for the given drive */
void
jv3_sort_ids(int drive)
{
  DiskState *d = &disk[drive];
  int olddrive = state.curdrive;
  int i, track, side;

  for (i=0; i<=JV3_SECSMAX; i++) {
    d->u.jv3.sorted_id[i] = i;
  }
  state.curdrive = drive;
  qsort((void*) d->u.jv3.sorted_id, JV3_SECSMAX, sizeof(short),
	jv3_id_compare);
  state.curdrive = olddrive;

  for (track=0; track<MAXTRACKS; track++) {
    d->u.jv3.track_start[track][0] = -1;
    d->u.jv3.track_start[track][1] = -1;
  }    
  track = side = -1;
  for (i=0; i<JV3_SECSMAX; i++) {
    SectorId *sid = &d->u.jv3.id[d->u.jv3.sorted_id[i]];
    if (sid->track != track ||
	(sid->flags & JV3_SIDE ? 1 : 0) != side) {
      track = sid->track;
      if (track == JV3_FREE) break;
      side = sid->flags & JV3_SIDE ? 1 : 0;
      d->u.jv3.track_start[track][side] = i;
    }
  }

  d->u.jv3.sorted_valid = 1;  
}

/* JV3 only */
int
id_index_to_size_code(DiskState *d, int id_index)
{
  return (d->u.jv3.id[id_index].flags & JV3_SIZE) ^
    ((d->u.jv3.id[id_index].track == JV3_FREE) ? 2 : 1);
}

/* IBM formats only */
int
size_code_to_size(int code)
{
  return 128 << code;
}

/* JV3 only */
int
id_index_to_size(DiskState *d, int id_index)
{
  return 128 << id_index_to_size_code(d, id_index);
}

/* Return the offset of the data block for the id_index'th sector
   in an emulated-disk file.  Not used for DMK. */
static off_t
offset(DiskState *d, int id_index)
{
  if (d->emutype == JV1) {
    return id_index * JV1_SECSIZE;
  } else if (d->emutype == JV3) {
    return d->u.jv3.offset[id_index];
  } else {
    trs_disk_unimpl(state.currcommand, "DMK offset (internal error)");
    return 0;
  }
}

/* Return the offset of the id block for the id_index'th sector
   in an emulated-disk file.  Initialize a new block if needed.  JV3 only. */
static off_t
idoffset(DiskState *d, int id_index)
{
  if (d->emutype == JV1 || d->emutype == DMK) {
    trs_disk_unimpl(state.currcommand, "JV1 or DMK idoffset (internal error)");
    return -1;
  } else {
    if (id_index < JV3_SECSPERBLK) {
      return JV3_IDSTART + id_index * sizeof(SectorId);
    } else {
      int idstart2 = d->u.jv3.offset[JV3_SECSPERBLK-1] +
	id_index_to_size(d, JV3_SECSPERBLK-1);

      if (d->u.jv3.nblocks == 1) {
        /* Initialize new block of ids */
	int c;
	fseek(d->file, idstart2, 0);
        c = fwrite((void*)&d->u.jv3.id[JV3_SECSPERBLK], JV3_SECSTART, 1, d->file);
	if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	c = fflush(d->file);
	if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	d->u.jv3.nblocks = 2;
      }	
      return idstart2 + (id_index - JV3_SECSPERBLK) * sizeof(SectorId);
    }
  }
}

int
jv3_alloc_sector(DiskState *d, int size_code)
{
  int maybe = d->u.jv3.free_id[size_code];
  d->u.jv3.sorted_valid = 0;
  while (maybe <= d->u.jv3.last_used_id) {
    if (d->u.jv3.id[maybe].track == JV3_FREE &&
	id_index_to_size_code(d, maybe) == size_code) {
      d->u.jv3.free_id[size_code] = maybe + 1;
      return maybe;
    }
    maybe++;
  }
  d->u.jv3.free_id[size_code] = JV3_SECSMAX; /* none are free */
  if (d->u.jv3.last_used_id >= JV3_SECSMAX-1) {
    return -1;
  }
  d->u.jv3.last_used_id++;
  d->u.jv3.offset[d->u.jv3.last_used_id + 1] =
    d->u.jv3.offset[d->u.jv3.last_used_id] + size_code_to_size(size_code);
  if (d->u.jv3.last_used_id + 1 == JV3_SECSPERBLK) {
      d->u.jv3.offset[d->u.jv3.last_used_id + 1] += JV3_SECSTART;
  }
  return d->u.jv3.last_used_id;
}

void
jv3_free_sector(DiskState *d, int id_index)
{
  int c;
  int size_code = (d->u.jv3.id[id_index].flags & JV3_SIZE) ^ 1;
  if (d->u.jv3.free_id[size_code] > id_index) {
    d->u.jv3.free_id[size_code] = id_index;
  }
  d->u.jv3.sorted_valid = 0;
  d->u.jv3.id[id_index].track = JV3_FREE;
  d->u.jv3.id[id_index].sector = JV3_FREE;
  d->u.jv3.id[id_index].flags =
    (d->u.jv3.id[id_index].flags | JV3_FREEF) ^ JV3_SIZE;
  fseek(d->file, idoffset(d, id_index), 0);
  c = fwrite(&d->u.jv3.id[id_index], sizeof(SectorId), 1, d->file);
  if (c == EOF) state.status |= TRSDISK_WRITEFLT;

  if (id_index == d->u.jv3.last_used_id) {
    int newlen;
    while (d->u.jv3.id[d->u.jv3.last_used_id].track == JV3_FREE) {
      d->u.jv3.last_used_id--;
    }
    fflush(d->file);
    rewind(d->file);
    if (d->u.jv3.last_used_id >= 0) {
      newlen = offset(d, d->u.jv3.last_used_id) +
	id_index_to_size(d, d->u.jv3.last_used_id);
    } else {
      newlen = offset(d, 0);
    }
    ftruncate(fileno(d->file), newlen);
  }
}

/* Heuristic to decide what file format we have */
/* Also decodes write-protect state */
void
trs_disk_emutype(DiskState *d)
{
  int c;
  char fmt[4];
  int count;

  fseek(d->file, 0, 0);
  c = getc(d->file);
  if (c == -1) {
    d->emutype = JV1;
    return;
  }
  if (c == 0 || c == 0xff) {
    fseek(d->file, DMK_FORMAT, 0);
    count = fread(fmt, 1, DMK_FORMAT_SIZE, d->file);
    if (count != DMK_FORMAT_SIZE) {
      d->emutype = JV1;
      return;
    }
    if (fmt[0] == 0 && fmt[1] == 0 && fmt[2] == 0 && fmt[3] == 0) {
      fseek(d->file, DMK_TRACKLEN, 0);
      count = (unsigned char) getc(d->file);
      count += (unsigned char) getc(d->file) << 8;
      if (count >= 16 && count <= DMK_TRACKLEN_MAX) {
	d->emutype = DMK;
	d->writeprot = d->writeprot || (c == 0xff);
	return;
      }
    }
    if (fmt[0] == 0x78 && fmt[1] == 0x56 && fmt[2] == 0x34 && fmt[3] == 0x12) {
      error("Real disk specifier file from DMK emulator not supported");
      d->emutype = NONE;
      fclose(d->file);
      d->file = NULL;
      return;
    }
  }
  if (c == 0) {
    fseek(d->file, 1, 0);
    if (getc(d->file) == 0xfe) {
      d->emutype = JV1;
      return;
    }
  }
  fseek(d->file, JV3_SECSPERBLK*sizeof(SectorId), 0);
  c = getc(d->file);
  if (c == 0 || c == 0xff) {
    d->emutype = JV3;
    d->writeprot = d->writeprot || (c == 0);
    return;
  }
  d->emutype = JV1;
}

void
trs_disk_change(int drive)
{
  char diskname[1024];
  DiskState *d = &disk[drive];  
  struct stat st;
  int c, res;

  if (d->file != NULL) {
    c = fclose(d->file);
    if (c == EOF) state.status |= TRSDISK_WRITEFLT;
  }
  if (trs_model == 5) {
    sprintf(diskname, "%s/disk4p-%d", trs_disk_dir, drive);
  } else {
    sprintf(diskname, "%s/disk%d-%d", trs_disk_dir, trs_model, drive);
  }
  res = stat(diskname, &st);
  if (res == -1) {
    d->file = NULL;
    return;
  }
#if __linux
  if (S_ISBLK(st.st_mode)) {
    /* Real floppy drive */
    int fd;
    int reset_now = 0;
    struct floppy_drive_params fdp;
    fd = open(diskname, O_ACCMODE|O_NDELAY);
    if (fd == -1) {
      error("%s: %s", diskname, strerror(errno));
      d->file = NULL;
      d->emutype = JV3;
      return;
    }
    d->file = fdopen(fd, "r+");
    if (d->file == NULL) {
      error("%s: %s", diskname, strerror(errno));
      d->emutype = JV3;
      return;
    }
    d->writeprot = 0;
    ioctl(fileno(d->file), FDRESET, &reset_now);
    ioctl(fileno(d->file), FDGETDRVPRM, &fdp);
    d->u.real.rps = fdp.rps;
    d->u.real.size_code = 1; /* initial guess: 256 bytes */
    d->u.real.empty_timeout = 0;
    if (d->emutype != REAL) {
      d->emutype = REAL;
      d->phytrack = 0;
      real_restore(drive);
    }
  } else
#endif
  {
    d->file = fopen(diskname, "r+");
    if (d->file == NULL) {
      d->file = fopen(diskname, "r");
      if (d->file == NULL) return;
      d->writeprot = 1;
    } else {
      d->writeprot = 0;
    }
    trs_disk_emutype(d);
  }
  if (d->emutype == JV3) {
    int id_index, n;
    int ofst;

    memset((void*)d->u.jv3.id, JV3_FREE, sizeof(d->u.jv3.id));

    /* Read first block of ids */
    fseek(d->file, JV3_IDSTART, 0);
    fread((void*)&d->u.jv3.id[0], 3, JV3_SECSPERBLK, d->file);

    /* Scan to find their offsets */
    ofst = JV3_SECSTART;
    for (id_index=0; id_index<JV3_SECSPERBLK; id_index++) {
      d->u.jv3.offset[id_index] = ofst;
      ofst += id_index_to_size(d, id_index);
    }

    /* Read second block of ids, if any */
    fseek(d->file, ofst, 0);
    n = fread((void*)&d->u.jv3.id[JV3_SECSPERBLK], 3, JV3_SECSPERBLK, d->file);
    d->u.jv3.nblocks = n > 0 ? 2 : 1;

    /* Scan to find their offsets */
    ofst += JV3_SECSTART;
    for (id_index=JV3_SECSPERBLK; id_index<JV3_SECSPERBLK*2; id_index++) {
      d->u.jv3.offset[id_index] = ofst;
      ofst += id_index_to_size(d, id_index);
    }

    /* Find u.jv3.last_used_id value and u.jv3.free_id hints */
    for (n=0; n<4; n++) {
      d->u.jv3.free_id[n] = JV3_SECSMAX;
    }
    d->u.jv3.last_used_id = -1;
    for (id_index=0; id_index<JV3_SECSMAX; id_index++) {
      if (d->u.jv3.id[id_index].track == JV3_FREE) {
	int size_code = id_index_to_size_code(d, id_index);
	if (d->u.jv3.free_id[size_code] == JV3_SECSMAX) {
	  d->u.jv3.free_id[size_code] = id_index;
	}
      } else {
	d->u.jv3.last_used_id = id_index;
      }
    }
    jv3_sort_ids(drive);
  } else if (d->emutype == DMK) {
    fseek(d->file, DMK_NTRACKS, 0);
    d->u.dmk.ntracks = (unsigned char) getc(d->file);
    d->u.dmk.tracklen = (unsigned char) getc(d->file) +
      (((unsigned char) getc(d->file)) << 8);
    c = getc(d->file);
    d->u.dmk.nsides = (c & DMK_SSIDE_OPT) ? 1 : 2;
    d->u.dmk.sden = (c & DMK_SDEN_OPT) != 0;
    d->u.dmk.ignden = (c & DMK_IGNDEN_OPT) != 0;
    d->u.dmk.curtrack = d->u.dmk.curside = -1;

    if (trs_disk_debug_flags & DISKDEBUG_DMK) {
      debug("DMK drv=%d wp=%d #tk=%d tklen=0x%x nsides=%d sden=%d ignden=%d\n",
	    drive, d->writeprot, d->u.dmk.ntracks, d->u.dmk.tracklen,
	    d->u.dmk.nsides, d->u.dmk.sden, d->u.dmk.ignden);
    }
  }
}

static int
cmd_type(unsigned char cmd)
{
  switch (cmd & TRSDISK_CMDMASK) {
  case TRSDISK_RESTORE:
  case TRSDISK_SEEK:
  case TRSDISK_STEP:
  case TRSDISK_STEPU:
  case TRSDISK_STEPIN:
  case TRSDISK_STEPINU:
  case TRSDISK_STEPOUT:
  case TRSDISK_STEPOUTU:
    return 1;
  case TRSDISK_READ:
  case TRSDISK_READM:
  case TRSDISK_WRITE:
  case TRSDISK_WRITEM:
    return 2;
  case TRSDISK_READADR:
  case TRSDISK_READTRK:
  case TRSDISK_WRITETRK:
    return 3;
  case TRSDISK_FORCEINT:
    return 4;
  }
  return -1;			/* not reached */
}


/* Called by the interrupt code to determine whether a motoroff NMI is
   required.  Called even if this NMI is masked, so we also use it here
   to set NOTRDY and LOSTDATA. */
int
trs_disk_motoroff()
{
  int stopped;
  int cmdtype;

  stopped = (state.motor_timeout - z80_state.t_count > TSTATE_T_MID);
  if (stopped) {
    state.status |= TRSDISK_NOTRDY;
    cmdtype = cmd_type(state.currcommand);
    if ((cmdtype == 2 || cmdtype == 3) && (state.status & TRSDISK_DRQ)) {
      /* Also end the command and set Lost Data for good measure */
      state.status = (state.status | TRSDISK_LOSTDATA) &
	~(TRSDISK_BUSY | TRSDISK_DRQ);
      state.bytecount = 0;
    }
  }
  return stopped;
}

/* Get the on-disk track data from the current track/side into the buffer */
void
dmk_get_track(DiskState* d)
{
  int res;
  if (d->phytrack == d->u.dmk.curtrack &&
      state.curside == d->u.dmk.curside) return;
  d->u.dmk.curtrack = d->phytrack;
  d->u.dmk.curside = state.curside;
  if (d->u.dmk.curtrack >= d->u.dmk.ntracks ||
      (d->u.dmk.curside && d->u.dmk.nsides == 1)) {
    memset(d->u.dmk.buf, 0, sizeof(d->u.dmk.buf));
    return;
  }
  fseek(d->file, (DMK_HDR_SIZE +
		  (d->u.dmk.curtrack * d->u.dmk.nsides + d->u.dmk.curside)
		  * d->u.dmk.tracklen), 0);
  res = fread(d->u.dmk.buf, d->u.dmk.tracklen, 1, d->file);
  if (res != 1) {
    memset(d->u.dmk.buf, 0, sizeof(d->u.dmk.buf));
    return;
  }    
}


/* Search for a sector on the current physical track.  For JV1 or JV3,
   return its index within the emulated disk's array of sectors.  For
   DMK, get the track into the buffer, return the index of the next
   byte after the header CRC, and set state.bytecount to its size
   code.  Set status and return -1 if there is no such sector.  If
   sector == -1, return the first sector found if any.  If side == 0
   or 1, perform side compare against sector ID; if -1, don't. */
static int
search(int sector, int side)
{
  DiskState *d = &disk[state.curdrive];
  if (d->file == NULL) {
    state.status |= TRSDISK_NOTFOUND;
    return -1;
  }
  if (d->emutype == JV1) { 
    if (d->phytrack < 0 || d->phytrack >= MAXTRACKS ||
	state.curside > 0 || sector >= JV1_SECPERTRK || d->file == NULL ||
	d->phytrack != state.track || state.density == 1 || side == 1) {
      state.status |= TRSDISK_NOTFOUND;
      return -1;
    }
    return JV1_SECPERTRK * d->phytrack + (sector < 0 ? 0 : sector);
  } else if (d->emutype == JV3) {
    int i;
    SectorId *sid;
    if (d->phytrack < 0 || d->phytrack >= MAXTRACKS ||
	state.curside >= JV3_SIDES ||
	(side != -1 && side != state.curside) ||
	d->phytrack != state.track || d->file == NULL) {
      state.status |= TRSDISK_NOTFOUND;
      return -1;
    }
    if (!d->u.jv3.sorted_valid) jv3_sort_ids(state.curdrive);
    i = d->u.jv3.track_start[d->phytrack][state.curside];
    if (i != -1) {
      for (;;) {
	sid = &d->u.jv3.id[d->u.jv3.sorted_id[i]];
	if (sid->track != d->phytrack ||
	    (sid->flags & JV3_SIDE ? 1 : 0) != state.curside) break;
	if ((sector == -1 || sid->sector == sector) &&
	    ((sid->flags & JV3_DENSITY) ? 1 : 0) == state.density) {
	  return d->u.jv3.sorted_id[i];
	}
	i++;
      }
    }
    state.status |= TRSDISK_NOTFOUND;
    return -1;
  } else /* d->emutype == DMK */ {
    /* !!maybe someday start at a point determined by angle() and wrap
       back.  would deal more realistically with disks that have more
       than one of the same sector. */
    int i;
    int incr = dmk_incr(d);

    /* get current phytrack into buffer */
    dmk_get_track(d);

    /* loop through IDAMs in track */
    for (i = 0; i < DMK_TKHDR_SIZE; i+=2) {
      unsigned char *p;

      /* fetch index of next IDAM */
      int idamp = d->u.dmk.buf[i] + (d->u.dmk.buf[i+1] << 8);

      /* fail if no more IDAMs */
      if (idamp == 0) break;

      /* skip IDAM if wrong density */
      if (!d->u.dmk.ignden &&
	  state.density != ((idamp & DMK_DDEN_FLAG) != 0)) continue;

      /* point p to IDAM */
      idamp &= DMK_IDAMP_BITS;
      p = &d->u.dmk.buf[idamp];

      /* fail if IDAM out of range */
      if (idamp >= DMK_TRACKLEN_MAX) break;

      /* initialize ID CRC */
      state.crc = state.density ? 0xcdb4 /* CRC of a1 a1 a1 */ : 0xffff;

      /* sanity check; is this an IDAM at all? */
      if (*p != 0xfe) continue;
      state.crc = calc_crc1(state.crc, *p);
      p += incr;

      /* compare track field of ID */
      if (*p != state.track) continue;
      state.crc = calc_crc1(state.crc, *p);
      p += incr;

      /* compare side field of ID if desired */
      if ((*p & 1) != side && side != -1) continue;
      state.crc = calc_crc1(state.crc, *p);
      p += incr;

      /* compare sector field of ID if desired */
      if (*p != sector && sector != -1) continue;
      state.crc = calc_crc1(state.crc, *p);
      p += incr;

      /* save size code field of ID; caller converts to actual byte count */
      state.bytecount = *p;
      state.crc = calc_crc1(state.crc, *p);
      p += incr;

      /* fold CRC field into computation; result should be 0 */
      state.crc = calc_crc1(state.crc, *p);
      p += incr;
      state.crc = calc_crc1(state.crc, *p);
      p += incr;

      if (state.crc != 0) {
	/* set CRC error flag and look for another ID that matches */
	state.status |= TRSDISK_CRCERR;
	continue;
      } else {
	/* clear CRC error flag in case set for an earlier ID match */
	state.status &= ~TRSDISK_CRCERR;
      }

      /* Found an ID that matches */
      d->u.dmk.nextidam = i + 2; /* remember where the next one is */
      return p - d->u.dmk.buf;
    }
    state.status |= TRSDISK_NOTFOUND;
    return -1;
  }
}


/* Search for the first sector on the current physical track (in
   either density) and return its index within the sorted index array
   (JV3), or index within the sector array (JV1).  Not used for DMK.
   Return -1 if there is no such sector, or if reading JV1 in double
   density.  Don't set TRSDISK_NOTFOUND; leave the caller to do
   that. */
static int
search_adr()
{
  DiskState *d = &disk[state.curdrive];
  if (d->file == NULL) {
    return -1;
  }
  if (d->emutype == JV1) { 
    if (d->phytrack < 0 || d->phytrack >= MAXTRACKS ||
	state.curside > 0 || d->file == NULL || state.density == 1) {
      return -1;
    }
    return JV1_SECPERTRK * d->phytrack;
  } else {
    if (d->phytrack < 0 || d->phytrack >= MAXTRACKS ||
	state.curside >= JV3_SIDES || d->file == NULL) {
      return -1;
    }
    if (!d->u.jv3.sorted_valid) jv3_sort_ids(state.curdrive);
    return d->u.jv3.track_start[d->phytrack][state.curside];
  }
}


void
verify()
{
  /* Verify that head is on the expected track */
  DiskState *d = &disk[state.curdrive];
  if (d->emutype == REAL) {
    real_verify();
  } else if (d->emutype == JV1) {
    if (d->file == NULL) {
      state.status |= TRSDISK_NOTFOUND;
    } if (state.density == 1) {
      state.status |= TRSDISK_NOTFOUND;
    } else if (state.track != d->phytrack) {
      state.status |= TRSDISK_SEEKERR;
    }
  } else {
    search(-1, -1); /* TRSDISK_SEEKERR == TRSDISK_NOTFOUND */
  }
}

/* Return a value in [0,1) indicating how far we've rotated
 * from the leading edge of the index hole */
float
angle()
{
  DiskState *d = &disk[state.curdrive];
  float a;
  /* Set revus to number of microseconds per revolution */
  int revus = d->inches == 5 ? 200000 /* 300 RPM */ : 166666 /* 360 RPM */;
#if TSTATEREV
  /* Lock revolution rate to emulated time measured in T-states */
  /* Minor bug: there will be a glitch when t_count wraps around on
     a 32-bit machine */
  int revt = (int)(revus * z80_state.clockMHz);
  a = ((float)(z80_state.t_count % revt)) / ((float)revt);
#else
  /* Old way: lock revolution rate to real time */
  struct timeval tv;
  gettimeofday(&tv, NULL);
  /* Ignore the seconds field; this is OK if there are a round number
     of revolutions per second */
  a = ((float)(tv.tv_usec % revus)) / ((float)revus);
#endif
  return a;
}

static void
type1_status()
{
  DiskState *d = &disk[state.curdrive];

  switch (cmd_type(state.currcommand)) {
  case 1:
  case 4:
    break;
  default:
    return;
  }

  if (d->file == NULL || (d->emutype == REAL && d->u.real.empty)) {
    state.status |= TRSDISK_INDEX;
  } else {
    if (angle() < trs_disk_holewidth) {
      state.status |= TRSDISK_INDEX;
    } else {
      state.status &= ~TRSDISK_INDEX;
    }
    if (d->writeprot) {
      state.status |= TRSDISK_WRITEPRT;
    } else {
      state.status &= ~TRSDISK_WRITEPRT;
    }
  }
  if (d->phytrack == 0) {
    state.status |= TRSDISK_TRKZERO;
  } else {
    state.status &= ~TRSDISK_TRKZERO;
  }
  /* RDY and HLT inputs are wired together on TRS-80 I/III/4/4P */
  if (state.status & TRSDISK_NOTRDY) {
    state.status &= ~TRSDISK_HEADENGD;
  } else {
    state.status |= TRSDISK_HEADENGD;
  }
}

void
trs_disk_select_write(unsigned char data)
{
  static int old_data = -1;

  if ((trs_disk_debug_flags & DISKDEBUG_FDCREG) && data != old_data) {
    debug("select_write(0x%02x) pc 0x%04x\n", data, reg_PC);
    old_data = data;
  }

  state.status &= ~TRSDISK_NOTRDY;
  if (trs_model == 1) {
    /* Disk 3 and side select share a bit.  You can't have a drive :3
       on a real Model I if any drive is two-sided.  Here we are more
       generous and just forbid drive :3 from being 2-sided. */
    state.curside = ( (data & (TRSDISK_0|TRSDISK_1|TRSDISK_2)) != 0 &&
		      (data & TRSDISK_SIDE) != 0 );
    if (state.curside) data &= ~TRSDISK_SIDE;

  } else {
    state.curside = (data & TRSDISK3_SIDE) != 0;
    state.density = (data & TRSDISK3_MFM) != 0;
    if (data & TRSDISK3_WAIT) {
      /* If there was an event pending, simulate waiting until
	 it was due. */
      if (trs_event_scheduled() != NULL &&
	  trs_event_scheduled() != trs_disk_lostdata) {
	z80_state.t_count = z80_state.sched;
	trs_do_event();
      }
    }
  }
  switch (data & (TRSDISK_0|TRSDISK_1|TRSDISK_2|TRSDISK_3)) {
  case 0:
    state.status |= TRSDISK_NOTRDY;
    break;
  case TRSDISK_0:
    state.curdrive = 0;
    break;
  case TRSDISK_1:
    state.curdrive = 1;
    break;
  case TRSDISK_2:
    state.curdrive = 2;
    break;
  case TRSDISK_3:
    state.curdrive = 3;
    break;
  case TRSDISK_4:
    /* fake value for emulator only */
    state.curdrive = 4;
    break;
  case TRSDISK_5:
    /* fake value for emulator only */
    state.curdrive = 5;
    break;
  case TRSDISK_6:
    /* fake value for emulator only */
    state.curdrive = 6;
    break;
  case TRSDISK_7:
    /* fake value for emulator only */
    state.curdrive = 7;
    break;
  default:
    trs_disk_unimpl(data, "bogus drive select");
    state.status |= TRSDISK_NOTRDY;
    break;
  }

  /* If a drive was selected... */
  if (!(state.status & TRSDISK_NOTRDY)) {
    DiskState *d = &disk[state.curdrive];

    /* Retrigger emulated motor timeout */
    state.motor_timeout = z80_state.t_count +
      MOTOR_USEC * z80_state.clockMHz;
    trs_disk_motoroff_interrupt(0);

    /* If a SIGUSR1 disk change is pending, accept it here */
    if (trs_disk_needchange) {
      trs_disk_change_all();
      trs_disk_needchange = 0;
    }

    /* Update our knowledge of whether there is a real disk present */
    if (d->emutype == REAL) real_check_empty(d);
  }
}

unsigned char
trs_disk_track_read(void)
{
  if (trs_disk_debug_flags & DISKDEBUG_FDCREG) {
    debug("track_read() => 0x%02x pc 0x%04x\n", state.track, reg_PC);
  }
  return state.track;
}

void
trs_disk_track_write(unsigned char data)
{
  if (trs_disk_debug_flags & DISKDEBUG_FDCREG) {
    debug("track_write(0x%02x) pc 0x%04x\n", data, reg_PC);
  }
  state.track = data;
}

unsigned char
trs_disk_sector_read(void)
{
  if (trs_disk_debug_flags & DISKDEBUG_FDCREG) {
    debug("sector_read() => 0x%02x pc 0x%04x\n", state.sector, reg_PC);
  }
  return state.sector;
}

void
trs_disk_set_controller(int controller)
{
  /* Support for more accurate Doubler emulation */
  FDCState tmp_state;
  if (state.controller == controller) return;
  tmp_state.status = state.status;
  tmp_state.track = state.track;
  tmp_state.sector = state.sector;
  tmp_state.data = state.data;
  tmp_state.lastdirection = state.lastdirection;
  state.controller = controller;
  state.status = other_state.status;
  state.track = other_state.track;
  state.sector = other_state.sector;
  state.data = other_state.data;
  state.lastdirection = other_state.lastdirection;
  other_state.status = tmp_state.status;
  other_state.track = tmp_state.track;
  other_state.sector = tmp_state.sector;
  other_state.data = tmp_state.data;
  other_state.lastdirection = tmp_state.lastdirection;
}

void
trs_disk_sector_write(unsigned char data)
{
  if (trs_disk_debug_flags & DISKDEBUG_FDCREG) {
    debug("sector_write(0x%02x) pc 0x%04x\n", data, reg_PC);
  }
  if (trs_model == 1 && (trs_disk_doubler & TRSDISK_TANDY)) {
    switch (data) {
      /* Emulate Radio Shack doubler */
    case TRSDISK_R1791:
      trs_disk_set_controller(TRSDISK_P1791);
      state.density = 1;
      break;
    case TRSDISK_R1771:
      trs_disk_set_controller(TRSDISK_P1771);
      state.density = 0;
      break;
    case TRSDISK_NOPRECMP:
    case TRSDISK_PRECMP:
      /* Nothing for emulator to do */
      break;
    default:
      break;
    }
  }
  state.sector = data;
}

unsigned char
trs_disk_data_read(void)
{
  DiskState *d = &disk[state.curdrive];
  SectorId *sid;
  switch (state.currcommand & TRSDISK_CMDMASK) {

  case TRSDISK_READ:
    if (state.bytecount > 0 && (state.status & TRSDISK_DRQ)) {
      int c;
      if (d->emutype == REAL) { 
	c = d->u.real.buf[size_code_to_size(d->u.real.size_code)
			 - state.bytecount];
      } else if (d->emutype == DMK) {
	c = d->u.dmk.buf[d->u.dmk.curbyte];
	state.crc = calc_crc1(state.crc, c);
	d->u.dmk.curbyte += dmk_incr(d);
      } else {
	c = getc(d->file);
	if (c == EOF) {
	  c = 0xe5;
	  if (d->emutype == JV1) {
	    state.status &= ~TRSDISK_RECTYPE;
	    state.status |= (state.controller == TRSDISK_P1771) ?
	      TRSDISK_1771_FB : TRSDISK_1791_FB;
	  }
	}
      }
      state.data = c;
      state.bytecount--;
      if (state.bytecount <= 0) {
	if (d->emutype == DMK) {
	  state.crc = calc_crc1(state.crc, d->u.dmk.buf[d->u.dmk.curbyte]);
	  d->u.dmk.curbyte += dmk_incr(d);
	  state.crc = calc_crc1(state.crc, d->u.dmk.buf[d->u.dmk.curbyte]);
	  if (state.crc != 0) {
	    state.status |= TRSDISK_CRCERR;
	  }
	}
	state.bytecount = 0;
	state.status &= ~TRSDISK_DRQ;
        trs_disk_drq_interrupt(0);
	if (trs_event_scheduled() == trs_disk_lostdata) {
	  trs_cancel_event();
	}
	trs_schedule_event(trs_disk_done, 0, 64);
      }
    } 
    break;

  case TRSDISK_READADR:
    if (state.bytecount <= 0 || !(state.status & TRSDISK_DRQ)) break;
    if (d->emutype == REAL) {
#if 0
      state.sector = d->u.real.buf[0]; /*179x data sheet says this*/
#else
      state.track = d->u.real.buf[0]; /*let's guess it meant this*/
      state.sector = d->u.real.buf[2]; /*1771 data sheet says this*/
#endif
      state.data = d->u.real.buf[6 - state.bytecount];

    } else if (d->emutype == DMK) {
      state.data = d->u.dmk.buf[d->u.dmk.curbyte];
#if 0
      if (state.bytecount == 6) {
	state.sector = state.data; /*179x data sheet says this*/
      }
#else
      if (state.bytecount == 6) {
	state.track = state.data; /*let's guess it meant this!!*/
      } else if (state.bytecount == 4) {
	state.sector = state.data;  /*1771 data sheet says this*/
      }
#endif
      d->u.dmk.curbyte += dmk_incr(d);

    } else if (state.last_readadr >= 0) {
      if (d->emutype == JV1) {
	switch (state.bytecount) {
	case 6:
	  state.data = d->phytrack;
#if 0
	  state.sector = d->phytrack; /*179x data sheet says this*/
#else
	  state.track = d->phytrack; /*let's guess it meant this*/
#endif
	  break;
	case 5:
	  state.data = 0;
	  break;
	case 4:
	  state.data = jv1_interleave[state.last_readadr % JV1_SECPERTRK];
	  state.sector = state.data;  /*1771 data sheet says this*/
	  break;
	case 3:
	  state.data = 0x01;  /* 256 bytes always */
	  break;
	case 2:
	case 1:
	  state.data = state.crc >> 8;
	  break;
	}
      } else if (d->emutype == JV3) {
	sid = &d->u.jv3.id[d->u.jv3.sorted_id[state.last_readadr]];
	switch (state.bytecount) {
	case 6:
	  state.data = sid->track;
#if 0
	  state.sector = sid->track; /*179x data sheet says this*/
#else
	  state.track = sid->track; /*let's guess it meant this*/
#endif
	  break;
	case 5:
	  state.data = (sid->flags & JV3_SIDE) != 0;
	  break;
	case 4:
	  state.data = sid->sector;
	  state.sector = sid->sector;  /*1771 data sheet says this*/
	  break;
	case 3:
	  state.data =
	    id_index_to_size_code(d, d->u.jv3.sorted_id[state.last_readadr]);
	  break;
	case 2:
	case 1:
	  state.data = state.crc >> 8;
	  break;
	}
      }
    }
    state.crc = calc_crc1(state.crc, state.data);
    state.bytecount--;
    if (state.bytecount <= 0) {
      if (d->emutype == DMK && state.crc != 0) {
	state.status |= TRSDISK_CRCERR;
      }
      state.bytecount = 0;
      state.status &= ~TRSDISK_DRQ;
      trs_disk_drq_interrupt(0);
      if (trs_event_scheduled() == trs_disk_lostdata) {
	trs_cancel_event();
      }
      trs_schedule_event(trs_disk_done, 0, 64);
    }
    break;

  case TRSDISK_READTRK:
    /* assert(emutype == DMK) */
    if (!(state.status & TRSDISK_DRQ)) break;
    if (state.bytecount > 0) {
      state.data = d->u.dmk.buf[d->u.dmk.curbyte];
      d->u.dmk.curbyte += dmk_incr(d);
      state.bytecount = state.bytecount - 2 + state.density;
    }
    if (state.bytecount <= 0) {
      state.bytecount = 0;
      state.status &= ~TRSDISK_DRQ;
      trs_disk_drq_interrupt(0);
      if (trs_event_scheduled() == trs_disk_lostdata) {
	trs_cancel_event();
      }
      trs_schedule_event(trs_disk_done, 0, 64);
    }
    break;

  default:
    break;
  }
  if (trs_disk_debug_flags & DISKDEBUG_FDCREG) {
    debug("data_read() => 0x%02x pc 0x%04x\n", state.data, reg_PC);
  }
  return state.data;
}

void
trs_disk_data_write(unsigned char data)
{
  DiskState *d = &disk[state.curdrive];
  int c;

  if (trs_disk_debug_flags & DISKDEBUG_FDCREG) {
    debug("data_write(0x%02x) pc 0x%04x\n", data, reg_PC);
  }
  switch (state.currcommand & TRSDISK_CMDMASK) {
  case TRSDISK_WRITE:
    if (state.bytecount > 0) {
      if (d->emutype == REAL) {
	d->u.real.buf[size_code_to_size(d->u.real.size_code)
		     - state.bytecount] = data;
	state.bytecount--;
	if (state.bytecount <= 0) {
	  real_write();
	}
	break;
      }
      c = putc(data, d->file);
      if (c == EOF) state.status |= TRSDISK_WRITEFLT;
      if (d->emutype == DMK) {
	d->u.dmk.buf[d->u.dmk.curbyte++] = data;
	if (dmk_incr(d) == 2) {
	  d->u.dmk.buf[d->u.dmk.curbyte++] = data;
	  c = putc(data, d->file);
	  if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	}
	state.crc = calc_crc1(state.crc, data);
      }	
      state.bytecount--;
      if (state.bytecount <= 0) {
	if (d->emutype == DMK) {
	  int idamp, i, j;
	  c = state.crc >> 8;
	  d->u.dmk.buf[d->u.dmk.curbyte++] = c;
	  c = putc(c, d->file);
	  if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	  if (dmk_incr(d) == 2) {
	    d->u.dmk.buf[d->u.dmk.curbyte++] = c;
	    c = putc(c, d->file);
	    if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	  }
	  c = state.crc & 0xff;
	  d->u.dmk.buf[d->u.dmk.curbyte++] = c;
	  c = putc(c, d->file);
	  if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	  if (dmk_incr(d) == 2) {
	    d->u.dmk.buf[d->u.dmk.curbyte++] = c;
	    c = putc(c, d->file);
	    if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	  }
	  /* Check if we smashed one or more following IDAMs; can
	     happen with weird "protected" formats */
	  i = j = d->u.dmk.nextidam;
	  while (i < DMK_TKHDR_SIZE) {
	    idamp = (d->u.dmk.buf[i] + (d->u.dmk.buf[i+1] << 8))
	      & DMK_IDAMP_BITS;
	    if (idamp != 0 && idamp != DMK_IDAMP_BITS &&
		d->u.dmk.curbyte /*!!+ erase shutoff slop?*/ > idamp) {
	      /* Yes, smashed this one */
	      i += 2;
	      if (trs_disk_debug_flags & DISKDEBUG_DMK) {
		debug("DMK smashed phytk %d physec %d\n", d->phytrack, i/2);
	      }
	    } else {
	      /* No, keep this one */
	      if (j == i) break; /* none were smashed; early exit */
	      d->u.dmk.buf[j++] = d->u.dmk.buf[i++];
	      d->u.dmk.buf[j++] = d->u.dmk.buf[i++];
	    }
	  }
	  if (j != i) {
	    /* Smashed at least one; rewrite the track header */
	    while (j < DMK_TKHDR_SIZE) {
	      d->u.dmk.buf[j++] = 0;
	    }
	    fseek(d->file, DMK_HDR_SIZE +
		  (d->phytrack * d->u.dmk.nsides + state.curside) *
		  d->u.dmk.tracklen, 0);
	    c = fwrite(d->u.dmk.buf, DMK_TKHDR_SIZE, 1, d->file);
	    if (c != 1) state.status |= TRSDISK_WRITEFLT;
	  }
	}
	state.bytecount = 0;
	state.status &= ~TRSDISK_DRQ;
        trs_disk_drq_interrupt(0);
	if (trs_event_scheduled() == trs_disk_lostdata) {
	  trs_cancel_event();
	}
	trs_schedule_event(trs_disk_done, 0, 64);
	c = fflush(d->file);
	if (c == EOF) state.status |= TRSDISK_WRITEFLT;
      }
    }
    break;
  case TRSDISK_WRITETRK:
    state.bytecount = state.bytecount - 2 + state.density;
    if (d->emutype == DMK) {
      if (state.bytecount <= 0) {
	if (state.format != FMT_DONE) {
	  if (trs_disk_debug_flags & DISKDEBUG_DMK) {
	    debug("complete track format dens %d tk %d side %d\n",
		  state.density, d->phytrack, state.curside);
	  }
	  state.format = FMT_DONE;
	  state.status &= ~TRSDISK_DRQ;
	  /* Done: write modified track */
	  fseek(d->file, DMK_HDR_SIZE +
		(d->phytrack * d->u.dmk.nsides + state.curside) *
		d->u.dmk.tracklen, 0);
	  c = fwrite(d->u.dmk.buf, d->u.dmk.tracklen, 1, d->file);
	  if (c != 1) state.status |= TRSDISK_WRITEFLT;
	  if (d->phytrack >= d->u.dmk.ntracks) {
	    d->u.dmk.ntracks = d->phytrack + 1;
	    fseek(d->file, DMK_NTRACKS, 0);
	    putc(d->u.dmk.ntracks, d->file);
	  }
	  c = fflush(d->file);
	  if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	  trs_disk_drq_interrupt(0);
	  if (trs_event_scheduled() == trs_disk_lostdata) {
	    trs_cancel_event();
	  }
	  trs_schedule_event(trs_disk_done, 0, 64);
	}
      } else {
	switch (data) {
	case 0xf5:
	  if (state.density) {
	    data = 0xa1;
	    state.format = FMT_PREAM;
	    state.crc = 0x968b;  /* CRC of a1 a1 */
	  } else {
	    state.format = FMT_DATA;
	  }
	  break;
	case 0xf6:
	  if (state.density) {
	    data = 0xc2;
	    state.format = FMT_IPREAM;
	  } else {
	    state.format = FMT_DATA;
	  }
	  break;
	case 0xf7:
	  data = state.crc >> 8;
	  d->u.dmk.buf[d->u.dmk.curbyte++] = data;
	  if (dmk_incr(d) == 2) {
	    d->u.dmk.buf[d->u.dmk.curbyte++] = data;
	  }
	  state.bytecount = state.bytecount - 2 + state.density;
	  data = state.crc & 0xff;
	  state.format = FMT_DATA;
	  break;
	case 0xfe:
	  if (!state.density || state.format == FMT_PREAM) {
	    unsigned short idamp = d->u.dmk.curbyte +
	      (state.density ? DMK_DDEN_FLAG : 0);
	    if (d->u.dmk.nextidam >= DMK_TKHDR_SIZE) {
	      error("DMK formatting too many address marks on track");
	    } else if (d->u.dmk.curbyte > d->u.dmk.tracklen) {
	      error("DMK address mark past end of track");
	    } else {
	      d->u.dmk.buf[d->u.dmk.nextidam++] = idamp & 0xff;
	      d->u.dmk.buf[d->u.dmk.nextidam++] = idamp >> 8;
	    }
	  }
	  state.format = FMT_DATA;
	  if (!state.density) {
	    state.crc = 0xffff;
	  }
	  break;
#if DMK_MARK_IAM
	  /* Mark IAMs in the track header like IDAMs.  This turns
	     out to cause bogus errors when doing Read Address commands
	     both in current versions of David Keil's emulator and in
	     xtrs 4.5a and earlier, so we disable it, at least for now. */
	case 0xfc:
	  if (!state.density || state.format == FMT_IPREAM) {
	    unsigned short idamp = d->u.dmk.curbyte +
	      (state.density ? DMK_DDEN_FLAG : 0);
	    if (d->u.dmk.nextidam >= DMK_TKHDR_SIZE) {
	      error("DMK formatting too many address marks on track");
	    } else if (d->u.dmk.curbyte > d->u.dmk.tracklen) {
	      error("DMK address mark past end of track");
	    } else {
	      d->u.dmk.buf[d->u.dmk.nextidam++] = idamp & 0xff;
	      d->u.dmk.buf[d->u.dmk.nextidam++] = idamp >> 8;
	    }
	  }
	  state.format = FMT_DATA;
	  break;
#endif
	case 0xf8:
	case 0xf9:
	case 0xfa:
	case 0xfb:
	  if (!state.density) {
	    state.crc = 0xffff;
	  }
	  state.format = FMT_DATA;
	  break;
	default:
	  state.format = FMT_DATA;
	  break;
	}
	d->u.dmk.buf[d->u.dmk.curbyte++] = data;
	if (dmk_incr(d) == 2) {
	  d->u.dmk.buf[d->u.dmk.curbyte++] = data;
	}
	state.crc = calc_crc1(state.crc, data);
      }	
      break;
    }
    if (state.bytecount <= 0) {
      if (state.format == FMT_DONE) break;
      if (state.format == FMT_GAP2) {
	/* False ID: there was no DAM for following data */
	if (d->emutype != JV3) {
	  trs_disk_unimpl(state.currcommand, "false sector ID (no data)");
	} else {
	  /* We do not have a flag for this; try using CRC error */
	  d->u.jv3.id[state.format_sec].flags |= JV3_ERROR;
	  error("warning: recording false sector ID as CRC error");

	  /* Write the sector id */
	  fseek(d->file, idoffset(d, state.format_sec), 0);
	  c = fwrite(&d->u.jv3.id[state.format_sec],
		     sizeof(SectorId), 1, d->file);
	  if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	}
      } else if (state.format != FMT_GAP3) {
	/* If not in FMT_GAP3 state, format data was either too long,
	   had extra garbage following, or was intentionally non-
	   standard.  SuperUtility does a few tricks like "software
	   bulk erase" and duplication of protected disks, so we
	   do not complain about this any more. */
#if BOGUS
	error("format data end is not in gap4");
#endif
	state.format_gap[4] = 0;
      } else {
	/* This was really GAP4 */
	state.format_gap[4] = state.format_gapcnt;
	state.format_gapcnt = 0;
      }
      if (trs_disk_debug_flags & DISKDEBUG_GAPS) {
	debug("trk %d side %d gap0 %d gap1 %d gap2 %d gap3 %d gap4 %d\n",
	      d->phytrack, state.curside,
	      state.format_gap[0], state.format_gap[1], state.format_gap[2], 
	      state.format_gap[3], state.format_gap[4]);
      }
      state.format = FMT_DONE;
      state.status &= ~TRSDISK_DRQ;
      if (d->emutype == REAL) {
	real_writetrk();
      } else {
	c = fflush(d->file);
	if (c == EOF) state.status |= TRSDISK_WRITEFLT;
      }
      trs_disk_drq_interrupt(0);
      if (trs_event_scheduled() == trs_disk_lostdata) {
	trs_cancel_event();
      }
      trs_schedule_event(trs_disk_done, 0, 64);
      break;
    }
    switch (state.format) {
    case FMT_GAP0:
      if (data == 0xfc) {
	state.format = FMT_GAP1;
	state.format_gap[0] = state.format_gapcnt;
	state.format_gapcnt = 0;
      } else if (data == 0xfe) {
	/* There wasn't a gap 0; we were really in gap 1 */
	state.format_gap[0] = 0;
	goto got_idam;
      } else {
	state.format_gapcnt++;
      }
      break;
    case FMT_GAP1:
      if (data == 0xfe) {
      got_idam:
	/* We've received the first ID address mark */
	state.format_gap[1] = state.format_gapcnt;
	state.format_gapcnt = 0;
	state.format = FMT_TRACKID;
      } else {
	state.format_gapcnt++;
      }
      break;
    case FMT_GAP3:
      if (data == 0xfe) {
      got_idam2:
	/* We've received an ID address mark */
	state.format_gap[3] = state.format_gapcnt;
	state.format_gapcnt = 0;
	state.format = FMT_TRACKID;
      } else {
	state.format_gapcnt++;
      }
      break;
    case FMT_TRACKID:
      if (d->emutype == REAL) {
	if (d->u.real.fmt_nbytes >= sizeof(d->u.real.buf)) {
	  /* Data structure full */
	  state.status |= TRSDISK_WRITEFLT;
	  state.bytecount = 0;
	  state.format_bytecount = 0;
	  state.format = FMT_DONE;
	} else {
	  d->u.real.buf[d->u.real.fmt_nbytes++] = data;
	  state.format = FMT_HEADID;
	}
      } else {
	if (data != d->phytrack) {
	  trs_disk_unimpl(state.currcommand, "false track number");
	}
	state.format = FMT_HEADID;
      }
      break;
    case FMT_HEADID:
      if (d->emutype == REAL) {
	d->u.real.buf[d->u.real.fmt_nbytes++] = data;
      } else if (d->emutype == JV1) {
	if (data != 0) {
	  trs_disk_unimpl(state.currcommand, "JV1 double sided");
	}
	if (state.density) { 
	  trs_disk_unimpl(state.currcommand, "JV1 double density");
	}
      } else {
	if (data != state.curside) {
	  trs_disk_unimpl(state.currcommand, "false head number");
	}
      }
      state.format = FMT_SECID;
      break;
    case FMT_SECID:
      if (d->emutype == REAL) {
	d->u.real.buf[d->u.real.fmt_nbytes++] = data;
      } else if (d->emutype == JV1) {
	if (data >= JV1_SECPERTRK) {
	  trs_disk_unimpl(state.currcommand, "JV1 sector number >= 10");
	}
      } else {
	state.format_sec = data;
      }
      state.format = FMT_SIZEID;
      break;
    case FMT_SIZEID:
      if (data > 0x03) {
	trs_disk_unimpl(state.currcommand, "invalid sector size");
      }
      if (d->emutype == JV3) {
	int id_index;
	id_index = jv3_alloc_sector(d, data);
	if (id_index == -1) {
	  /* Data structure full */
	  state.status |= TRSDISK_WRITEFLT;
	  state.bytecount = 0;
	  state.format_bytecount = 0;
	  state.format = FMT_DONE;
	  break;
	}
	d->u.jv3.sorted_valid = 0;
	d->u.jv3.id[id_index].track = d->phytrack;
	d->u.jv3.id[id_index].sector = state.format_sec;
	d->u.jv3.id[id_index].flags =
	  (state.curside ? JV3_SIDE : 0) | (state.density ? JV3_DENSITY : 0) |
	  ((data & 3) ^ 1);
	state.format_sec = id_index;

      } else if (d->emutype == REAL) {
	d->u.real.buf[d->u.real.fmt_nbytes++] = data;
	if (d->u.real.size_code != -1 && d->u.real.size_code != data) {
	  trs_disk_unimpl(state.currcommand,
			  "varying sector size on same track on real floppy");
	}
	d->u.real.size_code = data;
      } else {
	if (data != 0x01) {
	  trs_disk_unimpl(state.currcommand, "sector size != 256");
	}
      }
      state.format = FMT_GAP2;
      break;
    case FMT_GAP2:
      if ((data & 0xfc) == 0xf8) {
	/* Found a DAM */
        if (d->emutype == REAL) {
	  switch (data) {
	  case 0xfb:  /* Standard DAM */
	    break;
	  case 0xfa:
	    if (state.density) {
	      /* This DAM is illegal, but SuperUtility uses it, so
		 ignore the error.  This seems to be a bug in SU for
		 Model I, where it meant to use F8 instead.  I think
		 the WD controller would read back the FA as FB, so we
		 treat it as FB here.  */
	    } else {
	      if (trs_disk_truedam) {
		error("format DAM FA on real floppy");
	      }
	    }
	    break;
	  case 0xf9:
	    if (trs_disk_truedam) {
	      error("format DAM F9 on real floppy");
	    }
	    break;
	  case 0xf8:
	    /* This is probably needed by Model III TRSDOS, but it is
	       a pain to implement.  We would have to remember to do a
	       Write Deleted after the format is complete to change
	       the DAM.
	    */
	    error("format DAM F8 on real floppy");
	    break;
	  }
	} else if (d->emutype == JV1) {
          switch (data) {
	  case 0xf9:
	    trs_disk_unimpl(state.currcommand, "JV1 DAM cannot be F9");
	    break;
	  case 0xf8:
	  case 0xfa:
	    if (d->phytrack != 17) 
	      trs_disk_unimpl(state.currcommand,
			      "JV1 directory track must be 17");
	    break;
	  default: /* impossible */
	  case 0xfb:
	    break;
	  }
	} else /* JV3 */ {
	  if (state.density) {
	    /* Double density */
	    switch (data) {
	    case 0xf8: /* Standard deleted DAM */
	    case 0xf9: /* Illegal, probably never used; ignore error. */
	      d->u.jv3.id[state.format_sec].flags |= JV3_DAMDDF8;
	      break;
	    case 0xfb: /* Standard DAM */
	    case 0xfa: /* Illegal, but SuperUtility uses it! */
	    default:   /* Impossible */
	      d->u.jv3.id[state.format_sec].flags |= JV3_DAMDDFB;
	      break;
	    }
	  } else {
	    /* Single density */
	    switch (data) {
	    case 0xf8:
	      if (trs_disk_truedam) {
		d->u.jv3.id[state.format_sec].flags |= JV3_DAMSDF8;
	      } else {
		d->u.jv3.id[state.format_sec].flags |= JV3_DAMSDFA;
	      }
	      break;
	    case 0xf9:
	      d->u.jv3.id[state.format_sec].flags |= JV3_DAMSDF9;
	      break;
	    case 0xfa:
	      d->u.jv3.id[state.format_sec].flags |= JV3_DAMSDFA;
	      break;
	    default: /* impossible */
	    case 0xfb:
	      d->u.jv3.id[state.format_sec].flags |= JV3_DAMDDFB;
	      break;
	    }
	  }
	}
	if (d->emutype == JV3) {
	  /* Prepare to write the data */
	  fseek(d->file, offset(d, state.format_sec), 0);
	  state.format_bytecount = id_index_to_size(d, state.format_sec);
	} else if (d->emutype == JV1) {
	  state.format_bytecount = JV1_SECSIZE;
	} else if (d->emutype == REAL) {
	  state.format_bytecount = size_code_to_size(d->u.real.size_code);
	}
	state.format_gap[2] = state.format_gapcnt;
	state.format_gapcnt = 0;
	state.format = FMT_DATA;
      } else if (data == 0xfe) {
	/* False ID: there was no DAM for following data */
	if (d->emutype != JV3) {
	  trs_disk_unimpl(state.currcommand, "false sector ID (no data)");
	} else {
	  /* We do not have a flag for this; try using CRC error */
	  error("warning: recording false sector ID as CRC error");
	  d->u.jv3.id[state.format_sec].flags |= JV3_ERROR;

	  /* Write the sector id */
	  fseek(d->file, idoffset(d, state.format_sec), 0);
	  c = fwrite(&d->u.jv3.id[state.format_sec], sizeof(SectorId), 1, d->file);
	  if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	}
	goto got_idam2;
      } else {
	state.format_gapcnt++;
      }
      break;
    case FMT_DATA:
      if (data == 0xfe) {
	/* Short sector with intentional CRC error */
	if (d->emutype == JV3) {
	  d->u.jv3.id[state.format_sec].flags |= JV3_NONIBM | JV3_ERROR;
	  if (trs_disk_debug_flags & DISKDEBUG_VTOS3) {
	    debug("non-IBM sector: drv 0x%02x, sid %d,"
		  " trk 0x%02x, sec 0x%02x\n",
		  state.curdrive, state.curside,
		  d->u.jv3.id[state.format_sec].track, 
		  d->u.jv3.id[state.format_sec].sector);
	  }
	  /* Write the sector id */
	  fseek(d->file, idoffset(d, state.format_sec), 0);
	  c = fwrite(&d->u.jv3.id[state.format_sec],
		     sizeof(SectorId), 1, d->file);
	  if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	  goto got_idam;
	} else {
	  trs_disk_unimpl(state.currcommand, "JV1 non-IBM sector");
	}
      }
      if (d->emutype == JV3) {
	c = putc(data, d->file);
	if (c == EOF) state.status |= TRSDISK_WRITEFLT;
      } else if (d->emutype == REAL) {
	d->u.real.fmt_fill = data;
      }
      if (--state.format_bytecount <= 0) {
	state.format = FMT_DCRC;
      }
      break;
    case FMT_DCRC:
      if (data == 0xf7) {
	state.bytecount--;  /* two bytes are written */
      } else {
	/* Intentional CRC error */
	if (d->emutype != JV3) {
	  trs_disk_unimpl(state.currcommand, "intentional CRC error");
	} else {
	  d->u.jv3.id[state.format_sec].flags |= JV3_ERROR;
	}
      }
      if (d->emutype == JV3) {
	/* Write the sector id */
	fseek(d->file, idoffset(d, state.format_sec), 0);
	c = fwrite(&d->u.jv3.id[state.format_sec], sizeof(SectorId), 1, d->file);
	if (c == EOF) state.status |= TRSDISK_WRITEFLT;
      }
      state.format = FMT_GAP3;
      break;
    case FMT_DONE:
      break;
    case FMT_GAP4:
    case FMT_IAM:
    case FMT_IDAM:
    case FMT_IDCRC:
    case FMT_DAM:
    default:
      error("error in format state machine");
      break;
    }      
  default:
    break;
  }
  state.data = data;
  return;
}

unsigned char
trs_disk_status_read(void)
{
  static int last_status = -1;

  if (trs_disk_nocontroller) return 0xff;
  type1_status();
  if (!(state.status & TRSDISK_NOTRDY)) {
    if (state.motor_timeout - z80_state.t_count > TSTATE_T_MID) {
      /* Subtraction wrapped; motor stopped */
      state.status |= TRSDISK_NOTRDY;
    }
  }
  if ((trs_disk_debug_flags & DISKDEBUG_FDCREG) &&
      state.status != last_status) {
    debug("status_read() => 0x%02x pc 0x%04x\n", state.status, reg_PC);
    last_status = state.status;
  }

#if BOGUS
  /* Clear intrq unless user did a Force Interrupt with immediate interrupt. */
  /* The 17xx data sheets say this is how it is supposed to work, but it
   * makes Model I SuperUtility hang due to the interrupt routine failing
   * to clear the interrupt.  I suspect the data sheets are wrong.
   */
  if (!(((state.currcommand & TRSDISK_CMDMASK) == TRSDISK_FORCEINT) &&
	((state.currcommand & 0x08) != 0)))
#else
  /* Clear intrq always */
#endif
    {
      /* Don't call trs_schedule_event, which could cancel a pending
       *  interrupt that should occur later and prevent it from ever
       *  happening; just clear the interrupt right now.
       */
      trs_disk_intrq_interrupt(0);
    }

  return state.status;
}

void
trs_disk_command_write(unsigned char cmd)
{
  int id_index, non_ibm, goal_side, new_status;
  DiskState *d = &disk[state.curdrive];
  trs_event_func event;

  if (trs_disk_debug_flags & DISKDEBUG_FDCREG) {
    debug("command_write(0x%02x) pc 0x%04x\n", cmd, reg_PC);
  }

  /* Handle DMK partial track reformat */
  if (d->emutype == DMK &&
      (state.currcommand & ~TRSDISK_EBIT) == TRSDISK_WRITETRK &&
      state.format != FMT_DONE) {
    /* Interrupted format: must write out partial track */
    unsigned char oldtkhdr[DMK_TKHDR_SIZE];
    int c, i, j, idamp;

    if (trs_disk_debug_flags & DISKDEBUG_DMK) {
      debug("partial track format dens %d tk %d side %d\n",
	    state.density, d->phytrack, state.curside);
    }

    /* Fetch old IDAM pointers if any */
    fseek(d->file, DMK_HDR_SIZE +
	  (d->phytrack * d->u.dmk.nsides + state.curside) *
	  d->u.dmk.tracklen, 0);
    c = fread(oldtkhdr, DMK_TKHDR_SIZE, 1, d->file);
    if (c == 1) {
      /* Copy any pointers to IDAMs that are not being overwritten */
      i = 0;
      j = d->u.dmk.nextidam;
      while (i < DMK_TKHDR_SIZE) {
	idamp = (oldtkhdr[i] + (oldtkhdr[i+1] << 8)) & DMK_IDAMP_BITS;
	if (idamp == 0 || idamp == DMK_IDAMP_BITS) break;
	if (idamp < d->u.dmk.curbyte) {
	  /* IDAM overwritten; don't copy */
	  i += 2;
	  if (trs_disk_debug_flags & DISKDEBUG_DMK) {
	    debug("  discarding physec %d\n", i);
	  }
	} else {
	  /* IDAM not overwritten; need to copy in */
	  if (j >= DMK_TKHDR_SIZE) {
	    /* No room */
	    error("DMK reformatting adds too many sectors to track");
	    break;
	  }
	  d->u.dmk.buf[j++] = oldtkhdr[i++];
	  d->u.dmk.buf[j++] = oldtkhdr[i++];
	  if (trs_disk_debug_flags & DISKDEBUG_DMK) {
	    debug("  preserving physec %d as %d\n", i, j);
	  }
	}
      }
    } else {
      if (trs_disk_debug_flags & DISKDEBUG_FDCREG) {
	debug("  no existing sectors\n");
      }
    }
    /* Write modified portion of track only */
    fseek(d->file, DMK_HDR_SIZE +
	  (d->phytrack * d->u.dmk.nsides + state.curside) *
	  d->u.dmk.tracklen, 0);
    fwrite(d->u.dmk.buf, d->u.dmk.curbyte, 1, d->file);
    if (d->phytrack >= d->u.dmk.ntracks) {
      d->u.dmk.ntracks = d->phytrack + 1;
      fseek(d->file, DMK_NTRACKS, 0);
      putc(d->u.dmk.ntracks, d->file);
    }
    fflush(d->file);

    /* Invalidate buffer since not all data is here */
    d->u.dmk.curtrack = d->u.dmk.curside = -1;
    state.format = FMT_DONE;
  }

  /* Cancel any ongoing command */
  event = trs_event_scheduled();
  if (event == trs_disk_lostdata || event == trs_disk_intrq_interrupt) {
    trs_cancel_event();
  }
  trs_disk_intrq_interrupt(0);
  state.bytecount = 0;
  state.currcommand = cmd;
  switch (cmd & TRSDISK_CMDMASK) {

  case TRSDISK_RESTORE:
    if (trs_disk_debug_flags & DISKDEBUG_FDCCMD) {
      debug("restore 0x%02x drv %d\n", cmd, state.curdrive);
    }
    state.last_readadr = -1;
    d->phytrack = 0;
    state.track = 0;
    state.status = TRSDISK_TRKZERO|TRSDISK_BUSY;
    if (d->emutype == REAL) real_restore(state.curdrive);
    /* Should this set lastdirection? */
    if (cmd & TRSDISK_VBIT) verify();
    trs_schedule_event(trs_disk_done, 0, 2000);
    break;

  case TRSDISK_SEEK:
    if (trs_disk_debug_flags & DISKDEBUG_FDCCMD) {
      debug("seek 0x%02x drv %d ptk %d otk %d ntk %d\n",
	    cmd, state.curdrive, d->phytrack, state.track, state.data);
    }
    state.last_readadr = -1;
    d->phytrack += (state.data - state.track);
    state.track = state.data;
    if (d->phytrack <= 0) {
      d->phytrack = 0;		/* state.track too? */
      state.status = TRSDISK_TRKZERO|TRSDISK_BUSY;
    } else {
      state.status = TRSDISK_BUSY;
    }
    if (d->emutype == REAL) real_seek();
    /* Should this set lastdirection? */
    if (cmd & TRSDISK_VBIT) verify();
    trs_schedule_event(trs_disk_done, 0, 2000);
    break;

  case TRSDISK_STEP:
  case TRSDISK_STEPU:
  step:
    if (trs_disk_debug_flags & DISKDEBUG_FDCCMD) {
      debug("step%s %s 0x%02x drv %d ptk %d otk %d\n",
	    (cmd & TRSDISK_UBIT) ? "u" : "",
	    (state.lastdirection < 0) ? "out" : "in", cmd,
	    state.curdrive, d->phytrack, state.track);
    }      
    state.last_readadr = -1;
    d->phytrack += state.lastdirection;
    if (cmd & TRSDISK_UBIT) {
      state.track += state.lastdirection;
    }
    if (d->phytrack <= 0) {
      d->phytrack = 0;		/* state.track too? */
      state.status = TRSDISK_TRKZERO|TRSDISK_BUSY;
    } else {
      state.status = TRSDISK_BUSY;
    }
    if (d->emutype == REAL) real_seek();
    if (cmd & TRSDISK_VBIT) verify();
    trs_schedule_event(trs_disk_done, 0, 2000);
    break;

  case TRSDISK_STEPIN:
  case TRSDISK_STEPINU:
    state.lastdirection = 1;
    goto step;

  case TRSDISK_STEPOUT:
  case TRSDISK_STEPOUTU:
    state.lastdirection = -1;
    goto step;

  case TRSDISK_READ:
    if (trs_disk_debug_flags & DISKDEBUG_FDCCMD) {
      debug("read 0x%02x drv %d ptk %d tk %d sec %d %sden\n", cmd,
	    state.curdrive, d->phytrack, state.track, state.sector,
	    state.density ? "d" : "s");
    }
    state.last_readadr = -1;
    state.status = 0;
    non_ibm = 0;
    goal_side = -1;
    new_status = 0;
    if (state.controller == TRSDISK_P1771) {
      if (!(cmd & TRSDISK_BBIT)) {
	if (trs_disk_debug_flags & DISKDEBUG_VTOS3) {
	  debug("non-IBM read: drv 0x%02x, sid %d, trk 0x%02x, sec 0x%02x\n",
		state.curdrive, state.curside, state.track, state.sector);
	}
	if (d->emutype == REAL) {
	  trs_disk_unimpl(cmd, "non-IBM read on real floppy");
	}
	non_ibm = 1;
      } else {
	if (trs_disk_debug_flags & DISKDEBUG_VTOS3) {
	  if (state.sector >= 0x7c) {
	    debug("IBM read: drv 0x%02x, sid %d, trk 0x%02x, sec 0x%02x\n",
		  state.curdrive, state.curside, state.track, state.sector);
	  }
	}
      }
    } else {
      if (cmd & TRSDISK_CBIT) {
	goal_side = (cmd & TRSDISK_BBIT) != 0;
      }
    }
    if (d->emutype == REAL) {
      real_read();
      break;
    }
    id_index = search(state.sector, goal_side);
    if (id_index == -1) {
      state.status |= TRSDISK_BUSY;
      trs_schedule_event(trs_disk_done, 0, 512);
    } else {
      if (d->emutype == JV1) {

	if (d->phytrack == 17) {
	  if (state.controller == TRSDISK_P1771) {
	    new_status = TRSDISK_1771_FA;
	  } else {
	    new_status = TRSDISK_1791_F8;
	  }
	}
	state.bytecount = JV1_SECSIZE;
	fseek(d->file, offset(d, id_index), 0);

      } else if (d->emutype == JV3) {

	if (state.controller == TRSDISK_P1771) {
	  switch (d->u.jv3.id[id_index].flags & JV3_DAM) {
	  case JV3_DAMSDFB:
	    new_status = TRSDISK_1771_FB;
	    break;
	  case JV3_DAMSDFA:
	    new_status = TRSDISK_1771_FA;
	    break;
	  case JV3_DAMSDF9:
	    new_status = TRSDISK_1771_F9;
	    break;
	  case JV3_DAMSDF8:
	    new_status = TRSDISK_1771_F8;
	    break;
	  }
	} else if (state.density == 0) {
	  /* single density 179x */
	  switch (d->u.jv3.id[id_index].flags & JV3_DAM) {
	  case JV3_DAMSDFB:
	    new_status = TRSDISK_1791_FB;
	    break;
	  case JV3_DAMSDFA:
	    if (trs_disk_truedam) {
	      new_status = TRSDISK_1791_FB;
	    } else {
	      new_status = TRSDISK_1791_F8;
	    }
	    break;
	  case JV3_DAMSDF9:
	    new_status = TRSDISK_1791_F8;
	    break;
	  case JV3_DAMSDF8:
	    new_status = TRSDISK_1791_F8;
	    break;
	  }
	} else {
	  /* double density 179x */
	  switch (d->u.jv3.id[id_index].flags & JV3_DAM) {
	  default: /*impossible*/
	  case JV3_DAMDDFB:
	    new_status = TRSDISK_1791_FB;
	    break;
	  case JV3_DAMDDF8:
	    new_status = TRSDISK_1791_F8;
	    break;
	  }
	}
	if (d->u.jv3.id[id_index].flags & JV3_ERROR) {
	  new_status |= TRSDISK_CRCERR;
	}
	if (non_ibm) {
	  state.bytecount = 16;
	} else {
	  state.bytecount = id_index_to_size(d, id_index);
	}
	fseek(d->file, offset(d, id_index), 0);

      } else /* d->emutype == DMK */ {

	/* max distance past ID CRC to search for DAM */
	int damlimit = state.density ? 43 : 30; /* ref 1791 datasheet */
	unsigned char dam = 0;

	/* DMK search dumps the size code into state.bytecount; adjust
           to real bytecount here */
	if (non_ibm) {
	  state.bytecount = 16 * (((state.bytecount - 1)&0xff)+1);
	} else {
	  state.bytecount = 128 << (state.bytecount & 3);
	}

	/* search for valid DAM */
	while (--damlimit >= 0) {
	  dam = d->u.dmk.buf[id_index];
	  id_index += dmk_incr(d);
	  if (0xf8 <= dam && dam <= 0xfb) {
	    /* got one! */
	    break;
	  }
	}
	if (damlimit < 0) {
	  /* found ID with good CRC but no following DAM; fail */
	  state.status |= TRSDISK_BUSY;
	  trs_schedule_event(trs_disk_done, TRSDISK_NOTFOUND, 512);
	  break;
	}

	/* Set flags for DAM */
	if (state.controller == TRSDISK_P1771) {
	  /* 1771 */
	  switch (dam) {
	  case 0xfb:
	    new_status = TRSDISK_1771_FB;
	    break;
	  case 0xfa:
	    new_status = TRSDISK_1771_FA;
	    break;
	  case 0xf9:
	    new_status = TRSDISK_1771_F9;
	    break;
	  case 0xf8:
	    new_status = TRSDISK_1771_F8;
	    break;
	  }
	} else /* state.controller == TRSDISK_P1791 */ {
	  switch (dam) {
	  case 0xfb:
	    new_status = TRSDISK_1791_FB;
	    break;
	  case 0xfa:
	    /* Note: Illegal in DDEN but Write Track can still
	       generate it, and of course 1771 can generate in SDEN */
	    if (trs_disk_truedam) {
	      new_status = TRSDISK_1791_FB;
	    } else {
	      new_status = TRSDISK_1791_F8;
	    }
	    break;
	  case 0xf9:
	    /* Note: Illegal in DDEN but Write Track can still
	       generate it, and of course 1771 can generate in SDEN */
	    new_status = TRSDISK_1791_F8;
	    break;
	  case 0xf8:
	    new_status = TRSDISK_1791_F8;
	    break;
	  }
	}
	state.crc = calc_crc1((state.density
			       ? 0xcdb4 /* CRC of a1 a1 a1 */
			       : 0xffff), dam);

	d->u.dmk.curbyte = id_index;

      } /* end if (d->emutype == ...) */

      state.status |= TRSDISK_BUSY;
      trs_schedule_event(trs_disk_firstdrq, new_status, 64);
    }
    break;

  case TRSDISK_READM:
    state.last_readadr = -1;
    trs_disk_unimpl(cmd, "read multiple");
    break;

  case TRSDISK_WRITE:
    if (trs_disk_debug_flags & DISKDEBUG_FDCCMD) {
      debug("write 0x%02x drv %d ptk %d tk %d sec %d %sden\n",
	    cmd, state.curdrive, d->phytrack, state.track, state.sector,
	    state.density ? "d" : "s");
    }
    state.last_readadr = -1;
    state.status = 0;
    non_ibm = 0;
    goal_side = -1;
    if (state.controller == TRSDISK_P1771) {
      if (!(cmd & TRSDISK_BBIT)) {
	if (trs_disk_debug_flags & DISKDEBUG_VTOS3) {
	  debug("non-IBM write drv 0x%02x, sid %d, trk 0x%02x, sec 0x%02x\n",
		state.curdrive, state.curside, state.track, state.sector);
	}
	if (d->emutype == REAL) {
	  trs_disk_unimpl(cmd, "non-IBM write on real floppy");
	}
	non_ibm = 1;
      } else {
	if (trs_disk_debug_flags & DISKDEBUG_VTOS3) {
	  if (state.sector >= 0x7c) {
	    debug("IBM write: drv 0x%02x, sid %d, trk 0x%02x, sec 0x%02x\n",
		  state.curdrive, state.curside, state.track, state.sector);
	  }
	}
      }
    } else {
      if (cmd & TRSDISK_CBIT) {
	goal_side = (cmd & TRSDISK_BBIT) != 0;
      }
    }
    if (d->emutype == REAL) {
      state.status = TRSDISK_BUSY|TRSDISK_DRQ;
      trs_disk_drq_interrupt(1);
      trs_schedule_event(trs_disk_lostdata, state.currcommand,
			 500000 * z80_state.clockMHz);
      state.bytecount = size_code_to_size(d->u.real.size_code);
      break;
    }
    if (d->writeprot) {
      state.status = TRSDISK_WRITEPRT;
      break;
    }
    id_index = search(state.sector, goal_side);
    if (id_index == -1) {
      state.status |= TRSDISK_BUSY;
      trs_schedule_event(trs_disk_done, 0, 512);
    } else {
      int jv3dam = 0, dam = 0;
      if (state.controller == TRSDISK_P1771) {
	switch (cmd & (TRSDISK_CBIT|TRSDISK_DBIT)) {
	case 0:
	  dam = 0xfb;
	  jv3dam = JV3_DAMSDFB;
	  break;
	case 1:
	  dam = 0xfa;
	  jv3dam = JV3_DAMSDFA;
	  break;
	case 2:
	  dam = 0xf9;
	  jv3dam = JV3_DAMSDF9;
	  break;
	case 3:
	  if (trs_disk_truedam) {
	    dam = 0xf8;
	    jv3dam = JV3_DAMSDF8;
	  } else {
	    dam = 0xfa;
	    jv3dam = JV3_DAMSDFA;
	  }
	  break;
	}
      } else if (state.density == 0) {
	/* 179x single */
	switch (cmd & TRSDISK_DBIT) {
	case 0:
	  dam = 0xfb;
	  jv3dam = JV3_DAMSDFB;
	  break;
	case 1:
	  if (trs_disk_truedam) {
	    dam = 0xf8;
	    jv3dam = JV3_DAMSDF8;
	  } else {
	    dam = 0xfa;
	    jv3dam = JV3_DAMSDFA;
	  }
	  break;
	}
      } else {
	/* 179x double */
	switch (cmd & TRSDISK_DBIT) {
	case 0:
	  dam = 0xfb;
	  jv3dam = JV3_DAMDDFB;
	  break;
	case 1:
	  dam = 0xf8;
	  jv3dam = JV3_DAMDDF8;
	  break;
	}
      }

      if (d->emutype == JV1) {
	if (dam == 0xf9) {
	  trs_disk_unimpl(state.currcommand, "JV1 DAM cannot be F9");
	} else if ((dam == 0xfb) == (d->phytrack == 17)) {
	  trs_disk_unimpl(state.currcommand, "JV1 directory must be track 17");
	  break;
	}
	state.bytecount = JV1_SECSIZE;
	fseek(d->file, offset(d, id_index), 0);

      } else if (d->emutype == JV3) {
	SectorId *sid = &d->u.jv3.id[id_index];
	unsigned char newflags = sid->flags;
	newflags &= ~(JV3_ERROR|JV3_DAM); /* clear CRC error and DAM */
	newflags |= jv3dam;
	if (newflags != sid->flags) {
	  int c;
	  fseek(d->file, idoffset(d, id_index) 
		         + ((char *) &sid->flags) - ((char *) sid), 0);
	  c = putc(newflags, d->file);
	  if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	  c = fflush(d->file);
	  if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	  sid->flags = newflags;
	}

	/* Kludge for VTOS 3.0 */
	if (sid->flags & JV3_NONIBM) {
	  int i, j, c;
	  /* Smash following sectors. This is especially a kludge because
	     it uses the sector numbers, not the known physical sector
	     order. */
	  for (i = state.sector+1; i <= 0x7f; i++) {
	    j = search(i, -1);
	    if (j != -1) {
	      if (trs_disk_debug_flags & DISKDEBUG_VTOS3) {
		debug("smashing tk %d sector 0x%02x id_index %d\n",
		      state.track, i, j);
	      }
	      jv3_free_sector(d, j);
	      c = fflush(d->file);
	      if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	    }	      
	    /* Smash only one for non-IBM write */
	    if (non_ibm) break;
	  }
	}
	/* end kludge */

	if (non_ibm) {
	  state.bytecount = 16;
	} else {
	  state.bytecount = id_index_to_size(d, id_index);
	}
	fseek(d->file, offset(d, id_index), 0);

      } else /* d->emutype == DMK */ {
	int c, nzeros, i;
	
	/* DMK search dumps the size code into state.bytecount; adjust
           to real bytecount here */
	if (non_ibm) {
	  state.bytecount = 16 * (((state.bytecount - 1)&0xff)+1);
	} else {
	  state.bytecount = 128 << (state.bytecount & 3);
	}

	/* Skip initial part of gap, per 1771 and 179x data sheets */
	id_index += 11 * (state.density ? 2 : 1) * dmk_incr(d);
	fseek(d->file, (DMK_HDR_SIZE +
			(d->u.dmk.curtrack*d->u.dmk.nsides + d->u.dmk.curside)
			* d->u.dmk.tracklen + id_index), 0);

	/* Write remaining gap (per data sheets) and DAM */
	nzeros = 6 * (state.density ? 2 : 1) * dmk_incr(d);
	for (i=0; i<nzeros; i++) {
	  c = putc(0, d->file);
	  if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	  d->u.dmk.buf[id_index++] = 0;
	}
	if (state.density) {
	  for (i=0; i<3; i++) {
	    c = putc(0xa1, d->file);
	    if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	    d->u.dmk.buf[id_index++] = 0xa1;
	  }	    
	}
	c = putc(dam, d->file);
	if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	d->u.dmk.buf[id_index++] = dam;
	if (dmk_incr(d) == 2) {
	  c = putc(dam, d->file);
	  if (c == EOF) state.status |= TRSDISK_WRITEFLT;
	  d->u.dmk.buf[id_index++] = dam;
	}

	/* Initialize CRC */
	state.crc = calc_crc1((state.density
			       ? 0xcdb4 /* CRC of a1 a1 a1 */
			       : 0xffff), dam);

	d->u.dmk.curbyte = id_index;

      } /* end if (d->emutype == ...) */

      state.status |= TRSDISK_BUSY|TRSDISK_DRQ;
      trs_disk_drq_interrupt(1);
      trs_schedule_event(trs_disk_lostdata, state.currcommand,
			 500000 * z80_state.clockMHz);
    }
    break;

  case TRSDISK_WRITEM:
    state.last_readadr = -1;
    if (d->writeprot) {
      state.status = TRSDISK_WRITEPRT;
      break;
    }
    trs_disk_unimpl(cmd, "write multiple");
    break;

  case TRSDISK_READADR:
    if (trs_disk_debug_flags & DISKDEBUG_FDCCMD) {
      debug("readadr 0x%02x drv %d ptk %d tk %d last %d %sden\n",
	    cmd, state.curdrive, d->phytrack, state.track,
	    state.last_readadr, state.density ? "d" : "s");
    }
    state.data = 0; /* workaround for apparent SU1 bug */
    if (state.density) {
      state.crc = 0xb230;  /* CRC of a1 a1 a1 fe */
    } else {
      state.crc = 0xef21;  /* CRC of fe */
    }
    if (d->emutype == REAL) {
      real_readadr();
      break;
    } else if (d->emutype == JV1 || d->emutype == JV3) {
      int totbyt, i, ts, denok;
      float a, b, bytlen;
      id_index = search_adr();
      if (id_index == -1) {
	state.status = TRSDISK_BUSY;
	state.bytecount = 0;
	trs_schedule_event(trs_disk_done, TRSDISK_NOTFOUND,
			   1000000*z80_state.clockMHz);
	break;
      }
      /* Compute how long it should have taken for this sector to come
	 by and delay by an appropriate number of t-states.  This
	 makes the "A" command in HyperZap work (on emulated floppies
	 only).  It is not terribly useful, since other important HyperZap
	 functions (like mixed-density formatting) do not work, while
	 SuperUtility and Trakcess both work fine without the delay feature.
	 Note: it would probably be better to assume the sectors are
	 positioned using nominal gap sizes (say, the ones that HyperZap
	 uses when generating tracks using the D/G subcommand) instead
	 of the even spacing nonsense below.
      */
      if (d->emutype == JV1) {
	/* Which sector header is next?  Use a rough assumption
	   that the sectors are all the same angular length (bytlen).
	*/
	a = angle();
	bytlen = (1.0 - GAP1ANGLE - GAP4ANGLE)/((float)JV1_SECPERTRK);
	i = (int)( (a - GAP1ANGLE) / bytlen + 1.0 );
	if (i >= JV1_SECPERTRK) {
	  /* Wrap around to start of track */
	  i = 0;
	}
	b = ((float)i) * bytlen + GAP1ANGLE;
	if (b < a) b += 1.0;
	i += id_index;
      } else {
	/* Count data bytes on track.  Also check if there
	   are any sectors of the correct density. */
	i = id_index;
	totbyt = 0;
	denok = 0;
	for (;;) {
	  SectorId *sid = &d->u.jv3.id[d->u.jv3.sorted_id[i]];
	  int dden = (sid->flags & JV3_DENSITY) != 0;
	  if (sid->track != d->phytrack ||
	      (sid->flags & JV3_SIDE ? 1 : 0) != state.curside) break;
	  totbyt += (dden ? 1 : 2) *
	    id_index_to_size(d, d->u.jv3.sorted_id[i]);
	  if (dden == state.density) denok = 1;
	  i++;
	}
	if (!denok) {
	  /* No sectors of the correct density */
	  state.status = TRSDISK_BUSY;
	  state.bytecount = 0;
	  trs_schedule_event(trs_disk_done, TRSDISK_NOTFOUND,
			     1000000*z80_state.clockMHz);
	  break;
	}
	/* Which sector header is next?  Use a rough assumption that
           sectors are evenly spaced, taking up room proportional to
           their data length (and twice as much for single density).
	   Here bytlen = angular size per byte.
	*/
	a = angle();
	b = GAP1ANGLE;
	bytlen = (1.0 - GAP1ANGLE - GAP4ANGLE)/((float)totbyt);
	i = id_index;
	for (;;) {
	  SectorId *sid = &d->u.jv3.id[d->u.jv3.sorted_id[i]];
	  if (sid->track != d->phytrack ||
	      (sid->flags & JV3_SIDE ? 1 : 0) != state.curside) {
	    /* Wrap around to start of track */
	    i = id_index;
	    b = 1 + GAP1ANGLE;
	    break;
	  }
	  if (b > a && (((sid->flags & JV3_DENSITY) != 0) == state.density)) {
	    break;
	  }
	  b += ((sid->flags & JV3_DENSITY) ? 1 : 2) *
  	    id_index_to_size(d, d->u.jv3.sorted_id[i]) * bytlen;
	  i++;
	}
      }
      /* Convert angular delay to t-states */
      ts = (d->inches == 5 ? 200000 : 166667) * (b - a) * z80_state.clockMHz;

      state.status = TRSDISK_BUSY;
      state.last_readadr = i;
      state.bytecount = 6;
      trs_schedule_event(trs_disk_firstdrq, 0, ts);
      if (trs_disk_debug_flags & DISKDEBUG_READADR) {
	debug("readadr phytrack %d angle %f i %d ts %d\n",
	      d->phytrack, a, i, ts);
      }
    } else /* d->emutype == DMK */ {
      /* Compute how far it will be to the next ID in the correct density */
      float a = angle();
      int ia = a * (d->inches ? TRKSIZE_DD : TRKSIZE_8DD);
      int ib = 0;
      int i, j, idamp, dden, prev_idamp, prev_dden, ts;

      dmk_get_track(d);

      for (j = 0; j < 2; j++) {
	idamp = d->u.dmk.buf[0] + (d->u.dmk.buf[1] << 8);
	dden = (idamp & DMK_DDEN_FLAG) != 0;
	idamp = DMK_TKHDR_SIZE;

	for (i = 0; i < DMK_TKHDR_SIZE; i+=2) {
	  prev_idamp = idamp;
	  prev_dden = dden;
	  idamp = d->u.dmk.buf[i] + (d->u.dmk.buf[i+1] << 8);
	  if (idamp == 0) break;
	  dden = (idamp & DMK_DDEN_FLAG) != 0;
	  idamp &= DMK_IDAMP_BITS;
	  if (idamp >= DMK_TRACKLEN_MAX) break;
	  ib += (idamp - prev_idamp) *
	    ((!prev_dden && (d->u.dmk.sden || d->u.dmk.ignden)) ? 2 : 1);
	  if (ib > ia && dden == state.density &&
	      d->u.dmk.buf[idamp] == 0xfe) goto found;
	}
	/* Next ID (if any) is past the index hole */
	ib = (d->inches ? TRKSIZE_DD : TRKSIZE_8DD);
      }
      /* no suitable ID found */
      state.status = TRSDISK_BUSY;
      state.bytecount = 0;
      trs_schedule_event(trs_disk_done, TRSDISK_NOTFOUND,
			 1000000*z80_state.clockMHz);
      break;
    found:
      /* Convert dden byte count to t-states */
      ts = ((float) ((ib - ia) * (d->inches == 5 ? 32 : 16)))
	* z80_state.clockMHz;

      state.status = TRSDISK_BUSY;
      state.last_readadr = i;
      state.bytecount = 6;
      state.crc = calc_crc1((state.density
			     ? 0xcdb4 /* CRC of a1 a1 a1 */
			     : 0xffff),
			    d->u.dmk.buf[idamp]);
      d->u.dmk.curbyte = idamp + dmk_incr(d);
      trs_schedule_event(trs_disk_firstdrq, 0, ts);
      if (trs_disk_debug_flags & DISKDEBUG_READADR) {
	debug("readadr phytrack %d angle %f i %d ts %d\n",
	      d->phytrack, a, i, ts);
      }
    }
    break;

  case TRSDISK_READTRK:
    if (trs_disk_debug_flags & DISKDEBUG_FDCCMD) {
      debug("readtrk 0x%02x drv %d ptk %d tk %d %sden\n",
	    cmd, state.curdrive, d->phytrack, state.track,
	    state.density ? "d" : "s");
    }
    state.last_readadr = -1;
    if (d->file == NULL) {
      /* Data sheet says we wait forever for an index pulse, ugh */
      state.status = TRSDISK_BUSY;
      state.bytecount = 0;
      break;
    }
    if (d->emutype == REAL) {
      real_readtrk();
      break;
    }
    if (d->emutype != DMK) {
      trs_disk_unimpl(cmd, "read track");
      break;
    }
    dmk_get_track(d);
    d->u.dmk.curbyte = DMK_TKHDR_SIZE;
    if (disk[state.curdrive].inches == 5) {
      state.bytecount = TRKSIZE_DD;  /* decrement by 2's if SD */
    } else {
      state.bytecount = TRKSIZE_8DD; /* decrement by 2's if SD */
    }
    state.status = TRSDISK_BUSY|TRSDISK_DRQ;
    trs_disk_drq_interrupt(1);
    trs_schedule_event(trs_disk_lostdata, state.currcommand,
		       500000 * z80_state.clockMHz);
    break;

  case TRSDISK_WRITETRK:
    state.last_readadr = -1;
    /* Really a write track? */
    if (trs_model == 1 && (cmd == TRSDISK_P1771 || cmd == TRSDISK_P1791)) {
      /* No; emulate Percom Doubler */
      state.currcommand = TRSDISK_FORCEINT;
      if (trs_disk_doubler & TRSDISK_PERCOM) {
	trs_disk_set_controller(cmd);
	/* The Doubler's 1791 is hardwired to double density */
	state.density = (state.controller == TRSDISK_P1791);
      }
    } else {
      if (trs_disk_debug_flags & DISKDEBUG_FDCCMD) {
	debug("writetrk 0x%02x drv %d ptk %d tk %d %sden\n",
	      cmd, state.curdrive, d->phytrack, state.track,
	      state.density ? "d" : "s");
      }
      /* Yes; a real write track */
      if (d->emutype != REAL && d->writeprot) {
	state.status = TRSDISK_WRITEPRT;
	break;
      }
      state.status = 0;
      if (d->file == NULL) {
	/* Data sheet says we wait forever for an index pulse, ugh */
	state.status = TRSDISK_BUSY;
	state.bytecount = 0;
	break;
      }
      if (d->emutype == JV3) {
	/* Erase track if already formatted */
	int i;
	for (i=0; i<=d->u.jv3.last_used_id; i++) {
	  if (d->u.jv3.id[i].track == d->phytrack &&
	      ((d->u.jv3.id[i].flags & JV3_SIDE) != 0) == state.curside) {
	    jv3_free_sector(d, i);
	  }
	}
      } else if (d->emutype == REAL) {
	d->u.real.size_code = -1; /* watch for first, then check others match*/
	d->u.real.fmt_nbytes = 0; /* size of PC formatting command buffer */
      } else if (d->emutype == DMK) {
	if (state.density && d->u.dmk.sden) {
	  error("DMK disk created as single density only");
	  state.status |= TRSDISK_WRITEFLT;
	}
	if (state.curside && d->u.dmk.nsides == 1) {
	  error("DMK disk created as single sided only");
	  state.status |= TRSDISK_WRITEFLT;
	}
	d->u.dmk.curtrack = d->phytrack;
	d->u.dmk.curside = state.curside;
	memset(d->u.dmk.buf, 0, sizeof(d->u.dmk.buf));
	d->u.dmk.curbyte = DMK_TKHDR_SIZE;
	d->u.dmk.nextidam = 0;
      }
      state.status |= TRSDISK_BUSY|TRSDISK_DRQ;
      trs_disk_drq_interrupt(1);
      trs_schedule_event(trs_disk_lostdata, state.currcommand,
			 500000 * z80_state.clockMHz);
      state.format = FMT_GAP0;
      state.format_gapcnt = 0;
      if (disk[state.curdrive].inches == 5) {
	state.bytecount = TRKSIZE_DD;  /* decrement by 2's if SD */
      } else {
	state.bytecount = TRKSIZE_8DD; /* decrement by 2's if SD */
      }
    }
    break;

  case TRSDISK_FORCEINT:
    if (trs_disk_debug_flags & DISKDEBUG_FDCCMD) {
      debug("forceint 0x%02x\n", cmd);
    }
    /* Stop whatever is going on and forget it */
    trs_cancel_event();
    state.status = 0;
    type1_status();
    if ((cmd & 0x07) != 0) {
      /* Conditional interrupt features not implemented. */
      trs_disk_unimpl(cmd, "force interrupt with condition");
    } else if ((cmd & 0x08) != 0) {
      /* Immediate interrupt */
      trs_disk_intrq_interrupt(1);
    } else {
      trs_disk_intrq_interrupt(0);
    }
    break;
  }
}

/* Interface to real floppy drive */
int
real_rate(DiskState *d)
{
  if (d->inches == 5) {
    if (d->u.real.rps == 5) {
      return 2;
    } else if (d->u.real.rps == 6) {
      return 1;
    }
  } else if (d->inches == 8) {
    return 0;
  }
  trs_disk_unimpl(state.currcommand, "real_rate internal error");
  return 1;
}

void
real_error(DiskState *d, unsigned int flags, char *msg)
{
  time_t now = time(NULL);
  if (now > d->u.real.empty_timeout) {
    d->u.real.empty_timeout = time(NULL) + EMPTY_TIMEOUT;
    d->u.real.empty = 1;
  }
  if (trs_disk_debug_flags & DISKDEBUG_REALERR) {
    debug("error on real_%s\n", msg);
  }
}

void
real_ok(DiskState *d)
{
  d->u.real.empty_timeout = time(NULL) + EMPTY_TIMEOUT;
  d->u.real.empty = 0;
}

int
real_check_empty(DiskState *d)
{
#if __linux
  int reset_now = 0;
  struct floppy_raw_cmd raw_cmd;
  int res, i = 0;
  sigset_t set, oldset;

  if (time(NULL) <= d->u.real.empty_timeout) return d->u.real.empty;
  
  if (d->file == NULL) {
    d->u.real.empty = 1;
    return 1;
  }

  ioctl(fileno(d->file), FDRESET, &reset_now);

  /* Do a read id command.  Assume a disk is in the drive iff
     we get a nonnegative status back from the ioctl. */
  memset(&raw_cmd, 0, sizeof(raw_cmd));
  raw_cmd.rate = real_rate(d);
  raw_cmd.flags = FD_RAW_INTR;
  raw_cmd.cmd[i++] = state.density ? 0x4a : 0x0a; /* read ID */
  raw_cmd.cmd[i++] = state.curside ? 4 : 0;
  raw_cmd.cmd_count = i;
  raw_cmd.data = NULL;
  raw_cmd.length = 0;
  sigemptyset(&set);
  sigaddset(&set, SIGALRM);
  sigaddset(&set, SIGIO);
  sigprocmask(SIG_BLOCK, &set, &oldset);
  trs_paused = 1;
  res = ioctl(fileno(d->file), FDRAWCMD, &raw_cmd);
  sigprocmask(SIG_SETMASK, &oldset, NULL);
  if (res < 0) {
    real_error(d, raw_cmd.flags, "check_empty");
  } else {
    real_ok(d);
  }
#else
  trs_disk_unimpl(state.currcommand, "check for empty on real floppy");
#endif
  return d->u.real.empty;
}

void
real_verify()
{
  /* Verify that head is on the expected track */
  /*!! ignore for now*/
}

void
real_restore(int curdrive)
{
#if __linux
  DiskState *d = &disk[curdrive];
  struct floppy_raw_cmd raw_cmd;
  int res, i = 0;
  sigset_t set, oldset;

  raw_cmd.flags = FD_RAW_INTR;
  raw_cmd.cmd[i++] = FD_RECALIBRATE;
  raw_cmd.cmd[i++] = 0;
  raw_cmd.cmd_count = i;
  sigemptyset(&set);
  sigaddset(&set, SIGALRM);
  sigaddset(&set, SIGIO);
  sigprocmask(SIG_BLOCK, &set, &oldset);
  trs_paused = 1;
  res = ioctl(fileno(d->file), FDRAWCMD, &raw_cmd);
  sigprocmask(SIG_SETMASK, &oldset, NULL);
  if (res < 0) {
    real_error(d, raw_cmd.flags, "restore");
    state.status |= TRSDISK_SEEKERR;
    return;
  }
#else
  trs_disk_unimpl(state.currcommand, "restore real floppy");
#endif
}

void
real_seek()
{
#if __linux
  DiskState *d = &disk[state.curdrive];
  struct floppy_raw_cmd raw_cmd;
  int res, i = 0;
  sigset_t set, oldset;

  /* Always use a recal if going to track 0.  This should help us
     recover from confusion about what track the disk is really on.
     I'm still not sure why the confusion sometimes arises. */
  if (d->phytrack == 0) {
    real_restore(state.curdrive);
    return;
  }

  state.last_readadr = -1;
  memset(&raw_cmd, 0, sizeof(raw_cmd));
  raw_cmd.length = 256;
  raw_cmd.data = NULL;
  raw_cmd.rate = real_rate(d);
  raw_cmd.flags = FD_RAW_INTR;
  raw_cmd.cmd[i++] = FD_SEEK;
  raw_cmd.cmd[i++] = 0;
  raw_cmd.cmd[i++] = d->phytrack * d->real_step;
  raw_cmd.cmd_count = i;
  sigemptyset(&set);
  sigaddset(&set, SIGALRM);
  sigaddset(&set, SIGIO);
  sigprocmask(SIG_BLOCK, &set, &oldset);
  trs_paused = 1;
  res = ioctl(fileno(d->file), FDRAWCMD, &raw_cmd);
  sigprocmask(SIG_SETMASK, &oldset, NULL);
  if (res < 0) {
    real_error(d, raw_cmd.flags, "seek");
    state.status |= TRSDISK_SEEKERR;
    return;
  }
#else
  trs_disk_unimpl(state.currcommand, "seek real floppy");
#endif
}

void
real_read()
{
#if __linux
  DiskState *d = &disk[state.curdrive];
  struct floppy_raw_cmd raw_cmd;
  int res, i, retry, new_status;
  sigset_t set, oldset;

  /* Try once at each supported sector size */
  retry = 0;
  for (;;) {
    state.status = 0;
    new_status = 0;
    memset(&raw_cmd, 0, sizeof(raw_cmd));
    raw_cmd.rate = real_rate(d);
    raw_cmd.flags = FD_RAW_READ | FD_RAW_INTR;
    i = 0;
    raw_cmd.cmd[i++] = state.density ? 0x46 : 0x06;
    raw_cmd.cmd[i++] = state.curside ? 4 : 0;
    raw_cmd.cmd[i++] = state.track;
    raw_cmd.cmd[i++] = state.curside;
    raw_cmd.cmd[i++] = state.sector;
    raw_cmd.cmd[i++] = d->u.real.size_code;
    raw_cmd.cmd[i++] = 255;
    raw_cmd.cmd[i++] = 0x0a;
    raw_cmd.cmd[i++] = 0xff; /* unused */
    raw_cmd.cmd_count = i;
    raw_cmd.data = (void*) d->u.real.buf;
    raw_cmd.length = 128 << d->u.real.size_code;
    sigemptyset(&set);
    sigaddset(&set, SIGALRM);
    sigaddset(&set, SIGIO);
    sigprocmask(SIG_BLOCK, &set, &oldset);
    trs_paused = 1;
    res = ioctl(fileno(d->file), FDRAWCMD, &raw_cmd);
    sigprocmask(SIG_SETMASK, &oldset, NULL);
    if (res < 0) {
      real_error(d, raw_cmd.flags, "read");
      new_status |= TRSDISK_NOTFOUND;
    } else {
      real_ok(d); /* premature? */
      if (raw_cmd.reply[1] & 0x04) {
	/* Could have been due to wrong sector size, so we'll retry
	   internally in each other size before returning an error. */
	if (trs_disk_debug_flags & DISKDEBUG_REALSIZE) {
	  debug("real_read not fnd: side %d tk %d sec %d size 0%d phytk %d\n",
		state.curside, state.track, state.sector, d->u.real.size_code,
		d->phytrack*d->real_step);
	}
#if SIZERETRY
	d->u.real.size_code = (d->u.real.size_code + 1) % 4;
	if (++retry < 4) {
	  continue; /* retry */
	}
#endif
	new_status |= TRSDISK_NOTFOUND;
      }
      if (raw_cmd.reply[1] & 0x81) new_status |= TRSDISK_NOTFOUND;
      if (raw_cmd.reply[1] & 0x20) {
	new_status |= TRSDISK_CRCERR;
	if (!(raw_cmd.reply[2] & 0x20)) new_status |= TRSDISK_NOTFOUND;
      }
      if (raw_cmd.reply[1] & 0x10) new_status |= TRSDISK_LOSTDATA;
      if (raw_cmd.reply[2] & 0x40) {
	if (state.controller == TRSDISK_P1771) {
	  if (trs_disk_truedam) {
	    new_status |= TRSDISK_1771_F8;
	  } else {
	    new_status |= TRSDISK_1771_FA;
	  }
	} else {
	  new_status |= TRSDISK_1791_F8;
	}
      }
      if (raw_cmd.reply[2] & 0x20) new_status |= TRSDISK_CRCERR;
      if (raw_cmd.reply[2] & 0x13) new_status |= TRSDISK_NOTFOUND;
      if ((new_status & TRSDISK_NOTFOUND) == 0) {
	/* Start read */
	state.status = TRSDISK_BUSY;
	trs_schedule_event(trs_disk_firstdrq, new_status, 64);
	state.bytecount = size_code_to_size(d->u.real.size_code);
	return;
      }
    }
    break; /* exit retry loop */
  }
  /* Sector not found; fail */
  state.status = TRSDISK_BUSY;
  trs_schedule_event(trs_disk_done, new_status, 512);
#else
  trs_disk_unimpl(state.currcommand, "read real floppy");
#endif
}

void
real_write()
{
#if __linux
  DiskState *d = &disk[state.curdrive];
  struct floppy_raw_cmd raw_cmd;
  int res, i = 0;
  sigset_t set, oldset;

  state.status = 0;
  memset(&raw_cmd, 0, sizeof(raw_cmd));
  raw_cmd.rate = real_rate(d);
  raw_cmd.flags = FD_RAW_WRITE | FD_RAW_INTR;
  if (trs_disk_truedam && !state.density) {
    switch (state.currcommand & 0x03) {
    case 0:
    case 3:
      break;
    case 1:
      error("writing FA DAM on real floppy");
      break;
    case 2:
      error("writing F9 DAM on real floppy");
      break;
    }
  }
  /* Use F8 DAM for F8, F9, or FA */
  raw_cmd.cmd[i++] = ((state.currcommand & 
		       (state.controller == TRSDISK_P1771 ? 0x03 : 0x01))
		      ? 0x09 : 0x05) | (state.density ? 0x40 : 0x00);
  raw_cmd.cmd[i++] = state.curside ? 4 : 0;
  raw_cmd.cmd[i++] = state.track;
  raw_cmd.cmd[i++] = state.curside;
  raw_cmd.cmd[i++] = state.sector;
  raw_cmd.cmd[i++] = d->u.real.size_code;
  raw_cmd.cmd[i++] = 255;
  raw_cmd.cmd[i++] = 0x0a;
  raw_cmd.cmd[i++] = 0xff; /* 256 */
  raw_cmd.cmd_count = i;
  raw_cmd.data = (void*) d->u.real.buf;
  raw_cmd.length = 128 << d->u.real.size_code;
  sigemptyset(&set);
  sigaddset(&set, SIGALRM);
  sigaddset(&set, SIGIO);
  sigprocmask(SIG_BLOCK, &set, &oldset);
  trs_paused = 1;
  res = ioctl(fileno(d->file), FDRAWCMD, &raw_cmd);
  sigprocmask(SIG_SETMASK, &oldset, NULL);
  if (res < 0) {
    real_error(d, raw_cmd.flags, "write");
    state.status |= TRSDISK_NOTFOUND;
  } else {
    real_ok(d); /* premature? */
    if (raw_cmd.reply[1] & 0x04) {
      state.status |= TRSDISK_NOTFOUND;
      /* Could have been due to wrong sector size.  Presumably
         the Z-80 software will do some retries, so we'll cause
         it to try the next sector size next time. */
      if (trs_disk_debug_flags & DISKDEBUG_REALSIZE) {
	debug("real_write not found: side %d tk %d sec %d size 0%d phytk %d\n",
	      state.curside, state.track, state.sector, d->u.real.size_code,
	      d->phytrack*d->real_step);
      }
#if SIZERETRY
      d->u.real.size_code = (d->u.real.size_code + 1) % 4;
#endif
    }
    if (raw_cmd.reply[1] & 0x81) state.status |= TRSDISK_NOTFOUND;
    if (raw_cmd.reply[1] & 0x20) {
      state.status |= TRSDISK_CRCERR;
      if (!(raw_cmd.reply[2] & 0x20)) state.status |= TRSDISK_NOTFOUND;
    }
    if (raw_cmd.reply[1] & 0x10) state.status |= TRSDISK_LOSTDATA;
    if (raw_cmd.reply[1] & 0x02) {
      state.status |= TRSDISK_WRITEPRT;
      d->writeprot = 1;
    } else {
      d->writeprot = 0;
    }
    if (raw_cmd.reply[2] & 0x20) state.status |= TRSDISK_CRCERR;
    if (raw_cmd.reply[2] & 0x13) state.status |= TRSDISK_NOTFOUND;
  }
  state.bytecount = 0;
  trs_disk_drq_interrupt(0);
  state.status |= TRSDISK_BUSY;
  if (trs_event_scheduled() == trs_disk_lostdata) {
    trs_cancel_event();
  }
  trs_schedule_event(trs_disk_done, 0, 512);
#else
  trs_disk_unimpl(state.currcommand, "write real floppy");
#endif
}

void
real_readadr()
{
#if __linux
  DiskState *d = &disk[state.curdrive];
  struct floppy_raw_cmd raw_cmd;
  int res, i, new_status;
  sigset_t set, oldset;

  state.status = 0;
  new_status = 0;
  memset(&raw_cmd, 0, sizeof(raw_cmd));
  raw_cmd.rate = real_rate(d);
  raw_cmd.flags = FD_RAW_INTR;
  i = 0;
  raw_cmd.cmd[i++] = state.density ? 0x4a : 0x0a;
  raw_cmd.cmd[i++] = state.curside ? 4 : 0;
  raw_cmd.cmd_count = i;
  raw_cmd.data = NULL;
  raw_cmd.length = 0;
  sigemptyset(&set);
  sigaddset(&set, SIGALRM);
  sigaddset(&set, SIGIO);
  sigprocmask(SIG_BLOCK, &set, &oldset);
  trs_paused = 1;
  res = ioctl(fileno(d->file), FDRAWCMD, &raw_cmd);
  sigprocmask(SIG_SETMASK, &oldset, NULL);
  state.bytecount = 0;
  if (res < 0) {
    real_error(d, raw_cmd.flags, "readadr");
    new_status |= TRSDISK_NOTFOUND;
  } else {
    real_ok(d); /* premature? */
    if (raw_cmd.reply[1] & 0x85) new_status |= TRSDISK_NOTFOUND;
    if (raw_cmd.reply[1] & 0x20) new_status |= TRSDISK_CRCERR;
    if (raw_cmd.reply[1] & 0x10) new_status |= TRSDISK_LOSTDATA;
    if (raw_cmd.reply[2] & 0x40) {
      if (state.controller == TRSDISK_P1771) {
        new_status |= TRSDISK_1771_FA;
      } else {
        new_status |= TRSDISK_1791_F8;
      }
    }
    if (raw_cmd.reply[2] & 0x20) new_status |= TRSDISK_CRCERR;
    if (raw_cmd.reply[2] & 0x13) new_status |= TRSDISK_NOTFOUND;
    if ((new_status & TRSDISK_NOTFOUND) == 0) {
      state.status = TRSDISK_BUSY;
      trs_schedule_event(trs_disk_firstdrq, new_status, 64);
      memcpy(d->u.real.buf, &raw_cmd.reply[3], 4);
      d->u.real.buf[4] = d->u.real.buf[5] = 0; /* CRC not emulated */
      state.bytecount = 6;
      d->u.real.size_code = d->u.real.buf[3]; /* update hint */
      return;
    }
  }
  state.last_readadr = -1;
  /* Sector not found; fail */
  state.status = TRSDISK_BUSY;
  trs_schedule_event(trs_disk_done, new_status, 200000*z80_state.clockMHz);
#else
  trs_disk_unimpl(state.currcommand, "read address on real floppy");
#endif
}

void
real_readtrk()
{
  trs_disk_unimpl(state.currcommand, "read track on real floppy");
}

void
real_writetrk()
{
#if __linux
  DiskState *d = &disk[state.curdrive];
  struct floppy_raw_cmd raw_cmd;
  int res, i, gap3;
  sigset_t set, oldset;
  state.status = 0;

  /* Compute a usable gap3 */
  /* Constants based on IBM format as explained in "The floppy user guide"
     by Michael Haardt, Alain Knaff, and David C. Niemi */
  /* The formulas and constants are not factored out, in case some of
     those that are the same now need to change when I learn more. */
  if (state.density) {
    /* MFM recording */
    if (d->inches == 5) {
      /* 5" DD = 250 kHz MFM */
      gap3 = (TRKSIZE_DD - 161 - /*slop*/16)/(d->u.real.fmt_nbytes / 4)
	- 62 - (128 << d->u.real.size_code) - /*slop*/2;
    } else {
      /* 8" DD = 5" HD = 500 kHz MFM */
      gap3 = (TRKSIZE_8DD - 161 - /*slop*/16)/(d->u.real.fmt_nbytes / 4)
	- 62 - (128 << d->u.real.size_code) - /*slop*/2;
    }
  } else {
    /* FM recording */
    if (d->inches == 5) {
      /* 5" SD = 250 kHz FM (125 kbps) */
      gap3 = (TRKSIZE_SD - 99 - /*slop*/16)/(d->u.real.fmt_nbytes / 4)
	- 33 - (128 << d->u.real.size_code) - /*slop*/2;
    } else {
      /* 8" SD = 5" HD operated in FM = 500 kHz FM (250 kbps) */
      gap3 = (TRKSIZE_8SD - 99 - /*slop*/16)/(d->u.real.fmt_nbytes / 4)
	- 33 - (128 << d->u.real.size_code) - /*slop*/2;
    }
  }
  if (gap3 < 1) {
    error("gap3 too small");
    gap3 = 1;
  } else if (gap3 > 0xff) {
    gap3 = 0xff;
  }

  /* Do the actual write track */
  memset(&raw_cmd, 0, sizeof(raw_cmd));
  raw_cmd.rate = real_rate(d);
  raw_cmd.flags = FD_RAW_WRITE | FD_RAW_INTR;
  i = 0;
  raw_cmd.cmd[i++] = 0x0d | (state.density ? 0x40 : 0x00);
  raw_cmd.cmd[i++] = state.curside ? 4 : 0;
  raw_cmd.cmd[i++] = d->u.real.size_code;
  raw_cmd.cmd[i++] = d->u.real.fmt_nbytes / 4;
  raw_cmd.cmd[i++] = gap3;
  raw_cmd.cmd[i++] = d->u.real.fmt_fill;
  raw_cmd.cmd_count = i;
  raw_cmd.data = (void*) d->u.real.buf;
  raw_cmd.length = d->u.real.fmt_nbytes;
  
  if (trs_disk_debug_flags & DISKDEBUG_GAPS) {
    debug("real_writetrk size 0%d secs %d gap3 %d fill 0x%02x hex data ",
	  d->u.real.size_code, d->u.real.fmt_nbytes/4, gap3,
	  d->u.real.fmt_fill);
    for (i=0; i<d->u.real.fmt_nbytes; i+=4) {
      debug("%02x%02x%02x%02x ", d->u.real.buf[i], d->u.real.buf[i+1],
	    d->u.real.buf[i+2], d->u.real.buf[i+3]);
    }
    debug("\n");
  }

  sigemptyset(&set);
  sigaddset(&set, SIGALRM);
  sigaddset(&set, SIGIO);
  sigprocmask(SIG_BLOCK, &set, &oldset);
  trs_paused = 1;
  res = ioctl(fileno(d->file), FDRAWCMD, &raw_cmd);
  sigprocmask(SIG_SETMASK, &oldset, NULL);
  if (res < 0) {
    real_error(d, raw_cmd.flags, "writetrk");
    state.status |= TRSDISK_WRITEFLT;
  } else {
    real_ok(d); /* premature? */
    if (raw_cmd.reply[1] & 0x85) state.status |= TRSDISK_NOTFOUND;
    if (raw_cmd.reply[1] & 0x20) state.status |= TRSDISK_CRCERR;
    if (raw_cmd.reply[1] & 0x10) state.status |= TRSDISK_LOSTDATA;
    if (raw_cmd.reply[1] & 0x02) {
      state.status |= TRSDISK_WRITEPRT;
      d->writeprot = 1;
    } else {
      d->writeprot = 0;
    }
    if (raw_cmd.reply[2] & 0x20) state.status |= TRSDISK_CRCERR;
    if (raw_cmd.reply[2] & 0x13) state.status |= TRSDISK_NOTFOUND;
  }
  state.bytecount = 0;
  trs_disk_drq_interrupt(0);
  state.status |= TRSDISK_BUSY;
  if (trs_event_scheduled() == trs_disk_lostdata) {
    trs_cancel_event();
  }
  trs_schedule_event(trs_disk_done, 0, 512);
#else
  trs_disk_unimpl(state.currcommand, "write track on real floppy");
#endif
}