#!/usr/pkg/bin/perl
#####
# NAME
#	detab - replace tab codes by spaces
# VERSION
#	$Id$
# CHANGELOG
#	$Log$
# USAGE
#	detab [options]
#   OPTIONS
#	-w num	: set tab width
#
# DESCRIPTION
#	Detab reads the text data from standard input and replace the tab code
#	by spaces. The tabstop value can be changed by "-w NN" option.
#	The "NN" means the new tabstop unit.

$TABWIDTH 	= 8 ;
$NEWLINE	= "\n" ;
$TAB		= "\t" ;
$SPACE		= " " ;

main: {
	local($opt, $line, @charset, $char, $col, $nextcol) ;

	# analyze option
	$opt = shift(@ARGV) ;
	if($opt eq '-w'){
		$TABWIDTH = shift(@ARGV) ;
		if(!($TABWIDTH =~ /^[0-9]*$/)){
			die "number is required after '-w' option\n" ;
		}
		if($TABWIDTH <= 0){
			die "the tab width must be bigger than 0 \n" ;
		}
	}

	while($line = <>){
		@charset = split(//, $line) ; $col = 0 ;
		foreach $char(@charset){
			if($char eq $TAB){
				$nextcol = int $col / $TABWIDTH ;
				$nextcol = ($nextcol+1) * $TABWIDTH ;
				# print STDERR "col:$col, next:$nextcol\n" ;
				for( ; $col<$nextcol ; $col++){
					print $SPACE ;
				}
			} else {
				print $char ; $col++ ;
			}
		}
	}
	exit 0 ;
}

