Unify handling of EC level between encoder and decoder
[zxing.git] / core / src / com / google / zxing / qrcode / encoder / Encoder.java
index a914950..8b6b030 100644 (file)
@@ -20,6 +20,8 @@ import com.google.zxing.common.ByteMatrix;
 import com.google.zxing.common.ByteArray;
 import com.google.zxing.common.reedsolomon.GF256;
 import com.google.zxing.common.reedsolomon.ReedSolomonEncoder;
+import com.google.zxing.WriterException;
+import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
 
 import java.util.Vector;
 
@@ -30,7 +32,7 @@ import java.util.Vector;
 public final class Encoder {
 
   // The original table is defined in the table 5 of JISX0510:2004 (p.19).
-  private static final int kAlphanumericTable[] = {
+  private static final int[] ALPHANUMERIC_TABLE = {
       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  // 0x00-0x0f
       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  // 0x10-0x1f
       36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43,  // 0x20-0x2f
@@ -41,20 +43,20 @@ public final class Encoder {
 
   private static final class RSBlockInfo {
 
-    int num_bytes;
-    int block_info[][];
+    final int numBytes;
+    final int[][] blockInfo;
 
-    public RSBlockInfo(int num_bytes, int[][] block_info) {
-      this.num_bytes = num_bytes;
-      this.block_info = block_info;
+    public RSBlockInfo(int numBytes, int[][] blockInfo) {
+      this.numBytes = numBytes;
+      this.blockInfo = blockInfo;
     }
 
   }
 
-  // The table is from table 12 of JISX0510:2004 (p. 30). The "block_info" parts are ordered by
-  // L, M, Q, H. Within each block_info, the 0th element is num_ec_bytes, and the 1st element is
-  // num_rs_blocks. The table was doublechecked by komatsu.
-  private static final RSBlockInfo kRSBlockTable[] = {
+  // The table is from table 12 of JISX0510:2004 (p. 30). The "blockInfo" parts are ordered by
+  // L, M, Q, H. Within each blockInfo, the 0th element is getNumECBytes, and the 1st element is
+  // getNumRSBlocks. The table was doublechecked by komatsu.
+  private static final RSBlockInfo[] RS_BLOCK_TABLE = {
       new RSBlockInfo(  26, new int[][]{ {  7,  1}, {  10,  1}, {  13,  1}, {  17,  1}}),  // Version  1
       new RSBlockInfo(  44, new int[][]{ { 10,  1}, {  16,  1}, {  22,  1}, {  28,  1}}),  // Version  2
       new RSBlockInfo(  70, new int[][]{ { 15,  1}, {  26,  1}, {  36,  2}, {  44,  2}}),  // Version  3
@@ -99,8 +101,8 @@ public final class Encoder {
 
   private static final class BlockPair {
 
-    private ByteArray dataBytes;
-    private ByteArray errorCorrectionBytes;
+    private final ByteArray dataBytes;
+    private final ByteArray errorCorrectionBytes;
 
     public BlockPair(ByteArray data, ByteArray errorCorrection) {
       dataBytes = data;
@@ -117,75 +119,60 @@ public final class Encoder {
 
   }
 
-  // Encode "bytes" with the error correction level "ec_level". The encoding mode will be chosen
-  // internally by ChooseMode(). On success, store the result in "qr_code" and return true. On
-  // error, return false. We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for
-  // "ec_level" since our primary use is to show QR code on desktop screens. We don't need very
+  // Encode "bytes" with the error correction level "getECLevel". The encoding mode will be chosen
+  // internally by chooseMode(). On success, store the result in "qrCode" and return true.
+  // We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for
+  // "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very
   // strong error correction for this purpose.
   //
   // Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode()
   // with which clients can specify the encoding mode. For now, we don't need the functionality.
-  public static boolean Encode(final ByteArray bytes, int ec_level, QRCode qr_code) {
+  public static void encode(final ByteArray bytes, ErrorCorrectionLevel ecLevel, QRCode qrCode)
+      throws WriterException {
     // Step 1: Choose the mode (encoding).
-    final int mode = ChooseMode(bytes);
+    final int mode = chooseMode(bytes);
 
-    // Step 2: Append "bytes" into "data_bits" in appropriate encoding.
-    BitVector data_bits = new BitVector();
-    if (!AppendBytes(bytes, mode, data_bits)) {
-      return false;
-    }
-    // Step 3: Initialize QR code that can contain "data_bits".
-    final int num_input_bytes = data_bits.num_bytes();
-    if (!InitQRCode(num_input_bytes, ec_level, mode, qr_code)) {
-      return false;
-    }
+    // Step 2: Append "bytes" into "dataBits" in appropriate encoding.
+    BitVector dataBits = new BitVector();
+    appendBytes(bytes, mode, dataBits);
+    // Step 3: Initialize QR code that can contain "dataBits".
+    final int numInputBytes = dataBits.sizeInBytes();
+    initQRCode(numInputBytes, ecLevel, mode, qrCode);
 
     // Step 4: Build another bit vector that contains header and data.
-    BitVector header_and_data_bits = new BitVector();
-    if (!AppendModeInfo(qr_code.mode(), header_and_data_bits)) {
-      return false;
-    }
-    if (!AppendLengthInfo(bytes.size(), qr_code.version(), qr_code.mode(), header_and_data_bits)) {
-      return false;
-    }
-    header_and_data_bits.AppendBitVector(data_bits);
+    BitVector headerAndDataBits = new BitVector();
+    appendModeInfo(qrCode.getMode(), headerAndDataBits);
+    appendLengthInfo(bytes.size(), qrCode.getVersion(), qrCode.getMode(), headerAndDataBits);
+    headerAndDataBits.appendBitVector(dataBits);
 
     // Step 5: Terminate the bits properly.
-    if (!TerminateBits(qr_code.num_data_bytes(), header_and_data_bits)) {
-      return false;
-    }
+    terminateBits(qrCode.getNumDataBytes(), headerAndDataBits);
 
     // Step 6: Interleave data bits with error correction code.
-    BitVector final_bits = new BitVector();
-    InterleaveWithECBytes(header_and_data_bits, qr_code.num_total_bytes(), qr_code.num_data_bytes(),
-        qr_code.num_rs_blocks(), final_bits);
+    BitVector finalBits = new BitVector();
+    interleaveWithECBytes(headerAndDataBits, qrCode.getNumTotalBytes(), qrCode.getNumDataBytes(),
+        qrCode.getNumRSBlocks(), finalBits);
 
-    // Step 7: Choose the mask pattern and set to "qr_code".
-    ByteMatrix matrix = new ByteMatrix(qr_code.matrix_width(), qr_code.matrix_width());
-    qr_code.set_mask_pattern(ChooseMaskPattern(final_bits, qr_code.ec_level(), qr_code.version(),
+    // Step 7: Choose the mask pattern and set to "qrCode".
+    ByteMatrix matrix = new ByteMatrix(qrCode.getMatrixWidth(), qrCode.getMatrixWidth());
+    qrCode.setMaskPattern(chooseMaskPattern(finalBits, qrCode.getECLevel(), qrCode.getVersion(),
         matrix));
-    if (qr_code.mask_pattern() == -1) {
-      // There was an error.
-      return false;
-    }
 
-    // Step 8.  Build the matrix and set it to "qr_code".
-    MatrixUtil.BuildMatrix(final_bits, qr_code.ec_level(), qr_code.version(),
-        qr_code.mask_pattern(), matrix);
-    qr_code.set_matrix(matrix);
+    // Step 8.  Build the matrix and set it to "qrCode".
+    MatrixUtil.buildMatrix(finalBits, qrCode.getECLevel(), qrCode.getVersion(),
+        qrCode.getMaskPattern(), matrix);
+    qrCode.setMatrix(matrix);
     // Step 9.  Make sure we have a valid QR Code.
-    if (!qr_code.IsValid()) {
-      Debug.LOG_ERROR("Invalid QR code: " + qr_code.toString());
-      return false;
+    if (!qrCode.isValid()) {
+      throw new WriterException("Invalid QR code: " + qrCode.toString());
     }
-    return true;
   }
 
   // Return the code point of the table used in alphanumeric mode. Return -1 if there is no
   // corresponding code in the table.
-  static int GetAlphanumericCode(int code) {
-    if (code < kAlphanumericTable.length) {
-      return kAlphanumericTable[code];
+  static int getAlphanumericCode(int code) {
+    if (code < ALPHANUMERIC_TABLE.length) {
+      return ALPHANUMERIC_TABLE[code];
     }
     return -1;
   }
@@ -198,320 +185,314 @@ public final class Encoder {
   // interpreted as one character in Shift_JIS, but also two characters in ISO-8859-1.
   //
   // JAVAPORT: This MODE_KANJI limitation sounds like a problem for us.
-  public static int ChooseMode(final ByteArray bytes) {
-    boolean has_numeric = false;
-    boolean has_alphanumeric = false;
-    boolean has_other = false;
+  public static int chooseMode(final ByteArray bytes) throws WriterException {
+    boolean hasNumeric = false;
+    boolean hasAlphanumeric = false;
+    boolean hasOther = false;
     for (int i = 0; i < bytes.size(); ++i) {
       final int oneByte = bytes.at(i);
       if (oneByte >= '0' && oneByte <= '9') {
-        has_numeric = true;
-      } else if (GetAlphanumericCode(oneByte) != -1) {
-        has_alphanumeric = true;
+        hasNumeric = true;
+      } else if (getAlphanumericCode(oneByte) != -1) {
+        hasAlphanumeric = true;
       } else {
-        has_other = true;
+        hasOther = true;
       }
     }
-    if (has_other) {
+    if (hasOther) {
       return QRCode.MODE_8BIT_BYTE;
-    } else if (has_alphanumeric) {
+    } else if (hasAlphanumeric) {
       return QRCode.MODE_ALPHANUMERIC;
-    } else if (has_numeric) {
+    } else if (hasNumeric) {
       return QRCode.MODE_NUMERIC;
     }
     // "bytes" must be empty to reach here.
-    Debug.DCHECK(bytes.empty());
+    if (!bytes.empty()) {
+      throw new WriterException("Bytes left over");
+    }
     return QRCode.MODE_8BIT_BYTE;
   }
 
-  private static int ChooseMaskPattern(final BitVector bits, int ec_level, int version,
-      ByteMatrix matrix) {
-    if (!QRCode.IsValidMatrixWidth(matrix.width())) {
-      Debug.LOG_ERROR("Invalid matrix width: " + matrix.width());
-      return -1;
+  private static int chooseMaskPattern(final BitVector bits, ErrorCorrectionLevel ecLevel, int version,
+      ByteMatrix matrix) throws WriterException {
+    if (!QRCode.isValidMatrixWidth(matrix.width())) {
+      throw new WriterException("Invalid matrix width: " + matrix.width());
     }
 
-    int min_penalty = Integer.MAX_VALUE;  // Lower penalty is better.
-    int best_mask_pattern = -1;
+    int minPenalty = Integer.MAX_VALUE;  // Lower penalty is better.
+    int bestMaskPattern = -1;
     // We try all mask patterns to choose the best one.
-    for (int i = 0; i < QRCode.kNumMaskPatterns; ++i) {
-      final int mask_pattern = i;
-      if (!MatrixUtil.BuildMatrix(bits, ec_level, version,
-          mask_pattern, matrix)) {
-        return -1;
-      }
-      final int penalty = MaskUtil.CalculateMaskPenalty(matrix);
-      Debug.LOG_INFO("mask_pattern: " + mask_pattern + ", " + "penalty: " + penalty);
-      if (penalty < min_penalty) {
-        min_penalty = penalty;
-        best_mask_pattern = mask_pattern;
+    for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) {
+      MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
+      final int penalty = MaskUtil.calculateMaskPenalty(matrix);
+      if (penalty < minPenalty) {
+        minPenalty = penalty;
+        bestMaskPattern = maskPattern;
       }
     }
-    return best_mask_pattern;
+    return bestMaskPattern;
   }
 
-  // Initialize "qr_code" according to "num_input_bytes", "ec_level", and "mode". On success, modify
-  // "qr_code" and return true. On error, return false.
-  private static boolean InitQRCode(int num_input_bytes, int ec_level, int mode, QRCode qr_code) {
-    qr_code.set_ec_level(ec_level);
-    qr_code.set_mode(mode);
-
-    if (!QRCode.IsValidECLevel(ec_level)) {
-      Debug.LOG_ERROR("Invalid EC level: " + ec_level);
-      return false;
-    }
+  // Initialize "qrCode" according to "numInputBytes", "ecLevel", and "mode". On success, modify
+  // "qrCode" and return true.
+  private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, int mode, QRCode qrCode)
+      throws WriterException {
+    qrCode.setECLevel(ecLevel);
+    qrCode.setMode(mode);
 
     // In the following comments, we use numbers of Version 7-H.
-    for (int i = 0; i < kRSBlockTable.length; ++i) {
-      final RSBlockInfo row = kRSBlockTable[i];
-      // num_bytes = 196
-      final int num_bytes = row.num_bytes;
-      // num_ec_bytes = 130
-      final int num_ec_bytes  = row.block_info[ec_level][0];
-      // num_rs_blocks = 5
-      final int num_rs_blocks = row.block_info[ec_level][1];
-      // num_data_bytes = 196 - 130 = 66
-      final int num_data_bytes = num_bytes - num_ec_bytes;
-      // We want to choose the smallest version which can contain data of "num_input_bytes" + some
+    for (int i = 0; i < RS_BLOCK_TABLE.length; ++i) {
+      final RSBlockInfo row = RS_BLOCK_TABLE[i];
+      // numBytes = 196
+      final int numBytes = row.numBytes;
+      // getNumECBytes = 130
+      final int numEcBytes  = row.blockInfo[ecLevel.ordinal()][0];
+      // getNumRSBlocks = 5
+      final int numRSBlocks = row.blockInfo[ecLevel.ordinal()][1];
+      // getNumDataBytes = 196 - 130 = 66
+      final int numDataBytes = numBytes - numEcBytes;
+      // We want to choose the smallest version which can contain data of "numInputBytes" + some
       // extra bits for the header (mode info and length info). The header can be three bytes
       // (precisely 4 + 16 bits) at most. Hence we do +3 here.
-      if (num_data_bytes >= num_input_bytes + 3) {
+      if (numDataBytes >= numInputBytes + 3) {
         // Yay, we found the proper rs block info!
-        qr_code.set_version(i + 1);
-        qr_code.set_num_total_bytes(num_bytes);
-        qr_code.set_num_data_bytes(num_data_bytes);
-        qr_code.set_num_rs_blocks(num_rs_blocks);
-        // num_ec_bytes = 196 - 66 = 130
-        qr_code.set_num_ec_bytes(num_bytes - num_data_bytes);
-        // num_matrix_width = 21 + 6 * 4 = 45
-        qr_code.set_matrix_width(21 + i * 4);
-        return true;
+        qrCode.setVersion(i + 1);
+        qrCode.setNumTotalBytes(numBytes);
+        qrCode.setNumDataBytes(numDataBytes);
+        qrCode.setNumRSBlocks(numRSBlocks);
+        // getNumECBytes = 196 - 66 = 130
+        qrCode.setNumECBytes(numBytes - numDataBytes);
+        // matrix width = 21 + 6 * 4 = 45
+        qrCode.setMatrixWidth(21 + i * 4);
+        return;
       }
     }
-    Debug.LOG_ERROR("Cannot find proper rs block info (input data too big?)");
-    return false;
+    throw new WriterException("Cannot find proper rs block info (input data too big?)");
   }
 
   // Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
-  static boolean TerminateBits(int num_data_bytes, BitVector bits) {
-    final int capacity = num_data_bytes * 8;
+  static void terminateBits(int numDataBytes, BitVector bits) throws WriterException {
+    final int capacity = numDataBytes * 8;
     if (bits.size() > capacity) {
-      Debug.LOG_ERROR("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity);
-      return false;
+      throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity);
     }
     // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
     for (int i = 0; i < 4 && bits.size() < capacity; ++i) {
-      bits.AppendBit(0);
+      bits.appendBit(0);
     }
-    final int num_bits_in_last_byte = bits.size() % 8;
+    final int numBitsInLastByte = bits.size() % 8;
     // If the last byte isn't 8-bit aligned, we'll add padding bits.
-    if (num_bits_in_last_byte > 0) {
-      final int num_padding_bits = 8 - num_bits_in_last_byte;
-      for (int i = 0; i < num_padding_bits; ++i) {
-        bits.AppendBit(0);
+    if (numBitsInLastByte > 0) {
+      final int numPaddingBits = 8 - numBitsInLastByte;
+      for (int i = 0; i < numPaddingBits; ++i) {
+        bits.appendBit(0);
       }
     }
     // Should be 8-bit aligned here.
-    Debug.DCHECK_EQ(0, bits.size() % 8);
+    if (bits.size() % 8 != 0) {
+      throw new WriterException("Number of bits is not a multiple of 8");
+    }
     // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
-    final int num_padding_bytes = num_data_bytes - bits.num_bytes();
-    for (int i = 0; i < num_padding_bytes; ++i) {
+    final int numPaddingBytes = numDataBytes - bits.sizeInBytes();
+    for (int i = 0; i < numPaddingBytes; ++i) {
       if (i % 2 == 0) {
-        bits.AppendBits(0xec, 8);
+        bits.appendBits(0xec, 8);
       } else {
-        bits.AppendBits(0x11, 8);
+        bits.appendBits(0x11, 8);
       }
     }
-    Debug.DCHECK_EQ(bits.size(), capacity);  // Should be same.
-    return bits.size() == capacity;
+    if (bits.size() != capacity) {
+      throw new WriterException("Bits size does not equal capacity");
+    }
   }
 
-  // Get number of data bytes and number of error correction bytes for block id "block_id". Store
-  // the result in "num_data_bytes_in_block", and "num_ec_bytes_in_block". See table 12 in 8.5.1 of
+  // Get number of data bytes and number of error correction bytes for block id "blockID". Store
+  // the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
   // JISX0510:2004 (p.30)
-  static void GetNumDataBytesAndNumECBytesForBlockID(int num_total_bytes, int num_data_bytes,
-      int num_rs_blocks, int block_id, int[] num_data_bytes_in_block,
-      int[] num_ec_bytes_in_block) {
-    Debug.DCHECK_LT(block_id, num_rs_blocks);
-    // num_rs_blocks_in_group2 = 196 % 5 = 1
-    final int num_rs_blocks_in_group2 = num_total_bytes % num_rs_blocks;
-    // num_rs_blocks_in_group1 = 5 - 1 = 4
-    final int num_rs_blocks_in_group1 = num_rs_blocks - num_rs_blocks_in_group2;
-    // num_total_bytes_in_group1 = 196 / 5 = 39
-    final int num_total_bytes_in_group1 = num_total_bytes / num_rs_blocks;
-    // num_total_bytes_in_group2 = 39 + 1 = 40
-    final int num_total_bytes_in_group2 = num_total_bytes_in_group1 + 1;
-    // num_data_bytes_in_group1 = 66 / 5 = 13
-    final int num_data_bytes_in_group1 = num_data_bytes / num_rs_blocks;
-    // num_data_bytes_in_group2 = 13 + 1 = 14
-    final int num_data_bytes_in_group2 = num_data_bytes_in_group1 + 1;
-    // num_ec_bytes_in_group1 = 39 - 13 = 26
-    final int num_ec_bytes_in_group1 = num_total_bytes_in_group1 -
-        num_data_bytes_in_group1;
-    // num_ec_bytes_in_group2 = 40 - 14 = 26
-    final int num_ec_bytes_in_group2 = num_total_bytes_in_group2 -
-        num_data_bytes_in_group2;
+  static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes,
+      int numRSBlocks, int blockID, int[] numDataBytesInBlock,
+      int[] numECBytesInBlock) throws WriterException {
+    if (blockID >= numRSBlocks) {
+      throw new WriterException("Block ID too large");
+    }
+    // numRsBlocksInGroup2 = 196 % 5 = 1
+    final int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;
+    // numRsBlocksInGroup1 = 5 - 1 = 4
+    final int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;
+    // numTotalBytesInGroup1 = 196 / 5 = 39
+    final int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks;
+    // numTotalBytesInGroup2 = 39 + 1 = 40
+    final int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;
+    // numDataBytesInGroup1 = 66 / 5 = 13
+    final int numDataBytesInGroup1 = numDataBytes / numRSBlocks;
+    // numDataBytesInGroup2 = 13 + 1 = 14
+    final int numDataBytesInGroup2 = numDataBytesInGroup1 + 1;
+    // numEcBytesInGroup1 = 39 - 13 = 26
+    final int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;
+    // numEcBytesInGroup2 = 40 - 14 = 26
+    final int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;
     // Sanity checks.
     // 26 = 26
-    Debug.DCHECK_EQ(num_ec_bytes_in_group1, num_ec_bytes_in_group2);
+    if (numEcBytesInGroup1 != numEcBytesInGroup2) {
+      throw new WriterException("EC bytes mismatch");
+    }
     // 5 = 4 + 1.
-    Debug.DCHECK_EQ(num_rs_blocks, num_rs_blocks_in_group1 + num_rs_blocks_in_group2);
+    if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) {
+      throw new WriterException("RS blocks mismatch");
+    }
     // 196 = (13 + 26) * 4 + (14 + 26) * 1
-    Debug.DCHECK_EQ(num_total_bytes,
-        ((num_data_bytes_in_group1 + num_ec_bytes_in_group1) *
-            num_rs_blocks_in_group1) +
-            ((num_data_bytes_in_group2 + num_ec_bytes_in_group2) *
-                num_rs_blocks_in_group2));
-
-    if (block_id < num_rs_blocks_in_group1) {
-      num_data_bytes_in_block[0] = num_data_bytes_in_group1;
-      num_ec_bytes_in_block[0] = num_ec_bytes_in_group1;
+    if (numTotalBytes !=
+        ((numDataBytesInGroup1 + numEcBytesInGroup1) *
+            numRsBlocksInGroup1) +
+            ((numDataBytesInGroup2 + numEcBytesInGroup2) *
+                numRsBlocksInGroup2)) {
+      throw new WriterException("Total bytes mismatch");
+    }
+
+    if (blockID < numRsBlocksInGroup1) {
+      numDataBytesInBlock[0] = numDataBytesInGroup1;
+      numECBytesInBlock[0] = numEcBytesInGroup1;
     } else {
-      num_data_bytes_in_block[0] = num_data_bytes_in_group2;
-      num_ec_bytes_in_block[0] = num_ec_bytes_in_group2;
+      numDataBytesInBlock[0] = numDataBytesInGroup2;
+      numECBytesInBlock[0] = numEcBytesInGroup2;
     }
   }
 
   // Interleave "bits" with corresponding error correction bytes. On success, store the result in
-  // "result" and return true. On error, return false. The interleave rule is complicated. See 8.6
+  // "result" and return true. The interleave rule is complicated. See 8.6
   // of JISX0510:2004 (p.37) for details.
-  static boolean InterleaveWithECBytes(final BitVector bits, int num_total_bytes,
-      int num_data_bytes, int num_rs_blocks, BitVector result) {
+  static void interleaveWithECBytes(final BitVector bits, int numTotalBytes,
+      int numDataBytes, int numRSBlocks, BitVector result) throws WriterException {
 
-    // "bits" must have "num_data_bytes" bytes of data.
-    Debug.DCHECK(bits.num_bytes() == num_data_bytes);
+    // "bits" must have "getNumDataBytes" bytes of data.
+    if (bits.sizeInBytes() != numDataBytes) {
+      throw new WriterException("Number of bits and data bytes does not match");
+    }
 
     // Step 1.  Divide data bytes into blocks and generate error correction bytes for them. We'll
     // store the divided data bytes blocks and error correction bytes blocks into "blocks".
-    int data_bytes_offset = 0;
-    int max_num_data_bytes = 0;
-    int max_num_ec_bytes = 0;
+    int dataBytesOffset = 0;
+    int maxNumDataBytes = 0;
+    int maxNumEcBytes = 0;
 
     // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
-    Vector blocks = new Vector(num_rs_blocks);
+    Vector blocks = new Vector(numRSBlocks);
 
-    for (int i = 0; i < num_rs_blocks; ++i) {
-      int[] num_data_bytes_in_block = new int[1];
-      int[] num_ec_bytes_in_block = new int[1];
-      GetNumDataBytesAndNumECBytesForBlockID(
-          num_total_bytes, num_data_bytes, num_rs_blocks, i,
-          num_data_bytes_in_block, num_ec_bytes_in_block);
+    for (int i = 0; i < numRSBlocks; ++i) {
+      int[] numDataBytesInBlock = new int[1];
+      int[] numEcBytesInBlock = new int[1];
+      getNumDataBytesAndNumECBytesForBlockID(
+          numTotalBytes, numDataBytes, numRSBlocks, i,
+          numDataBytesInBlock, numEcBytesInBlock);
 
-      ByteArray data_bytes = new ByteArray();
-      data_bytes.set(bits.getArray(), data_bytes_offset, num_data_bytes_in_block[0]);
-      ByteArray ec_bytes = GenerateECBytes(data_bytes, num_ec_bytes_in_block[0]);
-      blocks.addElement(new BlockPair(data_bytes, ec_bytes));
+      ByteArray dataBytes = new ByteArray();
+      dataBytes.set(bits.getArray(), dataBytesOffset, numDataBytesInBlock[0]);
+      ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
+      blocks.addElement(new BlockPair(dataBytes, ecBytes));
 
-      max_num_data_bytes = Math.max(max_num_data_bytes, data_bytes.size());
-      max_num_ec_bytes = Math.max(max_num_ec_bytes, ec_bytes.size());
-      data_bytes_offset += num_data_bytes_in_block[0];
+      maxNumDataBytes = Math.max(maxNumDataBytes, dataBytes.size());
+      maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.size());
+      dataBytesOffset += numDataBytesInBlock[0];
+    }
+    if (numDataBytes != dataBytesOffset) {
+      throw new WriterException("Data bytes does not match offset");
     }
-    Debug.DCHECK_EQ(num_data_bytes, data_bytes_offset);
 
     // First, place data blocks.
-    for (int i = 0; i < max_num_data_bytes; ++i) {
+    for (int i = 0; i < maxNumDataBytes; ++i) {
       for (int j = 0; j < blocks.size(); ++j) {
-        final ByteArray data_bytes = ((BlockPair) blocks.elementAt(j)).getDataBytes();
-        if (i < data_bytes.size()) {
-          result.AppendBits(data_bytes.at(i), 8);
+        final ByteArray dataBytes = ((BlockPair) blocks.elementAt(j)).getDataBytes();
+        if (i < dataBytes.size()) {
+          result.appendBits(dataBytes.at(i), 8);
         }
       }
     }
     // Then, place error correction blocks.
-    for (int i = 0; i < max_num_ec_bytes; ++i) {
+    for (int i = 0; i < maxNumEcBytes; ++i) {
       for (int j = 0; j < blocks.size(); ++j) {
-        final ByteArray ec_bytes = ((BlockPair) blocks.elementAt(j)).getErrorCorrectionBytes();
-        if (i < ec_bytes.size()) {
-          result.AppendBits(ec_bytes.at(i), 8);
+        final ByteArray ecBytes = ((BlockPair) blocks.elementAt(j)).getErrorCorrectionBytes();
+        if (i < ecBytes.size()) {
+          result.appendBits(ecBytes.at(i), 8);
         }
       }
     }
-    if (num_total_bytes == result.num_bytes()) {  // Should be same.
-      return true;
-    }
-    Debug.LOG_ERROR("Interleaving error: " + num_total_bytes + " and " + result.num_bytes() +
+    if (numTotalBytes != result.sizeInBytes()) {  // Should be same.
+      throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.sizeInBytes() +
         " differ.");
-    return false;
+    }
   }
 
-  static ByteArray GenerateECBytes(ByteArray data_bytes, int num_ec_bytes_in_block) {
-    int numDataBytes = data_bytes.size();
-    int[] toEncode = new int[numDataBytes + num_ec_bytes_in_block];
+  static ByteArray generateECBytes(ByteArray dataBytes, int numEcBytesInBlock) {
+    int numDataBytes = dataBytes.size();
+    int[] toEncode = new int[numDataBytes + numEcBytesInBlock];
     for (int i = 0; i < numDataBytes; i++) {
-      toEncode[i] = data_bytes.at(i);
+      toEncode[i] = dataBytes.at(i);
     }
-    new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, num_ec_bytes_in_block);
+    new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, numEcBytesInBlock);
 
-    ByteArray ec_bytes = new ByteArray(num_ec_bytes_in_block);
-    for (int i = 0; i < num_ec_bytes_in_block; i++) {
-      ec_bytes.set(i, toEncode[numDataBytes + i]);
+    ByteArray ecBytes = new ByteArray(numEcBytesInBlock);
+    for (int i = 0; i < numEcBytesInBlock; i++) {
+      ecBytes.set(i, toEncode[numDataBytes + i]);
     }
-    return ec_bytes;
+    return ecBytes;
   }
 
   // Append mode info. On success, store the result in "bits" and return true. On error, return
   // false.
-  static boolean AppendModeInfo(int mode, BitVector bits) {
-    final int code = QRCode.GetModeCode(mode);
-    if (code == -1) {
-      Debug.LOG_ERROR("Invalid mode: " + mode);
-      return false;
-    }
-    bits.AppendBits(code, 4);
-    return true;
+  static void appendModeInfo(int mode, BitVector bits) throws WriterException {
+    final int code = QRCode.getModeCode(mode);
+    bits.appendBits(code, 4);
   }
 
 
   // Append length info. On success, store the result in "bits" and return true. On error, return
   // false.
-  static boolean AppendLengthInfo(int num_bytes, int version, int mode, BitVector bits) {
-    int num_letters = num_bytes;
+  static void appendLengthInfo(int numBytes, int version, int mode, BitVector bits) throws WriterException {
+    int numLetters = numBytes;
     // In Kanji mode, a letter is represented in two bytes.
     if (mode == QRCode.MODE_KANJI) {
-      Debug.DCHECK_EQ(0, num_letters % 2);
-      num_letters /= 2;
+      if (numLetters % 2 != 0) {
+        throw new WriterException("Number of letters must be even");
+      }
+      numLetters /= 2;
     }
 
-    final int num_bits = QRCode.GetNumBitsForLength(version, mode);
-    if (num_bits == -1) {
-      Debug.LOG_ERROR("num_bits unset");
-      return false;
-    }
-    if (num_letters > ((1 << num_bits) - 1)) {
-      Debug.LOG_ERROR(num_letters + "is bigger than" + ((1 << num_bits) - 1));
-      return false;
+    final int numBits = QRCode.getNumBitsForLength(version, mode);
+    if (numLetters > ((1 << numBits) - 1)) {
+      throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1));
     }
-    bits.AppendBits(num_letters, num_bits);
-    return true;
+    bits.appendBits(numLetters, numBits);
   }
 
   // Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits"
-  // and return true. On error, return false.
-  static boolean AppendBytes(final ByteArray bytes, int mode, BitVector bits) {
+  // and return true.
+  static void appendBytes(final ByteArray bytes, int mode, BitVector bits) throws WriterException {
     switch (mode) {
       case QRCode.MODE_NUMERIC:
-        return AppendNumericBytes(bytes, bits);
+        appendNumericBytes(bytes, bits);
+        break;
       case QRCode.MODE_ALPHANUMERIC:
-        return AppendAlphanumericBytes(bytes, bits);
+        appendAlphanumericBytes(bytes, bits);
+        break;
       case QRCode.MODE_8BIT_BYTE:
-        return Append8BitBytes(bytes, bits);
+        append8BitBytes(bytes, bits);
+        break;
       case QRCode.MODE_KANJI:
-        return AppendKanjiBytes(bytes, bits);
-      default:
+        appendKanjiBytes(bytes, bits);
         break;
+      default:
+        throw new WriterException("Invalid mode: " + mode);
     }
-    Debug.LOG_ERROR("Invalid mode: " + mode);
-    return false;
   }
 
   // Append "bytes" to "bits" using QRCode.MODE_NUMERIC mode. On success, store the result in "bits"
-  // and return true. On error, return false.
-  static boolean AppendNumericBytes(final ByteArray bytes, BitVector bits) {
+  // and return true.
+  static void appendNumericBytes(final ByteArray bytes, BitVector bits) throws WriterException {
     // Validate all the bytes first.
     for (int i = 0; i < bytes.size(); ++i) {
       int oneByte = bytes.at(i);
       if (oneByte < '0' || oneByte > '9') {
-        return false;
+        throw new WriterException("Non-digit found");
       }
     }
     for (int i = 0; i < bytes.size();) {
@@ -520,67 +501,64 @@ public final class Encoder {
         // Encode three numeric letters in ten bits.
         final int num2 = bytes.at(i + 1) - '0';
         final int num3 = bytes.at(i + 2) - '0';
-        bits.AppendBits(num1 * 100 + num2 * 10 + num3, 10);
+        bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
         i += 3;
       } else if (i + 1 < bytes.size()) {
         // Encode two numeric letters in seven bits.
         final int num2 = bytes.at(i + 1) - '0';
-        bits.AppendBits(num1 * 10 + num2, 7);
+        bits.appendBits(num1 * 10 + num2, 7);
         i += 2;
       } else {
         // Encode one numeric letter in four bits.
-        bits.AppendBits(num1, 4);
+        bits.appendBits(num1, 4);
         ++i;
       }
     }
-    return true;
   }
 
   // Append "bytes" to "bits" using QRCode.MODE_ALPHANUMERIC mode. On success, store the result in
-  // "bits" and return true. On error, return false.
-  static boolean AppendAlphanumericBytes(final ByteArray bytes, BitVector bits) {
+  // "bits" and return true.
+  static void appendAlphanumericBytes(final ByteArray bytes, BitVector bits) throws WriterException {
     for (int i = 0; i < bytes.size();) {
-      final int code1 = GetAlphanumericCode(bytes.at(i));
+      final int code1 = getAlphanumericCode(bytes.at(i));
       if (code1 == -1) {
-        return false;
+        throw new WriterException();
       }
       if (i + 1 < bytes.size()) {
-        final int code2 = GetAlphanumericCode(bytes.at(i + 1));
+        final int code2 = getAlphanumericCode(bytes.at(i + 1));
         if (code2 == -1) {
-          return false;
+          throw new WriterException();
         }
         // Encode two alphanumeric letters in 11 bits.
-        bits.AppendBits(code1 * 45 + code2, 11);
+        bits.appendBits(code1 * 45 + code2, 11);
         i += 2;
       } else {
         // Encode one alphanumeric letter in six bits.
-        bits.AppendBits(code1, 6);
+        bits.appendBits(code1, 6);
         ++i;
       }
     }
-    return true;
   }
 
   // Append "bytes" to "bits" using QRCode.MODE_8BIT_BYTE mode. On success, store the result in
-  // "bits" and return true. On error, return false.
-  static boolean Append8BitBytes(final ByteArray bytes, BitVector bits) {
+  // "bits" and return true.
+  static void append8BitBytes(final ByteArray bytes, BitVector bits) {
     for (int i = 0; i < bytes.size(); ++i) {
-      bits.AppendBits(bytes.at(i), 8);
+      bits.appendBits(bytes.at(i), 8);
     }
-    return true;
   }
 
   // Append "bytes" to "bits" using QRCode.MODE_KANJI mode. On success, store the result in "bits"
-  // and return true. On error, return false. See 8.4.5 of JISX0510:2004 (p.21) for how to encode
+  // and return true. See 8.4.5 of JISX0510:2004 (p.21) for how to encode
   // Kanji bytes.
-  static boolean AppendKanjiBytes(final ByteArray bytes, BitVector bits) {
+  static void appendKanjiBytes(final ByteArray bytes, BitVector bits) throws WriterException {
     if (bytes.size() % 2 != 0) {
-      // JAVAPORT: Our log implementation throws, which causes the unit test to fail.
-      //Debug.LOG_ERROR("Invalid byte sequence: " + bytes);
-      return false;
+      throw new WriterException("Number of bytes must be even");
     }
     for (int i = 0; i < bytes.size(); i += 2) {
-      Debug.DCHECK(IsValidKanji(bytes.at(i), bytes.at(i + 1)));
+      if (!isValidKanji(bytes.at(i), bytes.at(i + 1))) {
+        throw new WriterException("Invalid Kanji at " + i);
+      }
       final int code = (bytes.at(i) << 8) | bytes.at(i + 1);
       int subtracted = -1;
       if (code >= 0x8140 && code <= 0x9ffc) {
@@ -589,18 +567,16 @@ public final class Encoder {
         subtracted = code - 0xc140;
       }
       if (subtracted == -1) {
-        Debug.LOG_ERROR("Invalid byte sequence: " + bytes);
-        return false;
+        throw new WriterException("Invalid byte sequence: " + bytes);
       }
       final int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
-      bits.AppendBits(encoded, 13);
+      bits.appendBits(encoded, 13);
     }
-    return true;
   }
 
   // Check if "byte1" and "byte2" can compose a valid Kanji letter (2-byte Shift_JIS letter). The
   // numbers are from http://ja.wikipedia.org/wiki/Shift_JIS.
-  static boolean IsValidKanji(final int byte1, final int byte2) {
+  static boolean isValidKanji(final int byte1, final int byte2) {
     return (byte2 != 0x7f &&
         ((byte1 >= 0x81 && byte1 <= 0x9f &&
             byte2 >= 0x40 && byte2 <= 0xfc) ||
@@ -609,13 +585,13 @@ public final class Encoder {
   }
 
   // Check if "bytes" is a valid Kanji sequence. Used by the unit tests.
-  static boolean IsValidKanjiSequence(final ByteArray bytes) {
+  static boolean isValidKanjiSequence(final ByteArray bytes) {
     if (bytes.size() % 2 != 0) {
       return false;
     }
     int i = 0;
     for (; i < bytes.size(); i += 2) {
-      if (!IsValidKanji(bytes.at(i), bytes.at(i + 1))) {
+      if (!isValidKanji(bytes.at(i), bytes.at(i + 1))) {
         break;
       }
     }