!	HD -- Hex Dump
!	Copyright (C) 1995,1998,2000 Nils M Holm
!	See the file LICENSE for conditions of use.

#r5;

interface	readpacked(3) = 11,
		writepacked(3);

word(buf, n) do
	var	digits;

	digits := "0123456789ABCDEF";
	buf::0 := digits[(n>>8) / 16];
	buf::1 := digits[(n>>8) mod 16];
	buf::2 := digits[(n&255) / 16];
	buf::3 := digits[(n&255) mod 16];
end


byte(buf, n) do
	var	digits;

	digits := "0123456789ABCDEF";
	buf::0 := digits[n / 16];
	buf::1 := digits[n mod 16];
end


do
	const	BUFLEN = 1024;
	var	ibuf::BUFLEN, obuf::81;
	var	k, i, j, m, b, ch;
	var	h, l, c;

	h := 0;
	l := 0;
	c := 0;
	while (1) do
		k := readpacked(0, ibuf, BUFLEN);
		if (k < 1) leave;
		for (i=0, k/16+1) do
			for (j=0, 80) obuf::j := '\s';
			word(obuf, h);
			word(@obuf::4, l);
			m := i<k/16 -> 16 : k mod 16;
			if (\m) leave;
			b := 10;
			obuf::60 := '|';
			for (j=0, m) do
				ch := ibuf::(i*16+j);
				byte(@obuf::(b+j*3), ch);
				if (j = 7) b := b+1;
				obuf::(61+j) :=
					('\s' <= ch /\ ch <= '~')-> ch: '.';
			end
			obuf::(61+m) := '|';
			obuf::(62+m) := '\n';
			writepacked(1, obuf, 63+m);
			l := l+16;
			c := c+1;
			if (c >= 4096) do
				h := h+1; l := 0; c := 0;
			end
		end
	end
end

