1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day7.input] day7.m4
4 include(`common.m4')ifelse(common(7), `ok', `',
5 `errprint(`Missing common initialization
8 define(`input', translit((include(defn(`file'))), alpha`'nl`,()', ALPHA`;'))
9 define(`line', `_$0(translit(`$1', ` ', `,'))')
10 define(`_line', `pushdef(`prog', `$1')ifelse(`$3', `->', `holds(`$1',
11 shift(shift(shift($@))))')define(`w$1', $2)')
12 define(`holds', `define(`c$1', dquote(shift($@)))_$0($@)')
13 define(`_holds', `ifelse(`$2', `', `', `define(`p$2', `$1')$0(`$1',
16 patsubst(defn(`input'), `\([^;]*\);', `line(`\1')')
18 define(`chew', `line(substr(`$1', 0, index(`$1', `;')))define(`tail',
19 substr(`$1', incr(index(`$1', `;'))))ifelse(index(defn(`tail'), `;'),
20 -1, `', `$0(defn(`tail'))')')
21 define(`split', `ifelse(eval($1 < 155), 1, `chew(`$2')', `$0(eval($1/2),
22 substr(`$2', 0, eval($1/2)))$0(eval(len(defn(`tail')) + $1 - $1/2),
23 defn(`tail')substr(`$2', eval($1/2)))')')
24 split(len(defn(`input')), defn(`input'))
26 define(`lower', `translit(`$1', 'dquote(ALPHA)`, 'dquote(alpha)`)')
27 define(`fix', `define(`part2', eval(w$1 - $2))define(`s$1', eval(s$1 - $2))')
28 define(`balance', `ifdef(`s$1', `', `define(`s$1', ifdef(`c$1',
29 `eval(w$1 + _$0(c$1))', `w$1'))')s$1')
30 define(`_balance', `ifelse(balance(`$1'), balance(`$2'), `ifelse(`$3', `',
31 `s$1 + s$2', `ifelse(s$1, balance(`$3'), `', `fix(`$3', (s$3 - s$1))')s$1 +
32 $0(shift($@))')', `$3', `', `errprintn(`too few children to balance')m4exit(
33 1)', `ifelse(s$1, balance(`$3'), `fix(`$2', (s$2 - s$1))', `fix(`$1',
34 (s$1 - s$2))')s$1 + $0(shift($@))')')
35 define(`check', `ifdef(`p$1', `', `define(`part1',
36 lower(`$1'))balance(`$1')')')
37 _stack_foreach(`prog', `check(', `)', `tmp')