Fixed typo on pattern for "I"
[zxing.git] / core / src / com / google / zxing / oned / Code39Reader.java
1 /*
2  * Copyright 2008 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.oned;
18
19 import com.google.zxing.ReaderException;
20 import com.google.zxing.Result;
21 import com.google.zxing.ResultPoint;
22 import com.google.zxing.common.BitArray;
23 import com.google.zxing.common.GenericResultPoint;
24
25 /**
26  * <p>Decodes Code 39 barcodes. This does not supported "Full ASCII Code 39" yet.</p>
27  *
28  * @author srowen@google.com (Sean Owen)
29  */
30 public final class Code39Reader extends AbstractOneDReader {
31
32   private static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
33   private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
34
35   /**
36    * These represent the encodings of characters, as patterns of wide and narrow bars.
37    * The 9 least-significant bits of each int correspond to the pattern of wide and narrow,
38    * with 1s representing "wide" and 0s representing narrow.
39    */
40   private static final int[] CHARACTER_ENCODINGS = {
41       0x038, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9
42       0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J
43       0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016,  // K-T
44       0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-*
45       0x0A8, 0x0A2, 0x08A, 0x02A // $-%
46   };
47
48   private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39];
49
50   private final boolean usingCheckDigit;
51
52   /**
53    * Creates a reader that assumes all encoded data is data, and does not treat the final
54    * character as a check digit.
55    */
56   public Code39Reader() {
57     usingCheckDigit = false;
58   }
59
60   /**
61    * Creates a reader that can be configured to check the last character as a check digit.
62    *
63    * @param usingCheckDigit if true, treat the last data character as a check digit, not
64    * data, and verify that the checksum passes
65    */
66   public Code39Reader(boolean usingCheckDigit) {
67     this.usingCheckDigit = usingCheckDigit;
68   }
69
70   public Result decodeRow(final int rowNumber, final BitArray row) throws ReaderException {
71
72     int[] start = findAsteriskPattern(row);
73
74     int nextStart = start[1];
75
76     int end = row.getSize();
77
78     // Read off white space
79     while (nextStart < end && !row.get(nextStart)) {
80       nextStart++;
81     }
82
83     StringBuffer result = new StringBuffer();
84     int[] counters = new int[9];
85     char decodedChar;
86     int lastStart;
87     do {
88       recordPattern(row, nextStart, counters);
89       int pattern = toNarrowWidePattern(counters);
90       decodedChar = patternToChar(pattern);
91       result.append(decodedChar);
92       lastStart = nextStart;
93       for (int i = 0; i < counters.length; i++) {
94         nextStart += counters[i];
95       }
96       // Read off white space
97       while (nextStart < end && !row.get(nextStart)) {
98         nextStart++;
99       }
100     } while (decodedChar != '*');
101     result.deleteCharAt(result.length() - 1); // remove asterisk
102
103     if (usingCheckDigit) {
104       int max = result.length() - 1;
105       int total = 0;
106       for (int i = 0; i < max; i++) {
107         total += ALPHABET_STRING.indexOf(result.charAt(i));
108       }
109       if (total % 43 != ALPHABET_STRING.indexOf(result.charAt(max))) {
110         throw new ReaderException("Checksum failed");
111       }
112       result.deleteCharAt(max);
113     }
114
115     String resultString = result.toString();
116     return new Result(resultString,
117         new ResultPoint[]{new GenericResultPoint((float) (start[1] - start[0]) / 2.0f, (float) rowNumber),
118             new GenericResultPoint((float) (nextStart - lastStart) / 2.0f, (float) rowNumber)});
119
120   }
121
122   private static int[] findAsteriskPattern(BitArray row) throws ReaderException {
123     int width = row.getSize();
124     int rowOffset = 0;
125     while (rowOffset < width) {
126       if (row.get(rowOffset)) {
127         break;
128       }
129       rowOffset++;
130     }
131
132     int counterPosition = 0;
133     int[] counters = new int[9];
134     int patternStart = rowOffset;
135     boolean isWhite = false;
136     int patternLength = counters.length;
137
138     for (int i = rowOffset; i < width; i++) {
139       boolean pixel = row.get(i);
140       if ((!pixel && isWhite) || (pixel && !isWhite)) {
141         counters[counterPosition]++;
142       } else {
143         if (counterPosition == patternLength - 1) {
144           try {
145             if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) {
146               return new int[]{patternStart, i};
147             }
148           } catch (ReaderException re) {
149             // no match, continue
150           }
151           patternStart += counters[0] + counters[1];
152           for (int y = 2; y < patternLength; y++) {
153             counters[y - 2] = counters[y];
154           }
155           counterPosition--;
156         } else {
157           counterPosition++;
158         }
159         counters[counterPosition] = 1;
160         isWhite = !isWhite;
161       }
162     }
163     throw new ReaderException("Can't find pattern");
164   }
165
166   private static int toNarrowWidePattern(int[] counters) throws ReaderException {
167     int minCounter = Integer.MAX_VALUE;
168     for (int i = 0; i < counters.length; i++) {
169       if (counters[i] < minCounter) {
170         minCounter = counters[i];
171       }
172     }
173     int maxNarrowCounter = (int) (minCounter * 1.5f);
174     int wideCounters = 0;
175     int pattern = 0;
176     for (int i = 0; i < counters.length; i++) {
177       if (counters[i] > maxNarrowCounter) {
178         pattern |= 1 << (counters.length - 1 - i);
179         wideCounters++;
180       }
181     }
182     if (wideCounters != 3) {
183       throw new ReaderException("Can't find 3 wide bars/spaces out of 9");
184     }
185     return pattern;
186   }
187
188   private static char patternToChar(int pattern) throws ReaderException {
189     for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
190       if (CHARACTER_ENCODINGS[i] == pattern) {
191         return ALPHABET[i];
192       }
193     }
194     throw new ReaderException("Pattern did not match character encoding");
195   }
196
197 }