File: morse.c

package info (click to toggle)
morse 2.1-4
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 412 kB
  • ctags: 428
  • sloc: ansic: 3,750; xml: 376; makefile: 116
file content (1946 lines) | stat: -rw-r--r-- 49,469 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
/*
 * Copyright (c) 1988 Regents of the University of California.
 * Copyright (c) 1992 Joe Dellinger, University of Hawaii at Manoa
 * Copyright (c) 2005 Eric S. Raymond.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
/*
 * A morse code practice utility. (Contains those characters that can appear
 * on the FCC ham license exam.)
 *
 * Running "morse" without arguments or input gives self-doc.
 *
 * It doesn't keep PERFECT time, but it seems reasonably close
 * for reasonable word speeds on my slow SUN IPC!
 *
 * This program has a long history, see the HISTORY file for details.
 */

/*
 * Useful for seeing what the interleaved reading and writing loops are
 * really up to.
 *
 * #define DEBUG
 *
 * If you want to be overwhelmed with information about the probabilities
 * of each letter being chosen.
 *
 * #define DEBUGG
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <ctype.h>
#include <signal.h>
#include "beep.h"

#define FREQUENCY	800.0
#define FREQUENCY2	602.0
#define VOLUME		0.5
#define ERROR_VOLUME		0.5
#define WORDS_PER_MINUTE	20.0
#define MAX_BEHINDNESS	0
#define ERROR_FREQUENCY	2000.0

static int      whichfrequ = 0;
static float    frequency1 = FREQUENCY;
static float    frequency2 = FREQUENCY2;
static float    frequency;
static float    volume = VOLUME;
static float    dot_time;
static float    dash_time;
static float    intra_char_time;
static float    inter_char_time;
static float    inter_word_time;
static float    catchup_time;
static int      showletters = 0;
static int      showmorse = 0;
static int      wordsbefore = 0;
static int      wordsafter = 0;
static int      fancyending = 1;
static int      noticebad = 0;
static int      testing = 0;
static int      showtesting = 0;
static int      keepquiet = 0;
static int      dynamicspeed = 0;
static int      charbychar = 0;
static int	international = 0;
static int	allprosigns = 0;
static int	allpunctuation = 1;
static int      tryagaincount = 1;
static float    words_per_minute = WORDS_PER_MINUTE;
static float	error_frequency = ERROR_FREQUENCY;
static float	error_volume = ERROR_VOLUME;
static float    fwords_per_minute;
static int      randomletters = 0;
#define LETMESEE 2
static int      typeaway = 0;

static int      totalhitcount = 0;
static int      totalmisscount = 0;
static int      helpmeflag = 0;

#define MAXWORDLEN	20
#define TESTBUFSZ ((MAXWORDLEN+1)*10)
static int      wordlen = MAXWORDLEN;
static int      wordcount = -1;
static time_t   starttime;
static int      timeout = -1;
static int      testpointer = -1;
static int      testlength = 0;
static int      behindness = 0;
static int      max_behindness = MAX_BEHINDNESS;
static char     teststring[TESTBUFSZ];
static int      yourpointer = -1;
static int      yourlength = 0;
static char     yourstring[TESTBUFSZ];
static int      linepos = 0;

/*
 * How many times can a given character not be asked before
 * kicking up the probability of asking that one by one randomfactor unit.
 */
#define RIPECOUNT	64

#define TWOFIFTYSIX 256
static char    *(code[TWOFIFTYSIX]);
static int      errorlog[TWOFIFTYSIX];
static int      randomfactor[TWOFIFTYSIX];
static int      randomripe[TWOFIFTYSIX];
static int      testterminal (void);
static int      randomletter (void);

/*
 * Pointers to termcap/terminfo "smso/so" (enter_standout_mode) and "rmso/se"
 * (exit_standout_mode) terminal string capabilities (initialized respectively
 * with ANSI sequences "\E[7m" to turn the inverse video mode on and "\E[0m"
 * to turn all video attributes off).
 */
static const char           *enter_standout_mode = "\033[7m";
static const char           *exit_standout_mode = "\033[0m";

/*
 * Value of (Wrong - Right), which, if exceeded, will cause the program
 * to start prompting you. Above MAX_ERROR_THRESHOLD it will never prompt.
 * Don't let the user bank too much credit for past correct answers;
 * limit it by min(ERROR_FLOOR, error_threshold).
 */
#define MAX_ERROR_THRESHOLD		1000
#define ERROR_FLOOR			-3
static int      error_threshold = MAX_ERROR_THRESHOLD;
static int      error_floor = ERROR_FLOOR;

/*
 * How many characters behind before it decides you're having
 * trouble keeping up.
 */
#define BEHIND		1
#define WAYBEHIND	3
#define TOOFARBEHIND	6
/*
 * If SLOWPOKE or more wpm ticks go by, then it decides you are having lots
 * of trouble remembering this character, and need to be asked it more
 * often.
 */
#define SLOWPOKE	10
/* You aren't slow -- you left and came back! */
#define SLOWPOKEMAX	(50 * SLOWPOKE)
/*
 * If FASTPOKE or less wpm ticks go by, then it decides you are good at this
 * character, and need to be asked it less often.
 */
#define FASTPOKE	4

/*
 * These control how quickly the dynamicspeed option acts when you are
 * fast or slow. Easier to slow down than speed up!
 */
#define ERRORSLOWER	1.04
#define ALOTSLOWER	1.15
#define ALITTLESLOWER	1.02
#define ALITTLEFASTER	1.02

/*
 * How many inter_char_time's to give you to answer after the end of
 * a word before considering that you are not keeping up.
 * Maximum of 2.3, minimum of 0.
 * The bigger the value, the easier it is to kick in the "automatic
 * speedup" when using the "-d" option. The maximum means you have (almost)
 * right up to the beginning of the next word to answer and still have it
 * count as keeping up.
 */
#define SPORTING_RATIO 1.5

/*
 * The bigger, the more evenly things start out.
 * (Must be at least 2)
 */
#define RANDOMBASELEVEL	7
/*
 * RANDOMINCWORSE scales how badly you are punished for being wrong
 * or taking too long. RANDOMINCBETTER scales how you are rewarded for
 * answering quickly or being right.
 */
#define RANDOMINCWORSE	6
#define RANDOMINCBETTER	7
#define RANDOMMAX	(30 * RANDOMBASELEVEL)
/*
 * The average length of a random word (chosen using exponential distribution).
 * After implementing this I'm not so sure an exponential distribution
 * actually models the distribution of real word lengths in English very well.
 * It's not too bad, though, and the words themselves are all garbage anyway,
 * so what the heck.
 */
#define RANDWORDLEN	3.5

/* Put in a newline instead of a space when past this column */
#define LINELENGTH	78

/* An EOF without the EOF (%) sound */
#define SILENTEOF -2
/* Toggle tone frequency on control-G within input file */
#define FREQU_TOGGLE ((int)'\007')

