% Barcode Writer in Pure PostScript % https://bwipp.terryburton.co.uk % % vim: set sw=4 sts=4 et: % % Copyright (c) 2004-2026 Terry Burton % % $Id$ % % Permission is hereby granted, free of charge, to any % person obtaining a copy of this software and associated % documentation files (the "Software"), to deal in the % Software without restriction, including without % limitation the rights to use, copy, modify, merge, % publish, distribute, sublicense, and/or sell copies of % the Software, and to permit persons to whom the Software % is furnished to do so, subject to the following % conditions: % % The above copyright notice and this permission notice % shall be included in all copies or substantial portions % of the Software. % % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY % KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO % THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A % PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL % THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, % DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF % CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN % CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS % IN THE SOFTWARE. % --BEGIN ENCODER azteccode-- % --REQUIRES preamble raiseerror setuphooks processoptions parseinput setanycolor fifocache rsecbinary render renmatrix-- % --DESC: Aztec Code % --EXAM: This is Aztec Code % --EXOP: format=full % --RNDR: renmatrix % --FMLY: Two-dimensional symbols currentglobal true setglobal /setpacking where {pop currentpacking true setpacking} if 33 dict dup /raiseerror dup /uk.co.terryburton.bwipp findresource put dup /processoptions dup /uk.co.terryburton.bwipp findresource put dup /parseinput dup /uk.co.terryburton.bwipp findresource put dup /fifocache dup /uk.co.terryburton.bwipp findresource put dup /rsecbinary dup /uk.co.terryburton.bwipp findresource put dup /setuphooks dup /uk.co.terryburton.bwipp findresource put dup /renmatrix dup /uk.co.terryburton.bwipp findresource put dup /render dup /uk.co.terryburton.bwipp findresource put begin /azteccode [/before /after] //setuphooks exec (setup.define) //azteccode.before exec % % State key: "U"pper, "L"ower, "M"ixed, "P"unctuation, "D"igit, "B"inary % /azteccode.u 0 def /azteccode.l 1 def /azteccode.m 2 def /azteccode.p 3 def /azteccode.d 4 def /azteccode.b 5 def % % Special function characters % /azteccode.lu -2 def /azteccode.ll -3 def /azteccode.lm -4 def /azteccode.lp -5 def /azteccode.ld -6 def /azteccode.su -7 def /azteccode.sp -8 def /azteccode.sb -9 def /azteccode.fl -10 def /azteccode.p2 -11 def /azteccode.p3 -12 def /azteccode.p4 -13 def /azteccode.p5 -14 def /lu azteccode.lu def /ll azteccode.ll def /lm azteccode.lm def /lp azteccode.lp def /ld azteccode.ld def /su azteccode.su def /sp azteccode.sp def /sb azteccode.sb def /fl azteccode.fl def /p2 azteccode.p2 def /p3 azteccode.p3 def /p4 azteccode.p4 def /p5 azteccode.p5 def % % Character maps for each state % /azteccode.charmaps [ % U L M P D [ sp sp sp fl sp ] % 0 [ 32 32 32 13 32 ] % 1 [ (A) (a) 1 p2 (0) ] % 2 p2 = CR LF [ (B) (b) 2 p3 (1) ] % 3 p3 = ". " [ (C) (c) 3 p4 (2) ] % 4 p4 = ", " [ (D) (d) 4 p5 (3) ] % 5 p5 = ": " [ (E) (e) 5 (!) (4) ] % 6 [ (F) (f) 6 (") (5) ] % 7 [ (G) (g) 7 (#) (6) ] % 8 [ (H) (h) 8 ($) (7) ] % 9 [ (I) (i) 9 (%) (8) ] % 10 [ (J) (j) 10 (&) (9) ] % 11 [ (K) (k) 11 (') (,) ] % 12 [ (L) (l) 12 40 (.) ] % 13 [ (M) (m) 13 41 lu ] % 14 [ (N) (n) 27 (*) su ] % 15 [ (O) (o) 28 (+) -99 ] % 16 [ (P) (p) 29 (,) -99 ] % 17 [ (Q) (q) 30 (-) -99 ] % 18 [ (R) (r) 31 (.) -99 ] % 19 [ (S) (s) (@) (/) -99 ] % 20 [ (T) (t) 92 (:) -99 ] % 21 [ (U) (u) (^) (;) -99 ] % 22 [ (V) (v) (_) (<) -99 ] % 23 [ (W) (w) (`) (=) -99 ] % 24 [ (X) (x) (|) (>) -99 ] % 25 [ (Y) (y) (~) (?) -99 ] % 26 [ (Z) (z) 127 ([) -99 ] % 27 [ ll su ll (]) -99 ] % 28 [ lm lm lu ({) -99 ] % 29 [ ld ld lp (}) -99 ] % 30 [ sb sb sb lu -99 ] % 31 ] readonly def % % Punctuation compression % /azteccode.pcomp << <0d0a> p2 % CR LF (. ) p3 (, ) p4 (: ) p5 >> readonly def % % Punctuation compression pairs keyed by leading character code, giving % the trailing character code and the pair token % /azteccode.pcompnum << //azteccode.pcomp { exch dup length string cvs % Dict keys are names; convert back dup 0 get 3 1 roll 1 get exch 2 array astore } forall >> readonly def % % Bit length of latch between states % /azteccode.latlen [ % To: U L M P D B From [ 0 5 5 10 5 10 ] % U [ 9 0 5 10 5 10 ] % L [ 5 5 0 5 10 10 ] % M [ 5 10 10 0 10 15 ] % P [ 4 9 9 14 0 14 ] % D [ 0 0 0 0 0 0 ] % B ] readonly def % % Latch sequences between states % /azteccode.latseq [ % To: U L M P D B From [ [] [ll] [lm] [lm lp] [ld] [sb] ] % U [ [ld lu] [] [lm] [lm lp] [ld] [sb] ] % L [ [lu] [ll] [] [lp] [lu ld] [sb] ] % M [ [lu] [lu ll] [lu lm] [] [lu ld] [lu sb] ] % P [ [lu] [lu ll] [lu lm] [lu lm lp] [] [lu sb] ] % D [ [lu] [ll] [lm] [] [] [] ] % B ] readonly def /azteccode.e 1000000 def % "Empty" /e azteccode.e def % % Bit length of shift to state % /azteccode.shftlen [ % To: U L M P D From [ e e e 5 e ] % U [ 5 e e 5 e ] % L [ e e e 5 e ] % M [ e e e e e ] % P [ 4 e e 4 e ] % D ] readonly def /azteccode.metrics [ [ (rune) 0 0 0 6 ] % Special metric for rune symbols [ (compact) 1 1 17 6 ] [ (full) 1 1 21 6 ] [ (compact) 2 0 40 6 ] [ (full) 2 1 48 6 ] [ (compact) 3 0 51 8 ] [ (full) 3 1 60 8 ] [ (compact) 4 0 76 8 ] [ (full) 4 1 88 8 ] [ (full) 5 1 120 8 ] [ (full) 6 1 156 8 ] [ (full) 7 1 196 8 ] [ (full) 8 1 240 8 ] [ (full) 9 1 230 10 ] [ (full) 10 1 272 10 ] [ (full) 11 1 316 10 ] [ (full) 12 1 364 10 ] [ (full) 13 1 416 10 ] [ (full) 14 1 470 10 ] [ (full) 15 1 528 10 ] [ (full) 16 1 588 10 ] [ (full) 17 1 652 10 ] [ (full) 18 1 720 10 ] [ (full) 19 1 790 10 ] [ (full) 20 1 864 10 ] [ (full) 21 1 940 10 ] [ (full) 22 1 1020 10 ] [ (full) 23 0 920 12 ] [ (full) 24 0 992 12 ] [ (full) 25 0 1066 12 ] [ (full) 26 0 1144 12 ] [ (full) 27 0 1224 12 ] [ (full) 28 0 1306 12 ] [ (full) 29 0 1392 12 ] [ (full) 30 0 1480 12 ] [ (full) 31 0 1570 12 ] [ (full) 32 0 1664 12 ] ] readonly def /azteccode.rsparams [ [] [] [] [] [ 16 19 ] % 4-bit codewords for mode message [] [ 64 67 ] % 6-bit codewords [] [ 256 301 ] % 8-bit codewords [] [ 1024 1033 ] % 10-bit codewords [] [ 4096 4201 ] % 12-bit codewords ] readonly def /azteccode.modemapfull [ [-5 7] [-4 7] [-3 7] [-2 7] [-1 7] [ 1 7] [ 2 7] [ 3 7] [ 4 7] [ 5 7] [ 7 5] [ 7 4] [ 7 3] [ 7 2] [ 7 1] [ 7 -1] [ 7 -2] [ 7 -3] [ 7 -4] [ 7 -5] [ 5 -7] [ 4 -7] [ 3 -7] [ 2 -7] [ 1 -7] [-1 -7] [-2 -7] [-3 -7] [-4 -7] [-5 -7] [-7 -5] [-7 -4] [-7 -3] [-7 -2] [-7 -1] [-7 1] [-7 2] [-7 3] [-7 4] [-7 5] ] readonly def /azteccode.modemapcompact [ [-3 5] [-2 5] [-1 5] [ 0 5] [ 1 5] [ 2 5] [ 3 5] [ 5 3] [ 5 2] [ 5 1] [ 5 0] [ 5 -1] [ 5 -2] [ 5 -3] [ 3 -5] [ 2 -5] [ 1 -5] [ 0 -5] [-1 -5] [-2 -5] [-3 -5] [-5 -3] [-5 -2] [-5 -1] [-5 0] [-5 1] [-5 2] [-5 3] ] readonly def /azteccode.encfuncs [ /encu /encl /encm /encp /encd ] readonly def /azteccode.states [ //azteccode.u //azteccode.l //azteccode.m //azteccode.p //azteccode.d //azteccode.b ] readonly def /azteccode.statesnotb //azteccode.states 0 5 getinterval readonly def /azteccode.statesbackto //azteccode.states 0 3 getinterval readonly def % backto is only ever U, L or M /azteccode.charsizes [ 5 5 5 5 4 8 ] readonly def % % FIFO cache for ECC polynomials % % 2901 unique keys (5 GFs, single-block up to 1663 coeffs); memory-bounded % /azteccode.coeffscachemax 551 def % Override with global_ctx.azteccode.coeffscachemax /azteccode.coeffscachelimit 6000 def % Override with global_ctx.azteccode.coeffscachelimit /uk.co.terryburton.bwipp.global_ctx dup where { exch get dup /azteccode.coeffscachemax 2 copy known {get /azteccode.coeffscachemax exch def} {pop pop} ifelse /azteccode.coeffscachelimit 2 copy known {get /azteccode.coeffscachelimit exch def} {pop pop} ifelse } {pop} ifelse /azteccode.gencoeffs { /coeffs [ 1 rsnc {0} repeat ] def 1 1 rsnc { % i coeffs 1 index 2 copy 1 sub get put % coeffs[i] = coeffs[i-1] dup 1 sub -1 1 { % for j in i-1 -> 1 coeffs exch 2 copy get % ... coeffs j coeffs[j] rslog exch get 3 index add % ... log(coeffs[j]) + i rsalog exch get % p = coeffs[j] * ai coeffs 2 index 1 sub get % ... coeffs[j-1] xor put % coeffs[j] = p ^ coeffs[j-1] } for coeffs 0 2 copy get % ... coeffs 0 coeffs[0] rslog exch get 3 index add % ... log(coeffs[0]) + i rsalog exch get put % coeffs[0] = coeffs[0] * ai pop % i } for % % Deliver the coefficients reversed and in the log domain, with -1 % denoting a zero coefficient, as rsecbinary requires % [ rsnc 1 sub -1 0 { coeffs exch get dup 0 ne { rslog exch get } { pop -1 } ifelse } for ] readonly } bind def /azteccode.coeffscache azteccode.coeffscachemax azteccode.coeffscachelimit //fifocache exec def /azteccode.coeffscachefetch { 100000 mul add % key = rsbt * 100000 + rsnc { //azteccode.gencoeffs exec } { length } //azteccode.coeffscache /fetch get exec } bind def /azteccode.latevars dup 8 dict def load /init { (setup.latevars) //azteccode.before exec currentglobal true setglobal //azteccode.latevars begin % % Invert charmaps to give character to value maps for each state % /charvals [ 32 dict 32 dict 32 dict 32 dict 16 dict ] def 0 1 //azteccode.charmaps length 1 sub { /i exch def /encs //azteccode.charmaps i get def 0 1 4 { /j exch def encs j get dup type /stringtype eq {0 get} if % convert string to ASCII if required charvals j get exch i put } for } for /charvals charvals readonly def % % Calculate the log and anti-log tables for each GF, the anti-log % tables spanning two periods so that log-sums resolve without a % modulo reduction % /rstables [ //azteccode.rsparams { dup length 0 ne { aload pop /rspm exch def /rsgf exch def /rsalog [ 1 rsgf 2 mul 2 sub { dup 2 mul dup rsgf ge {rspm xor} if } repeat ] def /rslog rsgf array def 1 1 rsgf 1 sub {dup rsalog exch get exch rslog 3 1 roll put} for [ rslog rsalog ] } { pop [] } ifelse } forall ] readonly def % % Latch sequences for resuming from Binary, indexed by backto then by % target state: the free in-band return marker to backto followed by % the re-latch from backto to the target, at cost latlen[backto][target] % /bexitseq [ //azteccode.statesbackto { /bt exch def [ //azteccode.states { /y exch def [ //azteccode.latseq //azteccode.b get bt get aload pop //azteccode.latseq bt get y get aload pop ] } forall ] } forall ] readonly def % % For each pair token: the raw character pair and the state, if any, % that encodes both characters natively. P never qualifies since its % charset has neither trailing character (SP, LF); it uses the pair % codeword itself. % /pairdata //azteccode.pcomp length dict def //azteccode.pcomp { /psent exch def /pstr exch dup length string cvs def % Dict keys are names; convert back /praw [ pstr 0 get pstr 1 get ] def /pnative -1 def //azteccode.statesnotb { /pst exch def charvals pst get pstr 0 get known charvals pst get pstr 1 get known and { /pnative pst def } if } forall pairdata psent [ praw pnative ] put } forall /pairdata pairdata readonly def /init { //azteccode.latevars {def} forall } def end //azteccode.latevars /init get exec setglobal (setup.latevars) //azteccode.after exec } bind put /uk.co.terryburton.bwipp.global_ctx dup where { exch get /preload known {//azteccode.latevars /init get exec} if } {pop} ifelse /azteccode { 135 dict begin { (input.processoptions) //azteccode.before exec /dontdraw false def /format (full) def % full, compact or rune /readerinit false def /layers -1 def /eclevel 23 def /ecaddchars 3 def /raw false def /parse false def /parsefnc false def /sampos -1 def /samtotal -1 def /samid () def /strictspec false def /propspec false def /loosespec false def /mag 1.0 def /xdim -1.0 def /ast (default) def /xnom -1.0 def /xmin -1.0 def /xmax -1.0 def {null /apply //processoptions exec} stopped {pop stop} if /options exch def /global_encoder_defaults //render exec /barcode exch def /_render dontdraw /uk.co.terryburton.bwipp.global_ctx dup where {exch get /enabledontdraw known} {pop false} ifelse and /uk.co.terryburton.bwipp._dontdraw dup where {exch get} {pop false} ifelse or not def % Set by aztecmesas, which lays out the codewords of its own symbol sizes /mesa /uk.co.terryburton.bwipp._aztecmesa dup where {exch get} {pop null} ifelse def /modunit 2 def /uk.co.terryburton.bwipp.global_ctx dup where { exch get /default_modunit 2 copy known {get /modunit exch def} {pop pop} ifelse } {pop} ifelse % % Apply AST spec overrides and resolve physical specification % /azteccode ast /apply_ast //render exec not { //raiseerror exec } if /resolve_strictspec //render exec (input.processoptions) //azteccode.after exec //azteccode.latevars /init get exec (input.validate) //azteccode.before exec barcode () eq { /bwipp.aztecEmptyData (The data must not be empty) //raiseerror exec } if barcode length 20000 gt { /bwipp.azteccodeInputTooLong (The input data is too long) //raiseerror exec } if eclevel 5 lt eclevel 95 gt or { /bwipp.aztecInvalidEClevel (The EC percentage must be from 5 to 95) //raiseerror exec } if ecaddchars 3 lt { /bwipp.aztecInvalidECaddChars (The number of additional EC codewords must be 3 or more) //raiseerror exec } if format (full) ne format (compact) ne format (rune) ne and and { /bwipp.aztecInvalidFormat (The format must be either full, compact or rune) //raiseerror exec } if format (full) eq { readerinit layers 1 lt layers 22 gt or and { /bwipp.aztecFullInitInvalidLayers (Full-range symbols for reader programming must specify from 1 to 22 layers) //raiseerror exec } if layers -1 ne layers 1 lt layers 32 gt or and { /bwipp.aztecFullInvalidLayers (Layers for full-range symbols must be from 1 to 32) //raiseerror exec } if } if format (compact) eq { readerinit { layers -1 ne layers 1 ne and { /bwipp.aztecCompactInitInvalidLayers (Compact symbols for reader programming must have 1 layer) //raiseerror exec } if /layers 1 def } if layers -1 ne layers 1 lt layers 4 gt or and { /bwipp.aztecCompactInvalidLayers (Layers for compact symbols must be from 1 to 4) //raiseerror exec } if } if format (rune) eq { layers -1 ne { /bwipp.aztecRuneInvalidLayers (It is not valid to specify layers for runes) //raiseerror exec } if readerinit { /bwipp.aztecRuneReaderInit (Reader initialisation is not compactible with Aztec Runes) //raiseerror exec } if barcode length 0 eq { /bwipp.aztecRuneNotNumeric (Aztec runes must be numeric) //raiseerror exec } if barcode { dup 48 lt exch 57 gt or { /bwipp.aztecRuneNotNumeric (Aztec runes must be numeric) //raiseerror exec } if } forall barcode length 3 gt { /bwipp.aztecRuneInvalid (Aztec runes must be 0 to 255) //raiseerror exec } if barcode cvi dup 0 lt exch 255 gt or { /bwipp.aztecRuneInvalid (Aztec runes must be 0 to 255) //raiseerror exec } if } if /structapp sampos -1 ne samtotal -1 ne or samid () ne or def structapp { format (rune) eq readerinit or raw or { /bwipp.aztecSAMunavailable (Structured Append is not available for runes, reader initialisation or raw bits) //raiseerror exec } if sampos -1 eq samtotal -1 eq or { /bwipp.aztecSAMincomplete (Structured Append requires sampos and samtotal) //raiseerror exec } if samtotal 2 lt samtotal 26 gt or { /bwipp.aztecBadSAMtotal (The samtotal must be from 2 to 26) //raiseerror exec } if sampos 1 lt sampos samtotal gt or { /bwipp.aztecBadSAMpos (The sampos must be from 1 to samtotal) //raiseerror exec } if samid { 32 eq { /bwipp.aztecBadSAMid (The samid must not contain spaces) //raiseerror exec } if } forall } if (input.validate) //azteccode.after exec % % Parse the input % (input.preprocess) //azteccode.before exec /fn1 -1 def /fna -2 def % FNC1 in second position, after an AIM application indicator /fncvals << /parse parse /parsefnc parsefnc /eci true (FNC1) fn1 (FNC@) fna >> def barcode fncvals //parseinput exec /msg exch def /msglen msg length def % % FNC1 in second position follows an AIM application indicator of one letter or two digits % /fnc1second msglen 0 gt { msg 0 get fna eq } { false } ifelse def fnc1second { /appindlen msg 1 get dup 48 ge exch 57 le and { 2 } { 1 } ifelse def /msg [ msg 1 appindlen getinterval aload pop fn1 msg appindlen 1 add msglen appindlen sub 1 sub getinterval aload pop ] def } if parsefnc { % Function characters only come from parsefnc msg { fna eq { /bwipp.azteccodeFNC1secondNotFirst (FNC1 in second position must be declared at the start of the data) //raiseerror exec } if } forall } if % % ECIs are not available with FNC1 in second position, or in first position including after leading ECIs % fnc1second msg { % Skip leading ECIs dup -1000000 gt { fn1 eq or exit } if pop } forall { msg { -1000000 le { /bwipp.azteccodeECIwithFNC1 (ECIs are not available with FNC1 in first or second position) //raiseerror exec } if } forall } if % Absolute capacity is 32-layer full at eclevel=5 ecaddchars=3, numeric. msglen 4729 gt { /bwipp.azteccodeInputTooLong (The input data is too long) //raiseerror exec } if (input.preprocess) //azteccode.after exec % % Convert from input into message bitstream % (input.encoding) //azteccode.before exec /msgbits () def format (rune) ne raw and { barcode { dup 48 ne exch 49 ne and { /bwipp.aztecBadRawBits (Raw data must contain only the bits 0 and 1) //raiseerror exec } if } forall /msgbits barcode def } if format (rune) ne raw not and { % % Structured Append header data, which follows the M/L U/L flag: the message ID between spaces, if any, then the position and total as letters % structapp { /msg [ samid () ne { 32 samid {} forall 32 } if sampos 64 add samtotal 64 add msg aload pop ] def /msglen msg length def } if /charsize { dup 0 ge { pop //azteccode.charsizes exch get } { % FNC or ECI in P exch pop dup fn1 eq { % FNC1: PS{Flg(0)} + 3 pop 8 } { % ECI: PS{Flg(n)} + 3 + 4n neg 1000000 sub dup 0 eq {pop 1} if ln 10 ln div cvi 1 add 4 mul 8 add } ifelse } ifelse } def /e //azteccode.e def % % Merge punctuation pairs into single pair tokens. The leading and % trailing character sets are disjoint, so pairs cannot overlap and % greedy merging with the previously emitted token is safe. % mark msg { % ... prev ch dup 32 eq 1 index 10 eq or { % Only SP or LF completes a pair counttomark 2 ge { 1 index % ... prev ch prev //azteccode.pcompnum 1 index known { //azteccode.pcompnum exch get % ... prev ch [trail token] dup 0 get 2 index eq { 1 get 3 1 roll pop pop % ... token } { pop } ifelse } { pop } ifelse } if } if } forall counttomark array astore /msg exch def pop /msglen msg length def % % Codeword sequences are held as persistent chains of segments. Each % chain head is null or a node [parent_node, segment_array]; the final % sequence is materialised once by walking the chain. For the B-mode % run-length check we keep a counter rather than rescan the chain. % /curseqhd [ //azteccode.states length { null } repeat ] def /nxtseqhd [ //azteccode.states length { null } repeat ] def /curseqlen [ //azteccode.states length { 0 } repeat ] def /nxtseqlen [ //azteccode.states length { 0 } repeat ] def /curseqbb 0 def /nxtseqbb 0 def % U L M P D B /curlen [ 0 e e e e e ] def /backto //azteccode.u def % % Flatten a chain of [parent, segment] cons cells of total length L % into a fresh array. The chain's deepest node holds the prefix, so % we walk head-to-root and write each segment into the tail of the % output, advancing pos backwards. % /flatten { % hd len -> array dup array 3 1 roll % pos = len; out = array(len) { % out hd pos 1 index null eq { exit } if % done when hd is null 1 index 1 get % ... seg = hd[1] exch 1 index length sub % ... pos -= length(seg) 3 index 1 index 3 index putinterval % out[pos..] = seg exch pop % drop seg exch 0 get exch % hd = hd[0] } loop pop pop % return out } def % % Adopt an improved latch path x -> y found during relaxation % /relaximprove { % x y cost -> -- /cost exch def /y exch def /x exch def curlen y cost put /latyseg //azteccode.latseq x get y get def curseqhd y latyseg length 0 eq { curseqhd x get } { [ curseqhd x get latyseg ] } ifelse put curseqlen y curseqlen x get latyseg length add put y //azteccode.b eq { % Recompute B-chain byte-count: latseg may contain sb /nb 0 def latyseg { //azteccode.sb eq {0} {nb 1 add} ifelse /nb exch def } forall /curseqbb nb def /backto x //azteccode.p eq x //azteccode.d eq or {//azteccode.u} {x} ifelse def } if } def % % Adopt an improved resumption of the B chain, re-latching from % backto to y. Re-entering B never improves on staying in B, so y % is never B here and backto and the byte-run count are unchanged. % /bexitimprove { % y cost -> -- /cost exch def /y exch def curlen y cost put /latyseg bexitseqbt y get def curseqhd y [ curseqhd //azteccode.b get latyseg ] put curseqlen y curseqlen //azteccode.b get latyseg length add put } def msg { /char exch def % Let each state adopt a cheaper chain from another state by % latching, in a single pass: the latlen/latseq tables are % transitively closed and passing through B never improves a % chain, so one hop from each non-B state reaches every target % optimally. The B chain resumes at backto for free and % re-latches from there, also in one hop, via the composite % bexitseq sequences. //azteccode.statesnotb { /x exch def /costx curlen x get def /latrowx //azteccode.latlen x get def //azteccode.states { % y latrowx 1 index get costx add % y cost dup curlen 3 index get lt { x 3 1 roll relaximprove } { pop pop } ifelse } forall } forall /costb curlen //azteccode.b get def /latrowbt //azteccode.latlen backto get def /bexitseqbt bexitseq backto get def //azteccode.states { % y latrowbt 1 index get costb add % y cost dup curlen 3 index get lt { bexitimprove } { pop pop } ifelse } forall % U L M P D B /nxtlen [ e e e e e e ] def //azteccode.states { nxtseqhd exch null put } forall //azteccode.states { nxtseqlen exch 0 put } forall /nxtseqbb 0 def char //azteccode.p2 le char //azteccode.p5 ge and { % % Append a pair token to each state as the cheapest of: a % single codeword in P (reached by latching, which % relaxation has already offered, or by shifting); the two % characters natively in M (CR LF) or D (". " and ", "); % or two bytes extending a B run % pairdata char get aload pop /pnative exch def /praw exch def % Pair codeword in P /cost curlen //azteccode.p get 5 add def cost nxtlen //azteccode.p get lt { nxtlen //azteccode.p cost put nxtseqhd //azteccode.p [ curseqhd //azteccode.p get [ char ] ] put nxtseqlen //azteccode.p curseqlen //azteccode.p get 1 add put } if % Native character pair pnative -1 ne { /cost curlen pnative get //azteccode.charsizes pnative get dup add add def cost nxtlen pnative get lt { nxtlen pnative cost put nxtseqhd pnative [ curseqhd pnative get praw ] put nxtseqlen pnative curseqlen pnative get 2 add put } if } if % Shifted pair codeword, remaining in the shifting state //azteccode.statesnotb { /y exch def /cost curlen y get //azteccode.shftlen y get //azteccode.p get add 5 add def cost nxtlen y get lt { nxtlen y cost put nxtseqhd y [ curseqhd y get [ //azteccode.sp char ] ] put nxtseqlen y curseqlen y get 2 add put } if } forall % Byte pair /cost curlen //azteccode.b get //azteccode.charsizes //azteccode.b get dup add add def cost nxtlen //azteccode.b get lt { nxtlen //azteccode.b cost put nxtseqhd //azteccode.b [ curseqhd //azteccode.b get praw ] put nxtseqlen //azteccode.b curseqlen //azteccode.b get 2 add put /nxtseqbb curseqbb 2 add def } if } { //azteccode.states { /x exch def { % loop for common exit % % Skip states that cannot encode character % char 0 ge { x //azteccode.b ne {charvals x get char known not {exit} if} if } { x //azteccode.p ne {exit} if % Only P can encode FNC1 and ECI } ifelse % Append the character in state x: nxtseq[x] := curseq[x] + [char] /csize x char charsize def /cost curlen x get csize add def cost nxtlen x get lt { nxtlen x cost put nxtseqhd x [ curseqhd x get [ char ] ] put nxtseqlen x curseqlen x get 1 add put x //azteccode.b eq { /nxtseqbb curseqbb 1 add def } if } if x //azteccode.b eq {exit} if % B is treated as a latch % Append the character by shifting y -> x (y != x, y != B; stays in y) //azteccode.states { % y dup //azteccode.b eq {pop exit} if dup x eq { pop } { curlen 1 index get //azteccode.shftlen 2 index get x get add csize add % y cost dup nxtlen 3 index get lt { /cost exch def /y exch def nxtlen y cost put nxtseqhd y [ curseqhd y get [ x //azteccode.u eq {//azteccode.su} {//azteccode.sp} ifelse char ] ] put nxtseqlen y curseqlen y get 2 add put } { pop pop } ifelse } ifelse } forall exit } loop } forall } ifelse % Charge the extended-length overhead when a B run grows past % 31 bytes (the 11-bit length field, crossed stepping by one % character or by a byte pair) nxtseqbb 32 eq nxtseqbb 33 eq curseqbb 31 eq and or { nxtlen //azteccode.b 2 copy get 11 add put } if /curlen nxtlen def curseqhd nxtseqhd /curseqhd exch def /nxtseqhd exch def curseqlen nxtseqlen /curseqlen exch def /nxtseqlen exch def /curseqbb nxtseqbb def } forall % % Select the optimal sequence % /minseq //azteccode.e def /bestst -1 def //azteccode.states { /i exch def curlen i get minseq lt { /minseq curlen i get def /bestst i def } if } forall bestst -1 ne { /seq curseqhd bestst get curseqlen bestst get flatten def } if % % Encoding functions % /tobin { string dup length 1 sub 0 exch 1 exch {1 index exch 48 put} for dup 3 -1 roll 2 2 index length string cvrs dup length 2 index length exch sub exch putinterval } def /encu {charvals //azteccode.u get exch get 5 tobin} def /encl {charvals //azteccode.l get exch get 5 tobin} def /encm {charvals //azteccode.m get exch get 5 tobin} def /encd {charvals //azteccode.d get exch get 4 tobin} def /encp { dup fn1 eq { % FNC1: Flg(0) pop (00000000) } { dup -1000000 le { % ECI: Flg(n) + n-Digits neg 1000000 sub dup dup 0 eq {pop 1} if ln 10 ln div cvi dup 1 add 4 mul 8 add string dup 0 (00000) putinterval % Flg(n) dup 2 index 1 add 3 tobin 5 exch putinterval % len 3 1 roll -1 0 { % ECI digits in "Digit" encoding 4 mul 8 add exch dup 10 idiv 3 index 4 2 roll 10 mod 2 add 4 tobin putinterval } for pop } { charvals //azteccode.p get exch get 5 tobin } ifelse } ifelse } def /addtomsgbits { /v exch def j v length add msgbits length gt { /bwipp.aztecNoValidSymbol (Maximum length exceeded) //raiseerror exec } if msgbits j v putinterval /j j v length add def } def % % Encode the sequence % /state //azteccode.u def minseq { string } stopped { pop /bwipp.azteccodeInputTooLarge (The input data exceeds the implementation limits) //raiseerror exec } if /msgbits exch def /i 0 def /j 0 def { i seq length ge {exit} if state //azteccode.b ne { /char seq i get def % Encode character char //azteccode.encfuncs state get load exec addtomsgbits /i i 1 add def % Encode shifted next character char //azteccode.su eq char //azteccode.sp eq or { seq i get char //azteccode.su eq {encu} {encp} ifelse addtomsgbits /i i 1 add def } if % Latches to new state char //azteccode.lu eq {/state //azteccode.u def} if char //azteccode.ll eq {/state //azteccode.l def} if char //azteccode.lm eq {/state //azteccode.m def} if char //azteccode.lp eq {/state //azteccode.p def} if char //azteccode.ld eq {/state //azteccode.d def} if char //azteccode.sb eq {/state //azteccode.b def} if } { % Binary % Find number of bytes before latch or end, capped at 2078 /numbytes 0 def { i numbytes add seq length ge {exit} if seq i numbytes add get 0 lt {exit} if numbytes 2078 eq {exit} if % 11-bit length field maximum /numbytes numbytes 1 add def } loop % Encode length numbytes 31 le { numbytes 5 tobin addtomsgbits } { 0 5 tobin addtomsgbits numbytes 31 sub 11 tobin addtomsgbits } ifelse % Encode bytes numbytes { seq i get 8 tobin addtomsgbits /i i 1 add def } repeat % Return to previous state as indicated i seq length lt { /char seq i get def /i i 1 add def char //azteccode.lu eq {/state //azteccode.u def} if char //azteccode.ll eq {/state //azteccode.l def} if char //azteccode.lm eq {/state //azteccode.m def} if } if } ifelse } loop /msgbits msgbits 0 j getinterval def structapp { % Flag: M/L U/L from the initial Upper state /msgbits msgbits length 10 add string dup 0 (1110111101) putinterval dup 10 msgbits putinterval def } if } if options /debugbits known /uk.co.terryburton.bwipp.global_ctx dup where {exch get /enabledebug known} {pop false} ifelse and { /bwipp.debugbits msgbits //raiseerror exec } if % % Expand message bits into codewords of bpcw bits avoiding codewords with all zeros or all ones % /allzero {dup length (000000000000) 0 3 -1 roll getinterval eq} def /allones {dup length (111111111111) 0 3 -1 roll getinterval eq} def /tocws { /cws msgbits length bpcw 1 sub idiv 1 add array def % Each codeword takes at least bpcw-1 bits /m 0 def /c 0 def { msgbits length m le {exit} if msgbits length m sub bpcw ge { /cwb msgbits m bpcw 1 sub getinterval def % All but last bit /cwf msgbits m bpcw add 1 sub 1 getinterval def % Last bit cwb allzero {/cwf (1) def /m m 1 sub def} if % Flip last bit to avoid zeros cwb allones {/cwf (0) def /m m 1 sub def} if % Flip last bit to avoid ones % Concatenate the bits 12 string dup 0 cwb putinterval dup bpcw 1 sub cwf putinterval 0 bpcw getinterval /cwb exch def } { % Final codeword /cwb msgbits m msgbits length m sub getinterval def /cwb (111111111111) 12 string copy dup 0 cwb putinterval 0 bpcw getinterval def cwb allones {cwb cwb length 1 sub (0) putinterval} if % Prevent all ones } ifelse % Conversion of binary data into byte array /cw 0 def 0 1 bpcw 1 sub { /i exch def /cw cw 2 bpcw i sub 1 sub exp cvi cwb i get 48 sub mul add def } for cws c cw put /m m bpcw add def /c c 1 add def } loop cws 0 c getinterval } def % % Lookup the most appropriate symbol specification % /stuffedbpcw -1 def mesa null eq {//azteccode.metrics} {mesa /metrics get} ifelse { /m exch def /frmt m 0 get def % Format of the symbol /mlyr m 1 get def % Data layers /icap m 2 get def % Reader initialisation capable /ncws m 3 get def % Total of codewords /bpcw m 4 get def % Bits per codeword /numecw ncws eclevel mul 100 div ecaddchars add ceiling cvi def msgbits length 0 eq {/numecw 0 def} if % Error correction codewords /numdcw ncws numecw sub def % Data codewords frmt (compact) eq numdcw 64 gt and {/numdcw 64 def} if % Compact mode message counts at most 64 mesa null ne { numdcw mesa /maxdcw get gt { /numdcw mesa /maxdcw get def } if } if % The Mesa Mode Message counts at most maxdcw /okay true def format frmt ne {/okay false def} if readerinit icap 1 ne and {/okay false def} if layers -1 ne layers mlyr ne and {/okay false def} if msgbits length bpcw div ceiling cvi numdcw gt {/okay false def} if okay { % Bit stuffing may add codewords stuffedbpcw bpcw ne {/stuffed tocws def /stuffedbpcw bpcw def} if stuffed length numdcw gt {/okay false def} if } if okay {exit} if } forall okay not { /bwipp.aztecNoValidSymbol (Maximum length exceeded) //raiseerror exec } if /layers mlyr def /cws stuffed def % % Report the choices in the form of the options that select them; a Mesa takes no format % mesa null eq { /format format dup length string copy /report //render exec } if format (rune) ne { /layers layers /report //render exec } if options /debugcws known /uk.co.terryburton.bwipp.global_ctx dup where {exch get /enabledebug known} {pop false} ifelse and { /bwipp.debugcws cws //raiseerror exec } if (input.encoding) //azteccode.after exec % % Reed-Solomon algorithm. Returns rsnc ECC codewords. The GF parameters % vary with rsbt, so they are bound per call. % /rscodes { (ecc.cws) //azteccode.before exec /rsbt exch def /rsnc exch def /rscws exch def % % Lookup the Reed Solomon log tables for the codeword size % rstables rsbt get aload pop /rsalog exch def /rslog exch def (ecc.coeffs) //azteccode.before exec /coeffs rsnc rsbt //azteccode.coeffscachefetch exec def (ecc.coeffs) //azteccode.after exec /lfsr rsnc array def {rscws exch get} rscws length coeffs lfsr rslog rsalog //rsecbinary exec lfsr (ecc.cws) //azteccode.after exec } def % % Create the codewords and bit string for the mode % format (full) eq { /mode layers 1 sub 11 bitshift cws length 1 sub add def readerinit {/mode mode 2#0000010000000000 or def} if mesa null ne {/mode mode mesa /modeflags get or def} if /mode [ mode 2#1111000000000000 and -12 bitshift mode 2#0000111100000000 and -8 bitshift mode 2#0000000011110000 and -4 bitshift mode 2#0000000000001111 and ] def /mode [ mode aload pop mode 6 4 rscodes aload pop ] def } if format (compact) eq { /mode layers 1 sub 6 bitshift cws length 1 sub add def readerinit {/mode mode 2#00100000 or def} if /mode [ mode 2#11110000 and -4 bitshift mode 2#00001111 and ] def /mode [ mode aload pop mode 5 4 rscodes aload pop ] def } if format (rune) eq { /mode barcode cvi def /mode [ mode 2#11110000 and -4 bitshift mode 2#00001111 and ] def /mode [ mode aload pop mode 5 4 rscodes aload pop ] def /mode [mode {2#1010 xor} forall] def % Invert alternate bits } if /modebits mode length 4 mul string def 0 1 modebits length 1 sub {modebits exch (0) putinterval} for 0 1 mode length 1 sub { /i exch def modebits mode i get 2 4 string cvrs dup length 4 exch sub 4 i mul add exch putinterval } for % % Extend the data codewords with error correction codewords to create the bit string for the data % /ecws cws ncws cws length sub bpcw rscodes def options /debugecc known /uk.co.terryburton.bwipp.global_ctx dup where {exch get /enabledebug known} {pop false} ifelse and { /bwipp.debugecc ecws //raiseerror exec } if /cws [ cws aload pop ecws aload pop ] def mesa null ne { << /layers layers /bpcw bpcw /cws cws /modebits modebits >> } { format (full) eq { /databits layers layers mul 16 mul layers 112 mul add string def } { /databits layers layers mul 16 mul layers 88 mul add string def } ifelse 0 1 databits length 1 sub {databits exch (0) putinterval} for 0 1 ncws 1 sub { /i exch def databits cws i get 2 bpcw string cvrs dup length bpcw exch sub bpcw i mul add databits length ncws bpcw mul sub add exch putinterval } for (matrix.layout) //azteccode.before exec % % Move to a point in the cartesian plane centered on the bullseye % /cmv {size mul sub mid add} def % % Move to a bit position within a layer % /lmv { /lbit exch def /llyr exch def /lwid fw llyr 4 mul add def /ldir lbit 2 idiv lwid idiv def ldir 0 eq { % Top lwid 1 sub 2 idiv neg 1 add lbit 2 idiv lwid mod add fw 1 sub 2 idiv llyr 2 mul add lbit 2 mod add cmv } if ldir 1 eq { % Right fw 2 idiv llyr 2 mul add lbit 2 mod add lwid 1 sub 2 idiv 1 sub lbit 2 idiv lwid mod sub cmv } if ldir 2 eq { % Bottom lwid 2 idiv neg 1 add lbit 2 idiv lwid mod add neg fw 2 idiv llyr 2 mul add lbit 2 mod add neg cmv } if ldir 3 eq { % Left fw 1 sub 2 idiv llyr 2 mul add lbit 2 mod add neg lwid 2 idiv 1 sub lbit 2 idiv lwid mod sub neg cmv } if } def % % Create the pixel map % % For full symbols we disregard the reference grid at this stage % format (full) eq {/fw 12 def} {/fw 9 def} ifelse /size fw layers 4 mul add 2 add def /pixs [size size mul {-1} repeat] def /mid size 1 sub 2 idiv size mul size 1 sub 2 idiv add def (matrix.layout.data) //azteccode.before exec % % Data layers % /i 0 def 1 1 layers { /layer exch def 0 1 fw layer 4 mul add 8 mul 1 sub { /pos exch def pixs layer pos lmv databits databits length i sub 1 sub get 48 sub put /i i 1 add def } for } for (matrix.layout.data) //azteccode.after exec (matrix.layout.fixtures) //azteccode.before exec % % For full symbols expand the pixel map by inserting the reference grid % format (full) eq { /fw 13 def /size fw layers 4 mul add 2 add layers 10.5 add 7.5 div 1 sub cvi 2 mul add def /mid size size mul 2 idiv def /npixs [size size mul {-2} repeat] def 0 16 size 2 idiv { /i exch def 0 1 size 1 sub { /j exch def npixs size 2 idiv neg j add i cmv [size 2 idiv j add i add 1 add 2 mod] putinterval npixs size 2 idiv neg j add i neg cmv [size 2 idiv j add i add 1 add 2 mod] putinterval npixs i size 2 idiv neg j add cmv [size 2 idiv j add i add 1 add 2 mod] putinterval npixs i neg size 2 idiv neg j add cmv [size 2 idiv j add i add 1 add 2 mod] putinterval } for } for /j 0 def 0 1 npixs length 1 sub { /i exch def npixs i get -2 eq { npixs i pixs j get put /j j 1 add def } if } for /pixs npixs def } if % % Finder pattern % /fw fw 2 idiv def fw neg 1 fw { /i exch def fw neg 1 fw { /j exch def pixs i j cmv i abs j abs gt {i abs} {j abs} ifelse 1 add 2 mod put } for } for % % Orientation bits % [ [ fw 1 add neg fw 1 ] [ fw 1 add neg fw 1 add 1 ] [ fw neg fw 1 add 1 ] [ fw 1 add fw 1 add 1 ] [ fw 1 add fw 1 ] [ fw 1 add fw neg 1 ] [ fw fw 1 add 0 ] [ fw 1 add fw 1 add neg 0 ] [ fw fw 1 add neg 0 ] [ fw neg fw 1 add neg 0 ] [ fw 1 add neg fw 1 add neg 0 ] [ fw 1 add neg fw neg 0 ] ] {pixs exch aload pop 3 1 roll cmv exch put} forall (matrix.layout.fixtures) //azteccode.after exec (matrix.layout.reserve) //azteccode.before exec % % Mode ring % /modemap format (full) eq {//azteccode.modemapfull} {//azteccode.modemapcompact} ifelse def 0 1 modemap length 1 sub { pixs modemap 2 index get aload pop cmv modebits 3 index get 48 sub put pop } for (matrix.layout.reserve) //azteccode.after exec (matrix.layout) //azteccode.after exec << /ren /renmatrix /pixs pixs /pixx size /pixy size /height size modunit mul 72 div /width size modunit mul 72 div /borderleft 0.0 /borderright 0.0 /bordertop 0.0 /borderbottom 0.0 /strictspec strictspec /loosespec loosespec /xdim xdim /xmin xmin /xmax xmax /modunit modunit /opt options >> _render //renmatrix if } ifelse } stopped {end stop} if end } [/barcode] {null def} forall bind def /azteccode dup load executeonly /uk.co.terryburton.bwipp defineresource pop (setup.define) //azteccode.after exec end /setpacking where {pop setpacking} if setglobal % --END ENCODER azteccode--