! Convert a file from Unix (LF) into DOS (CR,LF) format.
! One file name is read from stdin. Files will be replaced in situ.

interface rename(2) = 14;

convert() do
	var	ibuf[513], obuf[1025];
	var	k, i, j;

	k := reads(ibuf, 512);
	while (k > 0) do
		j := 0;
		for (i=0, k) do
			ie (ibuf[i] = '\n') do
				obuf[j] := '\r';
				obuf[j+1] := '\n';
				j := j+2;
			end
			else do
				if (ibuf[i] = '\r') return 0;
				obuf[j] := ibuf[i];
				j := j+1;
			end
		end
		obuf[j] := 0;
		writes(obuf);
		k := reads(ibuf, 512);
	end
	return 1;
end


error(m) do
	select(1,2);
	writes("CRLF: ");
	writes(m);
	newline();
	halt;
end


do
	var	name[256];
	var	i, fdi, fdo;
	var	converted;

	reads(name, 256);
	for (i=0, 256) if (name[i] = '\n' \/ name[i] = '\r') leave;
	name[i] := 0;
	fdi := open(name, 0);
	if (fdi < 0) error("cannot open input");
	fdo := open("crlf.tmp", 1);
	if (fdo < 0) error("cannot create tmp file");
	writes("converting "); writes(name);
	select(0, fdi);
	select(1, fdo);
	converted := convert();
	close(fdi);
	close(fdo);
	select(1, 1);
	ie (converted) do
		erase(name);
		rename("crlf.tmp", name);
		writes(" - done");
	end
	else do
		erase("crlf.tmp");
		writes(" - already converted");
	end
	newline();
end