/*
 * If you want the morse code to come out synchronized with the printing
 * of dots and dashes with the -m option, then define this. The problem
 * is that then the morse code sounds ratty on slower CPU's.
 * John Shalamskas (KJ9U) suggested turning the precise morse-code printing
 * synching off because he didn't like the resulting code quality!
 */
#undef FLUSHCODE

static void            new_words_per_minute (void);
static void            dowords (int c);
static void            morse (int c);
static void            show (char *s);
static void            testaddchar (char c);
static void            youraddchar (char c);
static void            pollyou (void);
static void            tone (float hertz, float duration, float amplitude);
static void            toneflush (void);
static void            openterminal (void);
static int             readterminal (char **string);
static void            closeterminal (void);
static void            report (void);

static void            die (), suspend ();
static void            cleanup ();

int
main (int argc, char **argv)
{
extern char    *optarg;
extern int      optind;
int             ch;
char           *p;
int             ii, jj;
int             firsttime, notdoneyet;
int             yourchar;
float           randexp, randnum;
extern time_t   time ();
struct sigaction handler;

    if (argc == 1 && isatty (fileno (stdin)))
    {
/*
 * SELF DOC
 */
	printf ("Usage:\n");
	printf ("morse [options] < text_file\n");
	printf ("morse [options] words words words\n");
	printf ("morse [options] -r\n");
	printf ("morse [options] -i\n");
	printf ("Options:\n");
	printf ("-i    Play what you type.\n");
	printf ("-I    Like -i but don't turn off keyboard echoing.\n");
	printf ("-r    Generate random text. Starts out slanted towards easy\n");
	printf ("      letters, then slants towards ones you get wrong.\n");
	printf ("-n NUM (default %d means random length)\n", MAXWORDLEN);
	printf ("      Make words (groups) NUM characters long.\n");
	printf ("      Valid values are between %d and %d.\n", 1, MAXWORDLEN);
	printf ("-R NUM (default 0 means unlimited)\n");
	printf ("      Set the total time (in minutes) to generate text.\n");
	printf ("-N NUM (default 0 means unlimited)\n");
	printf ("      Set the total number of words (groups) to generate.\n");
	printf ("-C \'STRING\' (default all available characters)\n");
	printf ("      Select characters to send from this STRING only.\n");
	printf ("-w words_per_minute (default %g)\n", WORDS_PER_MINUTE);
	printf ("      actual overall sending speed\n");
	printf ("-F Farnsworth_character_words_per_minute\n");
	printf ("      If specified, characters are sent at this speed, with extra\n");
	printf ("      spaces inserted to bring the overall speed down to the -w\n");
	printf ("      value. Ignored if not higher than -w.\n");
	printf ("-f frequency_in_hertz (default %g)\n", FREQUENCY);
	printf ("-v volume (zero to one, rather nonlinear, default %g)\n",
		      VOLUME);
	printf ("-g alternate_frequency (default %g)\n", FREQUENCY2);
	printf ("      (toggles via control-G in input FILE at a word break)\n");
	printf ("-e    leave off the <SK> sound at the end\n");
	printf ("-c    complain about illegal characters instead of just ignoring them\n");
	printf ("-b    print each word before doing it\n");
	printf ("-a    print each word after doing it\n");
	printf ("-l    print each letter just before doing it\n");
	printf ("-m    print morse dots and dashes as they sound\n");
#ifdef FLUSHCODE
	printf ("      (this printing-intensive option slows the wpm down!)\n");
#endif
	printf ("-t    Type along with the morse, but don't see what\n");
	printf ("      you're typing (unless you make a mistake).\n");
	printf ("      You are allowed to get ahead as much as you want.\n");
	printf ("      If you get too far behind it will stop and resync with you.\n");
	printf ("      You can force it to resync at the next word end by hitting control-H.\n");
	printf ("      Hit ESC to see how you are doing, control-D to end.\n");
	printf ("      (The rightmost space in the printout marks where the average is.\n");
	printf ("      Farther left spaces separate off blocks of letters that are\n");
	printf ("      about twice as probable as the average to occur, three times, etc.)\n");
	printf ("-T    Like -t but see your characters (after they are played).\n");
	printf ("-s    Stop after each character and make sure you get it right. (implies -t)\n");
	printf ("-q    Quietly resyncs with your input (after you make a mistake).\n");
	printf ("-p NUM (default 0)\n");
	printf ("      Make you get it right NUM times, for penance. (implies -s)\n");
	printf ("      (Yes, NUM = 0 means you can sin all you want.)\n");
	printf ("-E NUM (default %d)\n", MAX_ERROR_THRESHOLD);
	printf ("      If your count of wrong answers minus right answers for a given character\n");
	printf ("      exceeds this, the program will start prompting you.\n");
	printf ("      If %d or above, it will never prompt. (implies -t)\n", MAX_ERROR_THRESHOLD);
	printf ("-M NUM (default %d)\n", MAX_BEHINDNESS);
	printf ("      If you get more than this number of characters behind, pause until you\n");
	printf ("      do your next letter. (1 behind is normal, 0 behind means never pause.)\n");
	printf ("      (implies -t)\n");
	printf ("-d    Dynamically speed up or slow down depending on how you are doing.\n");
	printf ("      (if also -s, then -d _only speeds up_!)\n");
	printf ("-A    Add ISO 8850-1 (Latin-1) signs to test set.\n");
	printf ("-B    Add uncommon punctuation to test set.\n");
	printf ("-S    Add uncommon prosigns to test set.\n");
	printf ("-X    Set error volume. Defaults to %g.\n", ERROR_VOLUME);
	printf ("      Error volume 0 means use console speaker.\n");
	printf ("-x    Set frequency of error tone, default 2000.0Hz\n");
	exit (0);
    }

    for (ii = 0; ii < TWOFIFTYSIX; ii++)
	code[ii] = NULL;

/* Load in the morse code code */
    code[(int) 'a'] = ".-";
    code[(int) 'b'] = "-...";
    code[(int) 'c'] = "-.-.";
    code[(int) 'd'] = "-..";
    code[(int) 'e'] = ".";
    code[(int) 'f'] = "..-.";
    code[(int) 'g'] = "--.";
    code[(int) 'h'] = "....";
    code[(int) 'i'] = "..";
    code[(int) 'j'] = ".---";
    code[(int) 'k'] = "-.-";
    code[(int) 'l'] = ".-..";
    code[(int) 'm'] = "--";
    code[(int) 'n'] = "-.";
    code[(int) 'o'] = "---";
    code[(int) 'p'] = ".--.";
    code[(int) 'q'] = "--.-";
    code[(int) 'r'] = ".-.";
    code[(int) 's'] = "...";
    code[(int) 't'] = "-";
    code[(int) 'u'] = "..-";
    code[(int) 'v'] = "...-";
    code[(int) 'w'] = ".--";
    code[(int) 'x'] = "-..-";
    code[(int) 'y'] = "-.--";
    code[(int) 'z'] = "--..";

    code[(int) '1'] = ".----";
    code[(int) '2'] = "..---";
    code[(int) '3'] = "...--";
    code[(int) '4'] = "....-";
    code[(int) '5'] = ".....";
    code[(int) '6'] = "-....";
    code[(int) '7'] = "--...";
    code[(int) '8'] = "---..";
    code[(int) '9'] = "----.";
    code[(int) '0'] = "-----";

    /* Punctuation marks */
    code[(int) '.'] = ".-.-.-";
    code[(int) ','] = "--..--";
    code[(int) '?'] = "..--..";
    code[(int) '/'] = "-..-.";
    code[(int) '-'] = "-....-";

    if (allpunctuation) {
    /* Not so commonly used punctuation marks */
    code[(int) ')'] = "-.--.-";
    code[(int) '\"'] = ".-..-.";
    code[(int) '_'] = "..--.-";
    code[(int) '\''] = ".----.";
    code[(int) ':'] = "---...";
    code[(int) ';'] = "-.-.-.";
    code[(int) '$'] = "...-..-";
    code[(int) '!'] = "-.-.--";
    }

    /* Commonly used procedure signs ("prosigns") */
    code[(int) '+'] = ".-.-.";  /* <AR> end of message */
    code[(int) '*'] = ".-...";  /* <AS> wait, stand-by */
    code[(int) '='] = "-...-";  /* <BT> (double dash) pause, break for text */
    code[(int) '('] = "-.--.";  /* <KN> over-specified station only */
    code[(int) '%'] = "...-.-"; /* <SK> end of contact, known also as <VA> */

    if (allprosigns) {
    /* Not so commonly used procedure signs ("prosigns") */
    code[(int) '^'] = ".-.-";   /* <AA> new line, the same as :a, ae */
    code[(int) '#'] = "-...-.-";/* <BK> invite receiving station to transmit */
    code[(int) '&'] = "-.-.-";  /* <KA> attention */
    code[(int) '@'] = "...-.";  /* <SN> understood */
    }

    if (international) {
    /* Not so commonly used international extensions (ISO 8859-1) */
    code[(int) ((unsigned char)'\344')] = ".-.-";   /* :a (also for ae), the same as <AA> */
    if (code[(int) '^'] != NULL) code[(int) '^'] = NULL;
    code[(int) ((unsigned char)'\340')] = ".--.-";  /* `a, oa (danish a with ring over it) */
    code[(int) ((unsigned char)'\347')] = "----";   /* ch (bar-ch) */
    code[(int) ((unsigned char)'\360')] = "..--.";  /* -d (eth, overstrike d with -) */
    code[(int) ((unsigned char)'\350')] = "..-..";  /* `e */
    code[(int) ((unsigned char)'\361')] = "--.--";  /* ~n */
    code[(int) ((unsigned char)'\366')] = "---.";   /* :o (also for oe) */
    code[(int) ((unsigned char)'\374')] = "..--";   /* :u (also for ue) */
    code[(int) ((unsigned char)'\376')] = ".--..";  /* ]p (thorn, overstrike ] with p) */
    code[(int) ((unsigned char)'\247')] = ".-.-.."; /* paragraph */
    }

    for (ii = 0; ii < TWOFIFTYSIX; ii++)
    {
	/* Everything starts equally fresh */
	randomripe[ii] = 0;
	/* Start out assuming you know how everything sounds */
	errorlog[ii] = 0;

	if (code[ii] == NULL)
	{
	    /* Ensures these will never be chosen */
	    randomfactor[ii] = 0;
	}
	else
	{
	    /* Start out favoring easy ones */
	    randomfactor[ii] = RANDOMBASELEVEL - strlen (code[ii]);
	    if (randomfactor[ii] < 1)
		randomfactor[ii] = 1;
	}
    }

    words_per_minute = WORDS_PER_MINUTE;
    fwords_per_minute = -1.;

    /* DGHJKLMOPQUVWYZhjkouyz are still available */
    while ((ch = getopt (argc, argv, "ABC:E:F:IM:N:R:STXabcdef:g:ilmn:p:qrstv:w:x:")) != EOF)
	switch ((char) ch)
	{
	case 'A':
	    international = 1;
	    break;
	case 'B':
	    allpunctuation = 1;
	    break;
	case 'C':
	    for (ii = 0; ii < strlen(optarg); ii++)
	      {
		*(optarg+ii) = tolower(*(optarg+ii));
	      }
	    for (ii = 0; ii < TWOFIFTYSIX; ii++)
	      {
		if (code[ii] != NULL)
		  {
		    if (strchr(optarg, ii) != NULL)
		      {
			randomfactor[ii] = RANDOMBASELEVEL - 1;
		      } else {
			code[ii] = NULL;
			randomfactor[ii] = 0;
		      }
		  }
	      }
	    break;
	case 'E':
	    testing = 1;
	    sscanf (optarg, "%d", &error_threshold);
	    if (error_threshold < error_floor)
		error_floor = error_threshold;
	    break;
	case 'F':
	    sscanf (optarg, "%f", &fwords_per_minute);
	    break;
	case 'I':
	    typeaway = LETMESEE;
	    break;
	case 'M':
	    testing = 1;
	    sscanf (optarg, "%d", &max_behindness);
	    if (max_behindness < 1)
		max_behindness = 0;
	    break;
	case 'N':
	    sscanf (optarg, "%d", &wordcount);
	    if (wordcount < 1) wordcount = -1;
	    break;
	case 'R':
	    sscanf (optarg, "%d", &timeout);
	    timeout *= 60;
	    if (timeout < 1) timeout = -1;
	    break;
	case 'S':
	    allprosigns = 1;
	    break;
	case 'T':
	    testing = 1;
	    showtesting = 1;
	    break;
	case 'X':
	    sscanf (optarg, "%f", &error_volume);
	    break;
	case 'a':
	    wordsafter = 1;
	    break;
	case 'b':
	    wordsbefore = 1;
	    break;
	case 'c':
	    noticebad = 1;
	    break;
	case 'd':
	    dynamicspeed = 1;
	    break;
	case 'e':
	    fancyending = 0;
	    break;
	case 'f':
	    sscanf (optarg, "%f", &frequency1);
	    break;
	case 'g':
	    sscanf (optarg, "%f", &frequency2);
	    break;
	case 'i':
	    typeaway = 1;
	    break;
	case 'l':
	    showletters = 1;
	    break;
	case 'm':
	    showmorse = 1;
	    break;
	case 'n':
	    sscanf (optarg, "%d", &wordlen);
	    if (wordlen < 1) wordlen = 1;
	    if (wordlen > MAXWORDLEN) wordlen = MAXWORDLEN;
	    break;
	case 'p':
	    charbychar = 1;
	    testing = 1;
	    sscanf (optarg, "%d", &tryagaincount);
	    break;
	case 'q':
	    keepquiet = 1;
	    break;
	case 'r':
	    randomletters = 1;
	    break;
	case 's':
	    charbychar = 1;
	    testing = 1;
	    break;
	case 't':
	    testing = 1;
	    break;
	case 'v':
	    sscanf (optarg, "%f", &volume);
	    if (volume < 0.)
		volume = 0.;
	    if (volume > 1.)
		volume = 1.;
	    break;
	case 'w':
	    sscanf (optarg, "%f", &words_per_minute);
	    break;
	case 'x':
	    sscanf (optarg, "%f", &error_frequency);
	    break;
	default:
	    fprintf (stderr, "Type \"morse\" without arguments to get self-doc!\n");
	    exit (1);
	    break;
	}
    argc -= optind;
    argv += optind;

    if (fwords_per_minute <= 0.)
	fwords_per_minute = words_per_minute;
    new_words_per_minute ();

    frequency = frequency1;

    if (BeepInit () != 0)
    {
	fprintf (stderr, "Can't access speaker.\n");
	exit (1);
    }

    time(&starttime);

    handler.sa_handler = die;
    sigemptyset(&handler.sa_mask);
    handler.sa_flags = 0;
    sigaction (SIGINT, &handler, NULL);
    sigaction (SIGTERM, &handler, NULL);
    sigaction (SIGQUIT, &handler, NULL);
    handler.sa_handler = suspend;
    sigaction (SIGTSTP, &handler, NULL);

    if (testing || typeaway)
    {
	openterminal ();
    }

/*
 * Do 0.25 seconds of silence initially to give the workstation time to
 * get settled after the stress of starting this program and opening
 * up everything.
 */
    tone (frequency, 0.25, 0);
    toneflush ();

    if (typeaway)
    {
	testing = 0;
	showtesting = 0;
	charbychar = 0;
	wordsbefore = 0;
	wordsafter = 0;
	randomletters = 0;

	notdoneyet = 1;

	while (notdoneyet)
	{
	    pollyou ();

	    for (jj = 0; jj < yourlength; jj++)
	    {
		yourchar = yourstring[(yourpointer - yourlength + 1 + jj + TESTBUFSZ) % TESTBUFSZ];

		/* Control-D: finished */
		if (yourchar == (int) '\004')
		{
		    toneflush ();
		    notdoneyet = 0;
		    break;
		}

		if (isspace (yourchar))
		{
		    if (showletters)
		    {
			toneflush ();
			printf ("%c", yourchar);
			fflush (stdout);
		    }

		    tone (frequency, inter_word_time, 0.);

		    continue;
		}

		morse (yourchar);
	    }
	    yourlength -= jj;

	    if (timeout > 0)
	      if (difftime(time(NULL),starttime) > (double)timeout)
		break;
	}
    }
    else if (randomletters)
    {
	srand48(time (NULL));
	randexp = 1. / (1. - 1. / (float) (RANDWORDLEN));
	while (1)
	{
	    if ((wordcount == 0) || timeout == 0) break;

	    dowords (randomletter ());

	    if (wordlen == MAXWORDLEN)
	      {
		/* Knock a few bits off the top so we're sure it won't overflow */
		/* Shift a few bits because the lower bits stink */
		/* Add in the time so it doesn't repeat from run to run */
		randnum = (float) (
				   (((lrand48() >> 9) + (long) (time (NULL))) >> 4)
				   & 0x00FFFFFF);
		randnum = randnum - randexp * (int) (randnum / randexp);
		if ((randnum >= 1.) && (linepos != 0)) dowords ((int) ' ');
	      }
	}
    }
    else
    {
	if (*argv)
	{
	    firsttime = 1;

	    do
	    {
		if (!firsttime)
		{
		    dowords ((int) ' ');
		}
		else
		    firsttime = 0;

		if ((wordcount == 0) || timeout == 0) break;

		for (p = *argv; *p; ++p)
		  {
		    dowords ((int) *p);
		    if ((wordcount == 0) || timeout == 0) break;
		  }
		if ((wordcount == 0) || timeout == 0) break;

	    } while (*++argv);
	}
	else
	{
	    while ((ch = getchar ()) != EOF)
	      {
		dowords (ch);
		if ((wordcount == 0) || timeout == 0) break;
	      }
	}
    }

    if (fancyending)
	dowords (EOF);
    else
	dowords (SILENTEOF);

    fflush (stdout);

    if (testing)
    {
	/*
	 * WE'RE completely done, and YOU aren't! Force catch up. (Note if
	 * charbychar = YES we won't get here, since we're always caught up
	 * after each character as it comes out.)
	 */
	while (testlength > 0)
	{
	    tone (frequency, catchup_time, 0.);
	    toneflush ();
	    testterminal ();
	}
    }

    /* Just to be sure! */
    toneflush ();

    if (showmorse || wordsbefore || wordsafter || showletters || showtesting)
	printf ("\n");
    fflush (stdout);

    if (testing)
	report ();

/* If you make any mistakes exit with a return code! */
    cleanup ();
    return (totalmisscount > 0);
}

