]> git.armaanb.net Git - bin.git/blob - morse.c
signal-finder: add script
[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", "k", "l",
11         "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1",
12         "2", "3", "4", "5", "6", "7", "8", "9", "0", " "};
13
14 const char *ma[] = {"•-", "-•••", "-•-•", "-••", "•", "••-•", "--•", "••••",
15         "••", "•---", "-•-", "•-••", "--", "-•", "---", "•--•", "--•-", "•-•", "•••",
16         "-", "•--", "•••-", "•--", "-••-", "-•--", "--••", "•----", "••---", "•••--",
17         "••••-", "•••••", "-••••", "--•••", "---••", "----•", "-----", "   "};
18
19 void
20 convert(char *c)
21 {
22         if (strcmp(c, "\n") == 0) {
23                 printf("\n");
24                 return;
25         }
26
27         for (int i = 0; aa[i]; i++) {
28                 if (strcmp(c, aa[i]) == 0) {
29                         printf("%s", ma[i]);
30                         break;
31                 } else if (i == sizeof(aa)/sizeof(char *) - 1) {
32                         printf("*");
33                 }
34         }
35         printf(" ");
36 }
37
38 int
39 main(int argc, char **argv)
40 {
41         char c[2];
42         c[1] = '\0';
43
44         if (argv[1] && strcmp(argv[1], "-") != 0) {
45                 for (int i = 0; argv[1][i]; i++) {
46                         c[0] = argv[1][i];
47                         convert(c);
48                 }
49         } else {
50                 while (read(STDIN_FILENO, &c[0], 1) > 0) {
51                         convert(c);
52                 }
53         }
54         printf("\n");
55         return 0;
56 }