a1a887afe875f13af1f084306810430a81c1e95e
[mmh] / sbr / cpydgst.c
1
2 /*
3  * cpydgst.c -- copy from one fd to another in encapsulating mode
4  *           -- (do dashstuffing of input data).
5  *
6  * $Id$
7  *
8  * This code is Copyright (c) 2002, by the authors of nmh.  See the
9  * COPYRIGHT file in the root directory of the nmh distribution for
10  * complete copyright information.
11  */
12
13 #include <h/mh.h>
14
15 /*
16  * We want to perform the substitution
17  *
18  *     \n(-.*)\n      -->       \n- \1\n
19  *
20  * This is equivalent to the sed substitution
21  *
22  *     sed -e 's%^-%- -%' < ifile > ofile
23  *
24  *  but the routine below is faster than the pipe, fork, and exec.
25  */
26
27 #define S1 0
28 #define S2 1
29
30 #define output(c)   if (bp >= dp) {flush(); *bp++ = c;} else *bp++ = c
31 #define flush()     if ((j = bp - outbuf) && write (out, outbuf, j) != j) \
32                         adios (ofile, "error writing"); \
33                     else \
34                         bp = outbuf
35
36
37 void
38 cpydgst (int in, int out, char *ifile, char *ofile)
39 {
40     register int i, j, state;
41     register char *cp, *ep;
42     register char *bp, *dp;
43     char buffer[BUFSIZ], outbuf[BUFSIZ];
44
45     dp = (bp = outbuf) + sizeof outbuf;
46     for (state = S1; (i = read (in, buffer, sizeof buffer)) > 0;)
47         for (ep = (cp = buffer) + i; cp < ep; cp++) {
48             if (*cp == '\0')
49                 continue;
50             switch (state) {
51                 case S1: 
52                     if (*cp == '-') {
53                         output ('-');
54                         output (' ');
55                     }
56                     state = S2; /* fall */
57
58                 case S2: 
59                     output (*cp);
60                     if (*cp == '\n')
61                         state = S1;
62                     break;
63             }
64         }
65
66     if (i == -1)
67         adios (ifile, "error reading");
68     flush();
69 }