static void
new_words_per_minute ()
{
float           wtick, ftick, tick;

    tick = 60. / (words_per_minute * 50);

    /*
     * In the limit as wpm goes past fwpm, Farnsworth becomes kosher PARIS
     */
    if (fwords_per_minute <= words_per_minute)
	ftick = 60. / (words_per_minute * 50);
    else
	ftick = 60. / (fwords_per_minute * 50);

    wtick = (50. * tick - 31. * ftick) / 19.;

    /*
     * This time is used when the computer is waiting on you to hit a key; it
     * is useful to scale the granularity with the real overrall words per
     * minute. This also serves as a measuring rod to see if you are
     * responding "fast enough". If you are too slow, then obviously you are
     * having trouble with that character, and should be given it more OFTEN.
     * Heh heh heh...
     */
    catchup_time = tick;

    /*
     * Things between characters and words go at the "remainder" speed,
     * whatever space you need to make the sped-up Farnsworth characters come
     * out with the correct overall words per minute.
     */
    inter_char_time = wtick * 3.;
    inter_word_time = wtick * 7.;

    /* Things within the character go at the Farnsworth speed */
    intra_char_time = ftick;
    dot_time = ftick;
    dash_time = ftick * 3.;
}

static int      tryingagain = 0, slowpoke = 0;

