26b76a6625ba2d2c205ac3b84f56a0c1604a4116
[egate.git] / util / ttyemit.c
1 /* Gateway tty print utility
2  * Europagate, 1995
3  *
4  * $Log: ttyemit.c,v $
5  * Revision 1.1  1995/04/17 09:36:34  adam
6  * ttyemit moved from kernel directory.
7  *
8  *
9  */
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <assert.h>
13
14 #include <ttyemit.h>
15
16 static char line_buf[256];
17 static int  line_col = 0;
18 static int  esc_flag = 0;
19
20 static int  line_min = 30;
21 static int  line_max = 76;
22 static FILE *out_f = stdout;
23
24 void tty_init (FILE *out, int min, int max)
25 {
26     out_f = out;
27     if (min > 0)
28         line_min = min;
29     if (max > 2)
30         line_max = max;
31     line_col = 0;
32     esc_flag = 0;
33 }
34
35 static void flush (void)
36 {
37     int j;
38
39     for (j = 0; j<line_col; j++)
40         putc (line_buf[j], out_f);
41     putc ('\n', out_f);
42     line_col = 0;
43 }
44
45 static void split (int ch)
46 {
47     int i = line_col, j;
48
49     while (1)
50         if (line_buf[--i] == ' ')
51         {
52             int extra = 0;
53
54             for (j = 0; j<i; j++)
55             {
56 #if 1
57                 if (j>1 && line_buf[j] >= 'A'&& line_buf[j] <= 'Z'
58                      && line_buf[j-1] == ' '
59                      && (line_buf[j-2] == '.' || line_buf[j-2] == ';')
60                      && extra < line_max-i )
61                 {
62                     extra++;
63                     putc (' ', out_f);
64                 }
65 #endif
66                 putc (line_buf[j], out_f);
67             }
68             putc ('\n', out_f);
69             j = 0;
70             ++i;
71             while (i < line_col)
72                 line_buf[j++] = line_buf[i++];
73             line_col = j;
74             break;
75         }
76         else if (i < line_min)
77             flush ();
78 }
79
80 static void escape (int ch)
81 {
82     switch (ch)
83     {
84     case 'n':
85         if (line_col >= line_max)
86             split (' ');
87         else
88             flush ();
89         break;
90     case 't':
91         do
92             line_buf[line_col++] = ' ';
93         while (line_col & 7);
94         break;
95     case 's':
96         line_buf[line_col++] = ' ';
97         break;
98     default:
99         line_buf[line_col++] = ch;
100     }
101 }
102
103 void tty_emit (int ch)
104 {
105     if (esc_flag)
106     {
107         escape (ch);
108         esc_flag = 0;
109     }
110     else if (ch == '\\')
111         esc_flag = 1;
112     else if (ch == '\n')
113         flush ();
114     else if (line_col || ch != ' ')
115     {
116         line_buf[line_col++] = ch;
117         if (line_col >= line_max)
118             split (ch);
119     }
120 }