#! /usr/bin/perl
#
# cppindent - Indent C preprocessor directives
#
# June 9, 2000 - Andrew E. Mileski <andrewm @netwinder.org>
#

use strict;

my $line = "";		# Temporary
my $spaces = "";	# The current amount of indentation
my @stack = ();		# The last conditional expression

while (<>) {
	chomp;

	# Substitute "if" statements for "ifdef" and "ifndef" statements
	if (m/^(\s*#\s*if)def\s+(\S+)(.*)/) {
		$_ = "$1 defined($2)$3\n";
	} elsif (m/^(\s*#\s*if)ndef\s+(\S+)(.*)/) {
		$_ = "$1 !defined($2)$3\n";
	}

	# Handle "if" statements
	if (m/^\s*#\s*if\s+(.*)/) {
		push @stack, $1;
		print "#${spaces}if $1\n";
		$spaces = "$spaces  ";
		next;
	}

	# Handle "else" statements
	if (m/^\s*#\s*else\s*(.*)/) {
		$line = "!(".(pop @stack).")";
		push @stack, $line;
		$spaces =~ s/..$//;
		print "#${spaces}else /* $line */ $1\n";
		$spaces = "$spaces  ";
		next;
	}

	# Handle "endif" statements
	if (m/^\s*#\s*endif\s*(.*)/) {
		$line = pop @stack;
		$spaces =~ s/..$//;
		print "#${spaces}endif /* $line */ $1\n";
		next;
	}

	# Handle all other directives
	if (m/^\s*#\s*(\S+)\s*(.*)/) {
		print "#${spaces}$1 $2\n";
		next;
	}

	# Not a preprocessor line
	print "$_\n";
}