static void
dowords (int c)
{
static int      wordc = 0;
static char     word[MAXWORDLEN+1];
char           *wordp;
int             ii;
int             againcount = 0;
int             are_we_repeating;

/*
 * Increment the line position counter.
 * If a line gets too long, just cut it off by inserting a new line.
 */
    if (c != EOF && c != SILENTEOF && c != FREQU_TOGGLE) linepos++;
    if (isspace (c) && ((linepos + wordlen) >= LINELENGTH)) c = '\n';
    if (c == '\n') linepos = 0;

    if (isspace (c) || c == EOF || c == SILENTEOF || c == FREQU_TOGGLE)
    {
	if (wordc > 0)
	{
	    if (wordcount > 0) wordcount--;
	    if (timeout > 0)
	      if (difftime(time(NULL),starttime) > (double)timeout)
		timeout = 0;

	    word[wordc] = '\0';

/*
 * We have just read in a new complete word from the input, (hopefully)
 * during the time of an inter-word space minus an inter-char space.
 * Now let's go back and see what happened with the PREVIOUS word,
 * the one that we had just finished playing. Did the user keep
 * up with us?
 */
#ifdef DEBUG
	    fprintf (stderr, " [%d] ", behindness);
#endif
	    if (testing && dynamicspeed && !charbychar)
	    {
		/*
		 * (If charbychar then behindness is ALWAYS 0 at this
		 * point...)
		 */
		if (behindness == 0)
		{
		    /* You're a speed demon! Speed up a bit, then! */
		    words_per_minute *= ALITTLEFASTER;
		    new_words_per_minute ();
		}
		else if (behindness > WAYBEHIND)
		{
		    /* You're way behind! Slow way down. */
		    words_per_minute /= ALOTSLOWER;
		    new_words_per_minute ();
		}
		else if (behindness > BEHIND)
		{
		    /* You're behind! Slow down a bit. */
		    words_per_minute /= ALITTLESLOWER;
		    new_words_per_minute ();
		}
	    }


/*
 * If the user was WAY too far behind stop and catch up with
 * the "new" word as the first one.
 */
	    if (testing && (behindness > TOOFARBEHIND || helpmeflag))
	    {
		if (helpmeflag)
		    printf ("\nOK, let's restart.\n");
		else
		    printf ("\nYou are too far behind! Let's restart.\n");
		fflush (stdout);

		toneflush ();

		/* Flush the keyboard buffer */
		pollyou ();

		/* Forget the past */
		helpmeflag = 0;
		behindness = 0;
		testlength = 0;
		yourlength = 0;

		/* Give the user a little rest. */
		sleep (2);
		printf ("\nWPM now %d\n", (int) (words_per_minute + .5));
		fflush (stdout);
		sleep (2);
		printf ("\nREADY?\n");
		fflush (stdout);
		sleep (1);
		printf ("\nSET\n");
		fflush (stdout);
		sleep (1);
		printf ("\nGO!\n");
		fflush (stdout);
		linepos = 0;
	    }

/*
 * Start treating the new word.
 */
	    if (wordsbefore)
	    {
		/* Try to keep your out-of-sync text from getting swirled in */
		if (showtesting)
		  {
		    printf ("\n");
		    linepos = 0;
		  }

		printf ("%s", word);

		if (showmorse || showletters || wordsafter || showtesting)
		{
		    printf ("  ");
		    for (ii = 0; ii < 16 - (wordc + 2); ii++)
		    {
			printf (" ");
		    }
		}

		fflush (stdout);
	    }

	    if (testing && charbychar)
	    {
		againcount = 0;
	    }

	    for (wordp = word; *wordp != '\0'; wordp++)
	    {
		tryingagain = 0;

	tryagain:
		if (testing && !tryingagain && !showletters &&
		    error_threshold < MAX_ERROR_THRESHOLD &&
		    errorlog[(int) *wordp] > error_threshold)
		{
		    toneflush ();
		    /* Give them a quick hint */
		    printf ("[%c]", *wordp);
		    fflush (stdout);

		    morse (*wordp);

		    toneflush ();
		    if (!showmorse)
		    {
			/* Erase the hint */
			printf ("\b\b\b   \b\b\b");
			fflush (stdout);
		    }
		}
		else
		{
		    morse (*wordp);
		}

		if (testing)
		{
		    if (charbychar)
		    {
			toneflush ();
			/* Force catchup */
			slowpoke = 0;
			while (behindness > 0)
			{
			    if (testterminal () && tryagaincount > 0)
			    {
				/*
				 * OOPS! They got it WRONG! MAKE THEM TRY
				 * AGAIN!
				 */
				printf ("Try again.\n");
				linepos = 0;
				/*
				 * Yeah I know gotos are inelegant but I
				 * don't feel like figuring out the "elegant"
				 * way to do this right now.
				 */
				againcount = tryagaincount - 1;
				tryingagain = 1;
				goto tryagain;
			    }
			    else
			    {
				/*
				 * They got it right, or they didn't answer
				 * yet.
				 */
				if (behindness > 0)
				{
				    /*
				     * They are STILL thinking, the
				     * slowpokes. Wait a bit before trying
				     * again.
				     */
				    tone (frequency, catchup_time, 0.);
				    /*
				     * Keep track of how long they're taking
				     * to answer!
				     */
				    if (slowpoke < SLOWPOKEMAX)
					slowpoke++;
				    toneflush ();
				}
				else if (dynamicspeed && !slowpoke && !tryingagain)
				{
				    /*
				     * They got it right without errors the
				     * first time and we didn't have to wait
				     * for them! A speed demon! Speed up a
				     * bit, then!
				     */
				    words_per_minute *= ALITTLEFASTER;
				    new_words_per_minute ();
				}
			    }
			}

			/* Insufficient penance? */
			if (againcount > 0)
			{
			    againcount--;
			    goto tryagain;
			}
		    }
		    else
		    {
			testterminal ();
			/*
			 * Stop if we get more than max_behindness ahead.
			 * max_behindness == 0 means don't worry about them,
			 * they can be as far behind as they want and we
			 * won't stop!
			 */
			if (max_behindness > 0)
			{
			    are_we_repeating = 0;
			    while (behindness >= max_behindness)
			    {
#ifdef DEBUG
				fprintf (stderr, " (%d) ", behindness);
#endif
				if (are_we_repeating)
				{
				    /*
				     * Pause for a bit so we don't loop too
				     * fast
				     */
				    tone (frequency, catchup_time, 0.);
				}
				else
				{
				    are_we_repeating = 1;
				}
				/* Finish playing whatever we're playing */
				toneflush ();
				/* And give them another chance */
				testterminal ();
			    }
			}
		    }
		}
	    }

	    toneflush ();
	    if (testing)
		testterminal ();

	    if (wordsafter)
	    {
		printf (" (%s)", word);
	    }

	    if (wordsbefore || wordsafter || showmorse)
	      {
		if (!showmorse && !testing && linepos)
		  {
		    if (wordsafter)
		      linepos += 3;
		    else
		      printf (" ");
		  } else {
		    printf ("\n");
		    linepos = 0;
		  }
	      }
	    else if (showletters || showtesting)
	    {
		if (c != EOF && c != SILENTEOF && c != FREQU_TOGGLE)
		{
		    if (showletters)
			printf ("%c", c);

		    if (showtesting)
			testaddchar (c);
		}
	    }

/*
 * WHEW! FINISHED QUEUEING THE WORD FOR PLAYING!
 * Now finish up all the other sundry details...
 */

	    /* Flush the output printing queue... */
	    fflush (stdout);
	    /*
	     * Pause for a bit; this gives the user a sporting chance at
	     * catching up with us.
	     */
	    tone (frequency, SPORTING_RATIO * inter_char_time, 0.);
	    toneflush ();
	    /* Start sounding an inter-word space */
	    tone (frequency, inter_word_time - SPORTING_RATIO * inter_char_time, 0.);

	    /* While that silence is playing check if the user has caught up. */
	    if (testing)
		testterminal ();

	    /* We finished this word; reset the word character count */
	    wordc = 0;
	}
	else if (!(wordsbefore || wordsafter || showmorse)
		 &&
		 (showletters || showtesting))
	{
	    if (c != EOF && c != SILENTEOF && c != FREQU_TOGGLE)
	    {
		if (showletters)
		    printf ("%c", c);

		if (showtesting)
		    testaddchar (c);
	    }
	}

	if (c == EOF)
	{
	    morse (EOF);
	    toneflush ();
	}
	else if (c == SILENTEOF)
	{
	    toneflush ();
	}
	else if (c == FREQU_TOGGLE)
	{
	    /* Switch to the other frequency */
	    /* (Won't work from keyboard, only from a file.) */
	    whichfrequ = 1 - whichfrequ;
	    switch (whichfrequ)
	    {
	    case 1:
		frequency = frequency2;
		break;
	    case 0:
	    default:
		frequency = frequency1;
		break;
	    }
	}
    }
    else
    {
	word[wordc++] = c;
    }

/*
 * If a word gets too long, just cut it off by inserting a space.
 * Just call ourselves with the character we wish we'd gotten...
 */
    if (wordc == wordlen && !(isspace (c) || c == EOF || c == SILENTEOF || c == FREQU_TOGGLE))
	dowords ((int) ' ');
}

