1 /* wbmptopbm.c - convert a wbmp file to a portable bitmap
2 
3    This is derived for Netpbm from the pbmwbmp package from
4    <http://www.looplab.com/wap/tools> on 2000.06.06.
5 
6    The specifications for the wbmp format are part of the Wireless
7    Application Environment specification at
8    <http://www.wapforum.org/what/technical.htm>.
9 
10 ** Copyright (C) 1999 Terje Sannum <terje@looplab.com>.
11 **
12 ** Permission to use, copy, modify, and distribute this software and its
13 ** documentation for any purpose and without fee is hereby granted, provided
14 ** that the above copyright notice appear in all copies and that both that
15 ** copyright notice and this permission notice appear in supporting
16 ** documentation.  This software is provided "as is" without express or
17 ** implied warranty.
18 */
19 
20 #include "pbm.h"
21 
22 static int
readc(FILE * f)23 readc(FILE *f) {
24   int c = fgetc(f);
25   if(c == EOF) pm_error("EOF / read error");
26   return c;
27 }
28 
29 
30 
31 static int
readint(FILE * f)32 readint(FILE *f) {
33   int c=0, pos=0, sum=0;
34   do {
35     c = readc(f);
36     sum = (sum << 7*pos++) | (c & 0x7f);
37   } while(c & 0x80);
38   return sum;
39 }
40 
41 
42 
43 static void
readheader(int h,FILE * f)44 readheader(int h, FILE *f) {
45   int c,i;
46   switch(h & 0x60) {
47   case 0x00:
48     /* Type 00: read multi-byte bitfield */
49     do c=readc(f); while(c & 0x80);
50     break;
51   case 0x60:
52     /* Type 11: read name/value pair */
53     for(i=0; i < ((h & 0x70) >> 4) + (h & 0x0f); i++) c=readc(f);
54     break;
55   }
56 }
57 
58 
59 
60 static bit **
readwbmp(FILE * f,int * cols,int * rows)61 readwbmp(FILE *f, int *cols, int *rows) {
62   int i,j,k,row,c;
63   bit **image;
64   /* Type */
65   c = readint(f);
66   if(c != 0) pm_error("Unrecognized WBMP type");
67   /* Headers */
68   c = readc(f); /* FixHeaderField */
69   while(c & 0x80) { /* ExtHeaderFields */
70     c = readc(f);
71     readheader(c, f);
72   }
73   /* Geometry */
74   *cols = readint(f);
75   *rows = readint(f);
76   image = pbm_allocarray(*cols, *rows);
77   /* read image */
78   row = *cols/8;
79   if(*cols%8) row +=1;
80   for(i=0; i<*rows; i++) {
81     for(j=0; j<row; j++) {
82       c=readc(f);
83       for(k=0; k<8 && j*8+k<*cols; k++) {
84 	image[i][j*8+k] = c & (0x80 >> k) ? PBM_WHITE : PBM_BLACK;
85       }
86     }
87   }
88   return image;
89 }
90 
91 
92 
93 int
main(int argc,char * argv[])94 main(int argc, char *argv[]) {
95   FILE *f;
96   bit **image;
97   int rows, cols;
98 
99   pbm_init(&argc, argv);
100   if(argc > 2) {
101     fprintf(stderr, "Copyright (C) 1999 Terje Sannum <terje@looplab.com>\n");
102     pm_usage("[wbmpfile]");
103   }
104 
105   f = argc == 2 ? pm_openr(argv[1]) : stdin;
106   image = readwbmp(f, &cols, &rows);
107   pm_close(f);
108   pbm_writepbm(stdout, image, cols, rows, 0);
109   pm_close(stdout);
110   return 0;
111 }
112 
113