#
/*
 * nc <n_col> [-<linesize>]
 */

/*)BUILD	$(TKBOPTIONS) = {
			TASK	= ...NCX
		}
*/

#ifdef	DOCUMENTATION

title	nc	Multi-column Output
index		Multi-column Output

synopsis


	nc ncol [-linelength]

description

	Nc reads the standard input, writing it to the standard output
	in <ncol> columns.  (<Ncol> should range from 1 to 9.)
	If <ncol> is missing, five columns will be output.  If the
	linelength option is missing, an 80 column line will be assumed.
	Each column is, of course,
	.s
		<linelength>/<ncol>
	.s
	bytes wide.

diagnostics

	None

author

	David Conroy, Martin Minow

bugs
	Why are there two programs to do the same thing?

#endif

#include <stdio.h>
#define LINESZ 80

int ncolumns	= 5;
int linelength	= LINESZ;
int tabstop[10] = { 0,  16, 32, 48, 64, 
		LINESZ };

main(argc,argv)
char **argv;
{
	register int colnum,charnum;

	register char c;

	for (colnum = 1; colnum < argc; colnum++) {
		if (argv[colnum][0] == '-')
			linelength = atoi(&argv[colnum][1]);
		else	ncolumns = atoi(&argv[colnum][0]);
	}
	charnum = linelength/ncolumns;
	for (colnum = 0; colnum < ncolumns; colnum++)
		tabstop[colnum] = colnum * charnum;
	tabstop[colnum] = linelength;

	colnum = 0;
	charnum = 0;
	while ((c=getchar()) != EOF) {
		if (c == '\n') {
			while (++colnum < ncolumns
				&& charnum >= tabstop[colnum]);
			if (colnum >= ncolumns) {
				putchar('\n');
				colnum = charnum = 0;
			} else 
				while(charnum < tabstop[colnum]) {
					charnum++;
					putchar(' ');
				}
		} else {
			charnum++;
			putchar(c);
		}
	}
	putchar('\n');
}
