1package datamatrix
2
3import (
4	"github.com/boombuler/barcode/utils"
5)
6
7type errorCorrection struct {
8	rs *utils.ReedSolomonEncoder
9}
10
11var ec *errorCorrection = newErrorCorrection()
12
13func newErrorCorrection() *errorCorrection {
14	gf := utils.NewGaloisField(301, 256, 1)
15
16	return &errorCorrection{utils.NewReedSolomonEncoder(gf)}
17}
18
19func (ec *errorCorrection) calcECC(data []byte, size *dmCodeSize) []byte {
20	dataSize := len(data)
21	// make some space for error correction codes
22	data = append(data, make([]byte, size.ECCCount)...)
23
24	for block := 0; block < size.BlockCount; block++ {
25		dataCnt := size.DataCodewordsForBlock(block)
26
27		buff := make([]int, dataCnt)
28		// copy the data for the current block to buff
29		j := 0
30		for i := block; i < dataSize; i += size.BlockCount {
31			buff[j] = int(data[i])
32			j++
33		}
34		// calc the error correction codes
35		ecc := ec.rs.Encode(buff, size.ErrorCorrectionCodewordsPerBlock())
36		// and append them to the result
37		j = 0
38		for i := block; i < size.ErrorCorrectionCodewordsPerBlock()*size.BlockCount; i += size.BlockCount {
39			data[dataSize+i] = byte(ecc[j])
40			j++
41		}
42	}
43
44	return data
45}
46