/*
 * Don't try to test the person DURING the call into morse!
 */
void
morse (int c)
{
    if ((isalpha (c) && (code[tolower(c)] == NULL)) || ((code[(int) '%'] == NULL) && ((c == EOF) || (c == '\004'))))
      c = ' ';

    if (showletters)
    {
        if ((c == EOF) || (c == '\004'))
	  {
	    if (showmorse)
	      {
		printf ("<SK>");
	      } else {
		printf ("%%");
	      }
	  }
	else if (c == '.' && showmorse)
	    printf ("<DOT>");
	else if (c == '-' && showmorse)
	    printf ("<DASH>");
	else if (c == '+' && showmorse)
	    printf ("<AR>");
	else if (c == '*' && showmorse)
	    printf ("<AS>");
	else if (c == '=' && showmorse)
	    printf ("<BT>");
	else if (c == '(' && showmorse)
	    printf ("<KN>");
	else if (c == '%' && showmorse)
	    printf ("<SK>");
#ifdef ALLPROSIGNS
	else if (c == '^' && (code[(int) '^'] != NULL) && showmorse)
	    printf ("<AA>");
	else if (c == '#' && showmorse)
	    printf ("<BK>");
	else if (c == '&' && showmorse)
	    printf ("<KA>");
	else if (c == '@' && showmorse)
	    printf ("<SN>");
#endif
	else
	    printf ("%c", c);

	fflush (stdout);
    }

    if (isalpha (c))
    {
	if (testing)
	    testaddchar (c - (isupper (c) ? 'A' : 'a') + 'a');
	show (code[c - (isupper (c) ? 'A' : 'a') + 'a']);
    }
    else if ((c == EOF) || (c == '\004'))
    {
	show (code[(int) '%']);
    }
    else if (code[c] != NULL)
    {
	if (testing)
	    testaddchar (c);
	show (code[c]);
    }
    else
    {
	/* Oops! This letter is junk! */

	if (noticebad)
	{
	    if (showletters)
	    {
		fflush (stdout);
	    }

	    /* Simulate a stumble */
	    tone (frequency, 2. * inter_word_time, 0.);
	    toneflush ();
	}

	if (showletters)
	{
	    /* Wipe out what we just printed */
	    fflush (stdout);
	    printf ("\b");
	    printf (" ");
	    printf ("\b");
	    fflush (stdout);
	}

	if (noticebad)
	{
	    if (showletters)
	    {
		/* And replace it with an error message */
		printf ("<UNKNOWN_CHARACTER>");
		fflush (stdout);
	    }

	    /* Give the error call */
	    show ("........");

	    /* Regroup */
	    tone (frequency, inter_word_time, 0.);
	}
    }

    if (showmorse)
	printf (" ");
    fflush (stdout);
    toneflush ();
    tone (frequency, inter_char_time - intra_char_time, 0.);
}


