LZW compression: Difference between revisions

m
→‎version 2: changed whitespace and comments, simplified some code.
m (→‎version 2: changed whitespace and comments, simplified some code.)
Line 4,898:
This REXX version can execute on   '''ASCII'''   or   '''EBCDIC'''   systems.
<lang rexx>/*REXX program compresses text using the LZW (Lempel─Ziv─Welch), and reconstitutes it.*/
parse arg x; if x='' then x= , /*get an optional argument from the CL.*/
x= '"There is nothing permanent except change." ─── Heraclitus [540 ── 475 BCE]'
say 'original text=' x /* [↑] Not specified? Then use default*/
cypher= LZWc(x) /*compress text using the LZW algorithm*/
say 'reconstituted=' LZWd(cypher) /*display the reconstituted string. */
say ' LZW integers=' cypher /* " " LZW integers used. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
LZWcLZWi: procedure; parse arg yi,,w $ @.; #=256; do j=0 for #; _=d2c(j); 256if i then @.j=_; else @._=j; end; /*LZW compress algorithm.*/return
do j=0 for #; _= d2c(j); @._= j; end /*j*/
do k=1 for length(y)+1; z= w || substr(y, k, 1)
if @.z=='' then do; $= $ @.w; @.z= #; #= # + 1; w= substr(y, k, 1); end
else w= z /*#: the dictionary size.*/
end /*k*/; return substr($, 2) /*elide a leading blank. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
LZWdLZWc: procedure; parse arg x y,,@.$; call LZWi 0; #w= 256 /*LZW decompress algorithm compress.*/
do k=1 for length(y)+1; do jz=0 w for|| #;substr(y, k, @.j= d2c(j1); end /*j*/
$= if @.x; wz=='' $ then do; $= $ @.w; @.z= #; #= # + 1; w= substr(y, k, 1); /*#: the dictionary size.*/end
else w= z do k=1 for words(y); z= word(y, k) /*#: the dictionary size.*/
end /*k*/; if @.z\=='' | @.k==" " then ?= @ return substr($, 2) /*elide a leading blank.z */
/*──────────────────────────────────────────────────────────────────────────────────────*/
else if z==# then ?= w || left(w, 1)
LZWd: procedure; parse arg x y; call LZWi 1; $= @.x; $w= $ || /*LZW ?decompress.*/
do @.#k=1 w ||for leftwords(?, 1y); w= ?; #z= #word(y, + 1 /*bump dict. size.*/k)
if @.z\=='' | end /*@.k*/; ==" " then return?= $</lang>@.z
else if z==# then ?= w || left(w, 1)
$= $ || ?
@.#= w || left(?, 1); w= ?; #= # + 1 do j=0 for #; _=/*bump d2c(j); @dict._= j; end /*jsize*/
end /*k*/; return substr($, 2) /*elide a leading blank. *</lang>
{{out|output|text=&nbsp; when using the default input:}}
<pre>