OSDN Git Service

global variable, outfile was removed
[lha/olha.git] / io.c
1 /***********************************************************
2         io.c -- input/output
3 ***********************************************************/
4 #include "ar.h"
5
6 #define CRCPOLY  0xA001         /* ANSI CRC-16 */
7                          /* CCITT: 0x8408 */
8
9 FILE *infile;
10 uint crc;
11 ushort bitbuf;
12
13 ushort crctable[UCHAR_MAX + 1];
14 static uint subbitbuf;
15 static int bitcount;
16
17 void
18 make_crctable(void)
19 {
20     uint i, j, r;
21
22     for (i = 0; i <= UCHAR_MAX; i++) {
23         r = i;
24         for (j = 0; j < CHAR_BIT; j++)
25             if (r & 1)
26                 r = (r >> 1) ^ CRCPOLY;
27             else
28                 r >>= 1;
29         crctable[i] = r;
30     }
31 }
32
33 void
34 fillbuf(struct lzh_istream *rp, int n)
35 {                               /* Shift bitbuf n bits left, read n bits */
36     bitbuf <<= n;
37     while (n > bitcount) {
38         bitbuf |= subbitbuf << (n -= bitcount);
39         if (compsize != 0) {
40             compsize--;
41             subbitbuf = (uchar) getc(rp->fp);
42         }
43         else
44             subbitbuf = 0;
45         bitcount = CHAR_BIT;
46     }
47     bitbuf |= subbitbuf >> (bitcount -= n);
48 }
49
50 uint
51 getbits(struct lzh_istream *rp, int n)
52 {
53     uint x;
54
55     x = bitbuf >> (BITBUFSIZ - n);
56     fillbuf(rp, n);
57     return x;
58 }
59
60 void
61 putbits(struct lzh_ostream *wp, int n, uint x)
62 {                               /* Write rightmost n bits of x */
63     if (n < bitcount) {
64         subbitbuf |= x << (bitcount -= n);
65     }
66     else {
67         if (compsize < origsize) {
68             putc(subbitbuf | (x >> (n -= bitcount)), wp->fp);
69             compsize++;
70         }
71         else
72             unpackable = 1;
73         if (n < CHAR_BIT) {
74             subbitbuf = x << (bitcount = CHAR_BIT - n);
75         }
76         else {
77             if (compsize < origsize) {
78                 putc(x >> (n - CHAR_BIT), wp->fp);
79                 compsize++;
80             }
81             else
82                 unpackable = 1;
83             subbitbuf = x << (bitcount = 2 * CHAR_BIT - n);
84         }
85     }
86 }
87
88 int
89 fread_crc(void *p, int n, FILE * f)
90 {
91     int i;
92
93     i = n = fread(p, 1, n, f);
94     origsize += n;
95     while (--i >= 0)
96         UPDATE_CRC(*(unsigned char*)p++);
97     return n;
98 }
99
100 void
101 fwrite_crc(void *p, int n, FILE * f)
102 {
103     if (fwrite(p, 1, n, f) < n)
104         error("Unable to write");
105     while (--n >= 0)
106         UPDATE_CRC(*(unsigned char*)p++);
107 }
108
109 void
110 init_getbits(struct lzh_istream *rp)
111 {
112     bitbuf = 0;
113     subbitbuf = 0;
114     bitcount = 0;
115     fillbuf(rp, BITBUFSIZ);
116 }
117
118 void
119 init_putbits(void)
120 {
121     bitcount = CHAR_BIT;
122     subbitbuf = 0;
123 }