/*
 * Don't try to test the person WHILE doing dots and dashes!
 */
static void
show (char *s)
{
char            c;

    while ((c = *s++) != '\0')
    {
	tone (frequency, intra_char_time, 0.);

#ifdef FLUSHCODE
	if (showmorse)
	    toneflush ();
#endif

	switch (c)
	{
	case '.':
	    tone (frequency, dot_time, volume);
	    break;
	case '-':
	    tone (frequency, dash_time, volume);
	    break;
	}

	if (showmorse)
	{
	    printf ("%c", c);
	    fflush (stdout);
#ifdef FLUSHCODE
	    toneflush ();
#endif
	}
    }
}

/*
 * This only gets passed valid characters: ones
 * that have a morse code associated with them
 * or ones for which isspace(c) is true.
 */
static void
testaddchar (char c)
{
    testpointer = (testpointer + 1) % TESTBUFSZ;
    teststring[testpointer] = c;
#ifdef DEBUG
    fprintf (stderr, " (%c,%d,%d) ", c, testlength, behindness);
#endif
    testlength++;
    if (testlength > TESTBUFSZ)
    {
	fprintf (stderr, "\n\nInput buffer queue overflow! Make TESTBUFSZ bigger!\n");
	fprintf (stderr, "(Or don't fall so far behind)\n");

	die ();
    }

/*
 * Since you are never asked to type spaces (you can type them if
 * you want, but they are ignored) spaces in the input file don't
 * count against your "behindness".
 */
    if (!isspace (c))
	behindness++;
}

static void
youraddchar (char c)
{
    yourpointer = (yourpointer + 1) % TESTBUFSZ;
    yourstring[yourpointer] = c;
#ifdef DEBUG
    fprintf (stderr, " <%c,%d> ", c, yourlength);
#endif
    yourlength++;
    if (yourlength > TESTBUFSZ)
    {
	fprintf (stderr, "\n\nKeyboard typeahead buffer queue overflow! Make TESTBUFSZ bigger!\n");
	fprintf (stderr, "(Or don't type so far ahead... how did you expect to get them right anyway?)\n");

	die ();
    }
}

static void
pollyou (void)
{
    int ii, num;
    char *string;

    num = readterminal (&string);

    for (ii = 0; ii < num; ii++)
	youraddchar (string[ii]);
}

