3 from sys import argv, exit
4 from itertools import cycle, izip
8 exit('usage: split-pieces { scaf WD | qf WD/N|WD,WD,... } N N ...')
11 def getarg(must = True):
13 if ARGC < len(argv): ARGC += 1; return argv[ARGC - 1]
14 elif must: bad_usage()
17 class ScafConvert (object):
18 def __init__(me, piecewd):
20 me.fmt = '0x%%0%dx' % ((piecewd + 3)/4)
21 me.mask = (1 << piecewd) - 1
24 return ScafConvert(int(getarg()))
28 nn.append(me.fmt % (n&me.mask))
32 return sum(n << i*me.piecewd for i, n in enumerate(nn))
34 class QfConvert (object):
35 def __init__(me, p, wdseq):
43 wd, n = map(int, arg.split('/'))
44 seq = [(wd*(i + 1) + n - 1)/n - (wd*i + n - 1)/n for i in xrange(n)]
46 seq = map(int, arg.split(','))
47 print ";; piece widths = %r" % seq
48 return QfConvert(p, seq)
50 if 2*n >= me.p: n -= p
55 lim = 1 << wd; m = lim - 1
57 if d >= lim/2: d -= lim; n += 1
62 for n, w in izip(nn, cycle(me.wdseq)):
68 R_split = RX.compile(r',\s*|\s+')
69 def spliteval(arg): return map(eval, R_split.split(arg.strip()))
71 convmap = { 'scaf': ScafConvert,
72 'unscaf': ScafConvert,
76 cvt = convmap[op].parse()
77 if op.startswith('un'): prepare, conv, format = spliteval, cvt.unhack, str
78 else: prepare, conv, format = eval, cvt.hack, lambda vv: ', '.join(vv)
81 val = getarg(must = False)
83 print format(conv(prepare(val)))