#!/usr/bin/perl



@files = @ARGV or die <<USAGE;
usage: $0 file [file [file ...]]

$0 rewrites the whitespace in all
preprocessor directives to increase
readability, while correctly ignoring
any preprocessor directives that have
been commented within /* ... */


USAGE


for (@files){
	-f $_ or die "$_ is not a file\n";
	-r  _ or die "$_ is not readable\n";
	-w  _ or die "$_ is not writable\n";
};

sub INDENTATION_FACTOR() { 3 };


for $file (@files){
	open IN, "<", $file;
	@lines = ();
	$incomment = 0;
	$indent = '';
	$depth = 0;
	while (<IN>){
		unless ($incomment){
			if(/^#\s*(\w\w)/){
				$word = $1;

	$word =~ /el|en/ and $depth--;
	$indent = ' 'x ($depth * INDENTATION_FACTOR);
	$word =~ /el|if/ and $depth++;

				s/^#\s*/#$indent/;
			};

			commenttest($_);


		}else{
# has multi-line comment ended?
			endcommenttest($_);

		};
		push @lines, $_;
	};
	close IN;
	open OUT, '>', $file;
	print OUT @lines;
};

sub commenttest{  # does this line start a multi-line comment?
	$t = shift;
	($start,$rest) = $t =~ m{^(.*?)/\*(.*)} or return;
	if(
		($qc = $start =~ tr/"/"/)
	and
		($qc/2 != int($qc/2))
	){
		$rest =~ s/^.*"// or die "unmatched \" in $t";
		return commenttest($rest);
	};
	$incomment = 1;
	endcommenttest($rest);
};

sub endcommenttest { # does this line end a comment (w/o starting a new one?)
	$t = shift;
	($rest) = $t =~ m{\*/(.*)} or return;
	$incomment = 0;
	commenttest($rest);
};

__END__





	
