#include <sys/cdefs.h>
__COPYRIGHT("@(#) Copyright (c) 1988, 1993\
The Regents of the University of California. All rights reserved.");
__RCSID("$NetBSD: morse.c,v 1.23 2024/10/12 19:26:24 rillig Exp $");
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static const char digit[][6] = {
"-----",
".----",
"..---",
"...--",
"....-",
".....",
"-....",
"--...",
"---..",
"----.",
};
static const char alph[][5] = {
".-",
"-...",
"-.-.",
"-..",
".",
"..-.",
"--.",
"....",
"..",
".---",
"-.-",
".-..",
"--",
"-.",
"---",
".--.",
"--.-",
".-.",
"...",
"-",
"..-",
"...-",
".--",
"-..-",
"-.--",
"--..",
};
static const struct {
char c;
const char morse[7];
} other[] = {
{ '.', ".-.-.-" },
{ ',', "--..--" },
{ ':', "---..." },
{ '?', "..--.." },
{ '\'', ".----." },
{ '-', "-....-" },
{ '/', "-..-." },
{ '(', "-.--." },
{ ')', "-.--.-" },
{ '"', ".-..-." },
{ '=', "-...-" },
{ '+', ".-.-." },
{ '_', "..--.-" },
{ '@', ".--.-." },
{ '\0', "" }
};
static void morse(int);
static void decode(const char *);
static void show(const char *);
static int sflag;
static int dflag;
int
main(int argc, char **argv)
{
int ch;
char *p;
setgid(getgid());
while ((ch = getopt(argc, argv, "ds")) != -1)
switch ((char)ch) {
case 'd':
dflag = 1;
break;
case 's':
sflag = 1;
break;
default:
fprintf(stderr, "usage: morse [-ds] [string ...]\n");
exit(1);
}
argc -= optind;
argv += optind;
if (dflag) {
if (*argv) {
do {
decode(*argv);
} while (*++argv);
} else {
char foo[10];
int is_blank, i;
i = 0;
is_blank = 0;
while ((ch = getchar()) != EOF) {
if (ch == '-' || ch == '.') {
foo[i++] = ch;
if (i == 10) {
i = 0;
putchar('x');
while ((ch = getchar()) != EOF &&
(ch == '.' || ch == '-'))
;
is_blank = 1;
}
} else if (i) {
foo[i] = '\0';
decode(foo);
i = 0;
is_blank = 0;
} else if (isspace(ch)) {
if (is_blank) {
putchar(' ');
is_blank = 0;
} else
is_blank = 1;
}
}
}
putchar('\n');
} else {
if (*argv)
do {
for (p = *argv; *p; ++p)
morse((unsigned char)*p);
show("");
} while (*++argv);
else while ((ch = getchar()) != EOF)
morse(ch);
show("...-.-");
}
return 0;
}
void
decode(const char *s)
{
for (size_t i = 0; i < __arraycount(digit); i++)
if (strcmp(digit[i], s) == 0) {
putchar('0' + i);
return;
}
for (size_t i = 0; i < __arraycount(alph); i++)
if (strcmp(alph[i], s) == 0) {
putchar('A' + i);
return;
}
for (size_t i = 0; other[i].c; i++)
if (strcmp(other[i].morse, s) == 0) {
putchar(other[i].c);
return;
}
if (strcmp("...-.-", s) == 0)
return;
putchar('x');
}
void
morse(int c)
{
if (isalpha(c))
show(alph[c - (isupper(c) ? 'A' : 'a')]);
else if (isdigit(c))
show(digit[c - '0']);
else if (isspace(c))
show("");
else
for (int i = 0; other[i].c; i++)
if (other[i].c == c) {
show(other[i].morse);
break;
}
}
void
show(const char *s)
{
if (sflag)
printf(" %s", s);
else for (; *s; ++s)
printf(" %s", *s == '.' ? "dit" : "daw");
printf("\n");
}