Biiig standardization of whitespace. 2 space indents now, no tabs.
[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   private static final int[] CHARACTER_ENCODINGS = {
36       0x038, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9
37       0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x08C, 0x01C, // A-J
38       0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016,  // K-T
39       0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-*
40       0x0A8, 0x0A2, 0x08A, 0x02A // $-%
41   };
42
43   private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39];
44
45   private final boolean usingCheckDigit;
46
47   /**
48    * Creates a reader that assumes all encoded data is data, and does not treat the final
49    * character as a check digit.
50    */
51   public Code39Reader() {
52     usingCheckDigit = false;
53   }
54
55   /**
56    * Creates a reader that can be configured to check the last character as a check digit.
57    *
58    * @param usingCheckDigit if true, treat the last data character as a check digit, not
59    * data, and verify that the checksum passes
60    */
61   public Code39Reader(boolean usingCheckDigit) {
62     this.usingCheckDigit = usingCheckDigit;
63   }
64
65   public Result decodeRow(final int rowNumber, final BitArray row) throws ReaderException {
66
67     int[] start = findAsteriskPattern(row);
68
69     int nextStart = start[1];
70
71     int end = row.getSize();
72
73     // Read off white space
74     while (nextStart < end && !row.get(nextStart)) {
75       nextStart++;
76     }
77
78     StringBuffer result = new StringBuffer();
79     int[] counters = new int[9];
80     char decodedChar;
81     int lastStart;
82     do {
83       recordPattern(row, nextStart, counters);
84       int pattern = toNarrowWidePattern(counters);
85       decodedChar = patternToChar(pattern);
86       result.append(decodedChar);
87       lastStart = nextStart;
88       for (int i = 0; i < counters.length; i++) {
89         nextStart += counters[i];
90       }
91       // Read off white space
92       while (nextStart < end && !row.get(nextStart)) {
93         nextStart++;
94       }
95     } while (decodedChar != '*');
96     result.deleteCharAt(result.length() - 1); // remove asterisk
97
98     if (usingCheckDigit) {
99       int max = result.length() - 1;
100       int total = 0;
101       for (int i = 0; i < max; i++) {
102         total += ALPHABET_STRING.indexOf(result.charAt(i));
103       }
104       if (total % 43 != ALPHABET_STRING.indexOf(result.charAt(max))) {
105         throw new ReaderException("Checksum failed");
106       }
107       result.deleteCharAt(max);
108     }
109
110     String resultString = result.toString();
111     return new Result(resultString,
112         new ResultPoint[]{new GenericResultPoint((float) (start[1] - start[0]) / 2.0f, (float) rowNumber),
113             new GenericResultPoint((float) (nextStart - lastStart) / 2.0f, (float) rowNumber)});
114
115   }
116
117   private static int[] findAsteriskPattern(BitArray row) throws ReaderException {
118     int width = row.getSize();
119     int rowOffset = 0;
120     while (rowOffset < width) {
121       if (row.get(rowOffset)) {
122         break;
123       }
124       rowOffset++;
125     }
126
127     int counterPosition = 0;
128     int[] counters = new int[9];
129     int patternStart = rowOffset;
130     boolean isWhite = false;
131     int patternLength = counters.length;
132
133     for (int i = rowOffset; i < width; i++) {
134       boolean pixel = row.get(i);
135       if ((!pixel && isWhite) || (pixel && !isWhite)) {
136         counters[counterPosition]++;
137       } else {
138         if (counterPosition == patternLength - 1) {
139           try {
140             if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) {
141               return new int[]{patternStart, i};
142             }
143           } catch (ReaderException re) {
144             // no match, continue
145           }
146           patternStart += counters[0] + counters[1];
147           for (int y = 2; y < patternLength; y++) {
148             counters[y - 2] = counters[y];
149           }
150           counterPosition--;
151         } else {
152           counterPosition++;
153         }
154         counters[counterPosition] = 1;
155         isWhite = !isWhite;
156       }
157     }
158     throw new ReaderException("Can't find pattern");
159   }
160
161   private static int toNarrowWidePattern(int[] counters) throws ReaderException {
162     int minCounter = Integer.MAX_VALUE;
163     for (int i = 0; i < counters.length; i++) {
164       if (counters[i] < minCounter) {
165         minCounter = counters[i];
166       }
167     }
168     int maxNarrowCounter = (int) (minCounter * 1.5f);
169     int wideCounters = 0;
170     int pattern = 0;
171     for (int i = 0; i < counters.length; i++) {
172       if (counters[i] > maxNarrowCounter) {
173         pattern |= 1 << (counters.length - 1 - i);
174         wideCounters++;
175       }
176     }
177     if (wideCounters != 3) {
178       throw new ReaderException("Can't find 3 wide bars/spaces out of 9");
179     }
180     return pattern;
181   }
182
183   private static char patternToChar(int pattern) throws ReaderException {
184     for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
185       if (CHARACTER_ENCODINGS[i] == pattern) {
186         return ALPHABET[i];
187       }
188     }
189     throw new ReaderException("Pattern did not match character encoding");
190   }
191
192 }