static int
testterminal (void)
{
int             testinc, yourinc;
int             correctchar, yourchar, yourcharnocase;
int             errorcount;
int             resync;

    errorcount = 0;

/*
 * There is nothing in the input file queue right now,
 * so we can't process any of your keystrokes.
 * Defer processing until we can catch up with YOU!
 */
    if (testlength == 0)
	return errorcount;

    /* We're ready for you; but are you ready for us? */
    pollyou ();

/*
 * Process your entries and the input queue entries in parallel
 */
    if (yourlength > 0 && testlength > 0)
    {
	for (testinc = 0, yourinc = 0;
	     testinc < testlength && yourinc < yourlength;
	     testinc++, yourinc++)
	{
	    correctchar = teststring[(testpointer - testlength + 1 + testinc + TESTBUFSZ) % TESTBUFSZ];

	    /*
	     * The latter half of this if shouldn't be necessary, but just in
	     * case...
	     */
	    if (isspace (correctchar) || code[correctchar] == NULL)
	    {
		if (showtesting)
		{
		    printf ("%c", correctchar);
		    fflush (stdout);
		}

		/* White space doesn't count for "behindness" */
		behindness++;
		/* The _other_ pointer wasn't used; don't increment it. */
		yourinc--;

		/* Short circuit the loop */
		continue;
	    }


	    yourchar = yourstring[(yourpointer - yourlength + 1 + yourinc + TESTBUFSZ) % TESTBUFSZ];
	    if (isalpha (yourchar))
		yourcharnocase = yourchar - (isupper (yourchar) ? 'A' : 'a') + 'a';
	    else
		yourcharnocase = yourchar;

	    /* Did you type something rude? If so, just ignore it. */
	    if (isspace (yourchar) || code[yourcharnocase] == NULL)
	    {
		/* ESCAPE: dump status info */
		/* Control-D: dump status info and then bye bye */
		/* Control-H: force restart */
		if (yourchar == '\033' || yourchar == (int) '\004')
		{
		    report ();

		    if (yourchar == (int) '\004')
			die ();
		}
		else if (yourchar == '\b')
		{
		    helpmeflag = 1;
		}

		/* The _other_ pointer wasn't used; don't increment it. */
		testinc--;
		/* Short circuit the loop */
		continue;
	    }

	    if (keepquiet > 1)
	      {
		for (resync = testinc; resync < testlength; resync++)
		  if ( yourcharnocase == teststring[(testpointer - testlength + 1 + resync + TESTBUFSZ) % TESTBUFSZ])
		    {
		      for (; testinc < resync; testinc++)
			{
			  correctchar = teststring[(testpointer - testlength + 1 + testinc + TESTBUFSZ) % TESTBUFSZ];
			  if (isspace (correctchar) || code[correctchar] == NULL)
			    {
			      if (showtesting) printf ("%c", correctchar);
			    } else {
			      printf("%s%c%s", enter_standout_mode, correctchar, exit_standout_mode);
			    }
			}
		      fflush (stdout);
		      correctchar = teststring[(testpointer - testlength + 1 + testinc + TESTBUFSZ) % TESTBUFSZ];
		      keepquiet = 1;
		      break;
		    }
	      }

	    if (yourcharnocase != correctchar)
	    {
		errorcount++;
		totalmisscount++;

		/*
		 * Record that you are having trouble with these.
		 */
		errorlog[correctchar]++;
		if (code[yourcharnocase] != NULL &&
		    errorlog[yourcharnocase] < MAX_ERROR_THRESHOLD)
		    errorlog[yourcharnocase]++;

		if (keepquiet > 0)
		  {
		    printf("%s%c%s", enter_standout_mode, correctchar, exit_standout_mode);
		    fflush (stdout);
		    keepquiet++;
		  } else {
		    /*
		     * Scold them for their mistake.
		     */
		    printf ("\n");

		    if (error_volume) {
			/* Beep using the tone generator */
			toneflush ();
			tone (error_frequency, 0.1, error_volume);
		    } else
			/* Beep using control-G */
			printf ("\007");
		    printf ("%c (%s) for %c (%s)\n",
			    yourchar, code[yourcharnocase],
			    correctchar, code[correctchar]);
		    fflush (stdout);
		    linepos = 0;
		  }

		if (charbychar)
		{
		    /* Give them a bit of time to think about their error */
		    tone (frequency, inter_word_time, 0.);
		    toneflush ();
		}
		if (dynamicspeed && !charbychar)
		{
		    /*
		     * Slow down. Doesn't make sense to slow down for errors,
		     * though, if you've got all the time you want to think
		     * about each one.
		     */
		    words_per_minute /= ERRORSLOWER;
		    new_words_per_minute ();
		}
		if (randomletters && !tryingagain)
		{
		    /*
		     * Ask ones that confused you more often!
		     */
		    if (code[yourcharnocase] != NULL)
		    {
			randomfactor[yourcharnocase] += (3 * RANDOMINCWORSE / 2);
			if (randomfactor[yourcharnocase] > RANDOMMAX)
			    randomfactor[yourcharnocase] = RANDOMMAX;
		    }

		    randomfactor[correctchar] += RANDOMINCWORSE * 2;
		    if (randomfactor[correctchar] > RANDOMMAX)
			randomfactor[correctchar] = RANDOMMAX;
		}
	    }
	    else
	    {
		/*
		 * Record that you got this right.
		 */
		if (!tryingagain)
		{
		    totalhitcount++;
		    if (errorlog[correctchar] > error_floor)
			errorlog[correctchar]--;
		}

		if (showtesting)
		{
		    printf ("%c", yourchar);
		    fflush (stdout);
		}

		if (randomletters && !tryingagain)
		{
		    if (slowpoke == SLOWPOKEMAX)
		    {
			printf ("\nNice to have you back again, I was getting bored!\n");
			linepos = 0;
		    }
		    else if (slowpoke >= SLOWPOKE * 3)
		    {
			/*
			 * Did you take too long thinking about it? If so,
			 * you probably need to be asked this one more
			 * often...
			 */
			randomfactor[correctchar] += (3 * RANDOMINCWORSE / 2);
			if (randomfactor[correctchar] > RANDOMMAX)
			    randomfactor[correctchar] = RANDOMMAX;

			/*
			 * Hits this slow shouldn't count! You were obviously
			 * just guessing! (But it doesn't count as an error
			 * either.)
			 */
			totalhitcount--;
		    }
		    else if (slowpoke > FASTPOKE)
		    {
			randomfactor[correctchar] +=
			 (slowpoke * RANDOMINCWORSE) / (2 * SLOWPOKE);
			if (randomfactor[correctchar] > RANDOMMAX)
			    randomfactor[correctchar] = RANDOMMAX;
		    }
		    else if (slowpoke <= (FASTPOKE / 2))
		    {
			/*
			 * Ask ones that you quickly answer correctly less
			 * often!
			 */
			randomfactor[correctchar] -= (3 * RANDOMINCBETTER / 2);
			/*
			 * Don't let randomfactor hit 0, or you'll NEVER be
			 * asked this one AGAIN!
			 */
			if (randomfactor[correctchar] < 1)
			    randomfactor[correctchar] = 1;
		    }
		    else if (slowpoke <= FASTPOKE)
		    {
			randomfactor[correctchar] -= (RANDOMINCBETTER / 2);
			if (randomfactor[correctchar] < 1)
			    randomfactor[correctchar] = 1;
		    }
		}
	    }

	}
	testlength -= testinc;
	behindness -= testinc;
	yourlength -= yourinc;
    }

/*
 * If there are some extra white space characters in the input queue
 * it's OK, we'll get to them next time or we'll clean them out at the
 * end.
 */
    return errorcount;
}


