Initial Revision
[ohcount] / test / expected_dir / lua1.lua / lua / code
1 function q_create()
2 local q = {}
3 q.first = 0
4 q.last = 0
5 return q
6 end
7 function q_insert(q, s)
8 q[q.last] = s
9 q.last = q.last + 1
10 end
11 function q_empty(q)
12 return q.first >= q.last
13 end
14 function q_remove(q)
15 if q_empty(q) then
16 return nil
17 end
18 local s = q[q.first]
19 q[q.first] = nil
20 q.first = q.first+1
21 return s
22 end
23 function q_card(q)
24 return q.last - q.first
25 end
26 function q_length(q, f)
27 local l, i = 0, q.first
28 while i < q.last do
29 l = l + strlen(q[i])
30 i = i + 1
31 end
32 return l
33 end
34 function justify(q)
35 local blanks = MAX - q_length(q)
36 local skips = q_card(q) - 1
37 local line = q_remove(q)
38 local quotient = floor(blanks/skips)
39 local reminder = blanks/skips - quotient
40 local error = 0
41 while skips > 0 do
42 error = error + reminder
43 if error >= 0.5 then
44 error = error - 1
45 line = line .. strrep(" ", quotient+1)
46 else
47 line = line .. strrep(" ", quotient)
48 end
49 line = line .. q_remove(q)
50 skips = skips - 1
51 end
52 return line or ""
53 end
54 function catenate(q)
55 local line = q_remove(q)
56 while not q_empty(q) do
57 line = line .. " " .. q_remove(q)
58 end
59 return line or ""
60 end
61 DEFMAX = 72
62 if not arg or getn(arg) < 1 then
63 MAX = DEFMAX
64 else
65 MAX = tonumber(arg[1])
66 if not MAX or MAX < 0 then
67 MAX = DEFMAX
68 end
69 end
70 text = q_create()
71 line = read()
72 while line do
73 _, n = gsub(line, "(%S+)", function (s) q_insert(%text, s) end)
74 if n == 0 then
75 q_insert(text, "\n")
76 end
77 line = read()
78 end
79 line = q_create()
80 word = q_remove(text)
81 size = 0
82 while word do
83 if word == "\n" then
84 if not q_empty(line) then
85 write(catenate(line), "\n\n")
86 else
87 write("\n")
88 end
89 size = 0
90 elseif size + strlen(word) > MAX then
91 write(justify(line), "\n")
92 size = 0
93 end
94 if word ~= "\n" then
95 q_insert(line, word)
96 size = size + strlen(word) + 1
97 end
98 word = q_remove(text)
99 end
100 write(catenate(line), "\n")