]> git.armaanb.net Git - bin.git/blob - morse.c
eb0bd8ee4f3c7db0609a6bba37b19ab4657bfcbc
[bin.git] / morse.c
1 /* Convert ASCII to morse code. Reads from stdin if provided with no argument
2          or "-", otherwise reads from the first command line argument. Prints "?" if
3          character is not found. */
4
5 #include <string.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <unistd.h>
9
10 const char *aa[] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
11                                                                                 "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
12                                                                                 "u", "v", "w", "x", "y", "z", "1", "2", "3", "4",
13                                                                                 "5", "6", "7", "8", "9", "0", " "};
14
15 const char *ma[] = {"•-", "-•••", "-•-•", "-••", "•", "••-•", "--•",
16                                                                                 "••••", "••", "•---", "-•-", "•-••", "--", "-•",
17                                                                                 "---", "•--•", "--•-", "•-•", "•••", "-", "•--",
18                                                                                 "•••-", "•--", "-••-", "-•--", "--••", "•----",
19                                                                                 "••---", "•••--", "••••-", "•••••", "-••••",
20                                                                                 "--•••", "---••", "----•", "-----", " "};
21
22 void
23 convert(char *c)
24 {
25         if (strcmp(c, "\n") == 0) {
26                 printf("\n");
27                 return;
28         }
29
30         for (int i = 0; aa[i]; i++) {
31                 if (strcmp(c, aa[i]) == 0) {
32                         printf("%s", ma[i]);
33                         break;
34                 } else if (i == sizeof(aa)/sizeof(char *) - 1) {
35                         printf("?");
36                 }
37         }
38         printf(" ");
39 }
40
41 int
42 main(int argc, char **argv)
43 {
44         (void)argc;
45         char c[2];
46         c[1] = '\0';
47
48         if (argv[1] && strcmp(argv[1], "-") != 0) {
49                 for (int i = 0; argv[1][i]; i++) {
50                         c[0] = argv[1][i];
51                         convert(c);
52                 }
53         } else {
54                 while (read(STDIN_FILENO, &c[0], 1) > 0) {
55                         convert(c);
56                 }
57         }
58         printf("\n");
59         return 0;
60 }