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

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

sub flush_space {
	local($spacenum) = @_ ;
	local($i) ;

	for($i=0 ; $i<$spacenum ; $i++){
		print $SPACE ;
	}
}

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

	# 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 ; $spacenum = 0 ;
		foreach $char(@charset){
			if($char eq $SPACE){
				if($col % $TABWIDTH == $TABWIDTH - 1){
					print $TAB ;
					$spacenum = 0 ;
				} else {
					$spacenum++ ;
				}
				$col++ ;
			} elsif($char eq $TAB){
				flush_space($spacenum) ; $spacenum = 0 ;
				print $TAB ;
				$col = int($col/$TABWIDTH) + 1 ;
				$col = $col * $TABWIDTH ;
			} else {
				flush_space($spacenum) ; $spacenum = 0 ;
				print $char ;
				$spacenum = 0 ; 
				$col++ ;
			}
		}
	}
	exit 0 ;
}

