tabstops.c
changeset 0 cb8aa6a22086
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tabstops.c	Thu May 18 22:56:54 2006 +0200
@@ -0,0 +1,118 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+
+#define MAXTABSTOPS 50
+#define MAXLINECHARS 10000
+
+
+void strpart(char * dest, const char *src, const int begin, const int end)
+{
+	int i;
+	i=begin;
+	while (i<=end)
+	{
+		dest[i-begin] = src[i];
+		i++;
+	}
+	
+	dest[i-begin] = '\0';
+}
+
+int main(int numarg, char **args)
+{
+	int tabstops[MAXTABSTOPS+1];
+	int i,j;
+	char original[MAXLINECHARS];
+	char word[MAXLINECHARS];
+	int this_tab_stop;
+	int last_char;
+	int reverse=0;	/* Funcionament normal */
+	int num_tab_stops;
+	int output_column;
+
+
+	if (numarg<2)
+	{
+		printf("Bad Usage.\n");
+		exit(1);
+	}
+
+	tabstops[0] = 0;
+	tabstops[numarg] = MAXLINECHARS;
+	num_tab_stops = 1;
+
+	for (i=1; i<numarg; i++)
+	{
+		if (args[i][0] == '-')
+			switch(args[i][1])
+			{
+			case 'r':
+				reverse=1;
+			}
+		else
+			tabstops[num_tab_stops++] = atoi(args[i])-1;
+		/* Usually columns start at '1' */
+		/* Not error-free in atoi! */
+	}
+
+	while(!feof(stdin))
+	{
+		fgets(original, MAXLINECHARS, stdin);
+		if (feof(stdin)) break;
+
+		if (reverse==0)
+			this_tab_stop=0;
+		else
+			this_tab_stop=1;
+
+		last_char=-1;
+
+		if(reverse==0)
+		{
+			for(i=0; i<strlen(original); i++)
+			{
+				if(i == tabstops[this_tab_stop+1])
+				{
+					strpart(word, original, tabstops[this_tab_stop], last_char);
+					printf("%s", word);
+					if(this_tab_stop != num_tab_stops)	/* Ultim tab stop */
+						putchar('\t');
+
+					/* A pel proxim tab */
+					last_char = tabstops[++this_tab_stop]-1;
+				}
+
+				if(original[i] != ' ')
+					last_char = i;
+			}
+			/* Final de linia */
+			strpart(word, original, tabstops[this_tab_stop], last_char);
+			printf("%s", word);
+		}
+		else
+		{
+			this_tab_stop=1;
+			output_column=1;
+			for(i=0; i<strlen(original); i++)
+			{
+				if(original[i]=='\t' && this_tab_stop < num_tab_stops) 
+				{
+					for(j=output_column; j<=tabstops[this_tab_stop]; j++)
+					{
+						putchar(' ');
+					}
+					output_column = tabstops[this_tab_stop];
+					this_tab_stop++;
+				}
+				else
+					putchar(original[i]);
+
+				output_column++;
+			}
+		}
+			
+	}
+
+	exit(0);
+}