/*----------------------------------------*/

static void
tone (float hertz, float duration, float amplitude)
{
    Beep ((int) (duration * 1000), (int) (amplitude * 100), (int) hertz);
}


static void
toneflush (void)
{
    BeepWait ();
}


/*----------------------------------------*/

#include <sys/ioctl.h>
#include <fcntl.h>
#include <termios.h>
struct termios oldtermgtty;
struct termios termgtty;
static char    *terminal = "/dev/tty";
static int      termfd;
static int      termopen = 0;
static int      oldflgs, newflgs;

static void
openterminal (void)
{
    /* get parameters and open terminal */

    termfd = open (terminal, O_RDWR | O_NDELAY, 0);
    tcgetattr(termfd, &termgtty);
    oldtermgtty = termgtty;
    if (typeaway != LETMESEE)
	termgtty.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
    termgtty.c_lflag &= ~ICANON;
    termgtty.c_cc[VMIN] = 1;
    termgtty.c_cc[VTIME] = 0;
    tcsetattr(termfd, TCSADRAIN, &termgtty);
    termopen = 1;
}

static int
readterminal (char **string)
{
/* This must be declared static! */
static char     line[TESTBUFSZ];
int             n;

    n = read (termfd, line, sizeof (line) - 1);

    if (n > 0)
    {
	line[n] = '\0';
	*string = line;
    }
    else
	*string = NULL;

    return n;
}

static void
closeterminal (void)
{
    tcsetattr(termfd, TCSADRAIN, &oldtermgtty);
    close (termfd);
}

static void
die (void)
{
    cleanup ();
    exit (1);
}

static void
cleanup (void)
{
    if (termopen)
	closeterminal ();
    BeepCleanup ();
}

static void
suspend (int sig)
{
    struct sigaction handler;

    sigemptyset(&handler.sa_mask);
    handler.sa_flags = 0;
    handler.sa_handler = suspend;
    sigaction (SIGTSTP, &handler, NULL);
    cleanup ();
    kill (getpid (), SIGSTOP);
    if (termopen)
	openterminal ();
    BeepResume ();
}


/*----------------------------------------*/

static int
randomletter (void)
{
int             ii;
int             sum, sum2;
long            ranspot;
static int      lasttime = -1;
static long     norepeat;

/*
 * This keeps the not-so-random random number generator from ignoring
 * certain characters forever!
 */
    norepeat = ((long) time (NULL) / 31) % 17291;

/*
 * All the usable letters get one unit riper.
 */
    for (ii = 0; ii < TWOFIFTYSIX; ii++)
    {
	if (randomfactor[ii] > 0)
	{
#ifdef DEBUGG
	    fprintf (stderr, "%c: %d %d\n",
		     (char) ii, randomfactor[ii], randomripe[ii]);
#endif
	    randomripe[ii]++;
	}
    }

    sum = 0;
    for (ii = 0; ii < TWOFIFTYSIX; ii++)
	sum += (randomfactor[ii] + (int) (randomripe[ii] / RIPECOUNT));

/*
 * The low bits of random aren't very random, I don't care WHAT
 * the manual claims.
 */
    do
    {
	ranspot = ((lrand48() >> 4) % sum + norepeat) % sum;

	sum2 = 0;
	for (ii = 0; ii < TWOFIFTYSIX - 1; ii++)
	{
	    sum2 += (randomfactor[ii] + (int) (randomripe[ii] / RIPECOUNT));

	    if (sum2 > ranspot)
		break;
	}
	/* Do it again if you got the same as last time! */
    } while (ii == lasttime);

    /* This one is FRESH again. */
    randomripe[ii] = 0;
    /* Remember for next time. */
    lasttime = ii;

    return ii;
}

static int
rancomp (const void *elem1, const void *elem2)
{
    register int *e1 = (int *)elem1;
    register int *e2 = (int *)elem2;
    float           a, b;


    a = (randomfactor[(*e1)] + (randomripe[(*e1)] / (float) RIPECOUNT));
    b = (randomfactor[(*e2)] + (randomripe[(*e2)] / (float) RIPECOUNT));

    if (a == b)
	return 0;
    else if (a > b)
	return -1;
    else
	return 1;
}

static void
report (void)
{
    int ii, jj, count;
    float sum; 
    int randomstr[TWOFIFTYSIX];

    printf ("\nCurrent words per minute: %.1f\n", words_per_minute);

    printf ("Total hits %d, misses %d", totalhitcount, totalmisscount);
    if (totalmisscount > 0)
	printf (", hit per miss ratio %.1f\n", (float) totalhitcount / (float) totalmisscount);
    else
	printf ("\n");

    if (randomletters)
    {
	printf ("Most to least frequent choices:\n");
	count = 0;
	sum = 0.;
	for (ii = 0; ii < TWOFIFTYSIX; ii++)
	{
	    if (randomfactor[ii] > 0)
	    {
		sum += (randomfactor[ii] + (randomripe[ii] / (float) RIPECOUNT));
		randomstr[count] = ii;
		count++;
	    }
	}

	qsort ((char *) randomstr, count, sizeof (randomstr[0]), rancomp);

	for (ii = 0; ii < count; ii++)
	{
/*
 * Insert a space for each jump across an integer.
 * The normalization (count/sum) ensures that if all
 * letters were equally probable, they would all have value 1.
 * Since they are not generally equally probable, then 1 is just the average.
 * Thus the rightmost space in the printout marks where the average is.
 * Further left spaces separate off blocks of letters that are approximately
 * twice as probable as the average, three times, etc.
 */
	    if (ii > 0)
	    {
		for (jj = 0; jj <
		     (int) (
			    (randomfactor[randomstr[ii - 1]] + (randomripe[randomstr[ii - 1]] / (float) RIPECOUNT))
			    * count / sum) -
		     (int) (
			    (randomfactor[randomstr[ii]] + (randomripe[randomstr[ii]] / (float) RIPECOUNT))
			    * count / sum);
		     jj++)
		    printf (" ");
	    }
	    printf ("%c", (char) randomstr[ii]);
	}
	printf ("\n");
    }

    /*
     * So you don't get penalized for being "slow" after this.
     */
    if (charbychar)
	slowpoke = SLOWPOKEMAX + 1;

    fflush (stdout);
}