#!/usr/bin/perl

sub read_file {
	my ($filename, $title, $cwd, $indent_level, $include_line, $non_menu) = @_;
	my $file_contents = "";
	my $file_handler;
	my $indent_string = "";
	my $indent_string_bracket = "";
	my $line_title = ( split '/', $include_line )[ -1 ];

#	print "\@\@\@Indent level: $indent_level\n";

	for (my $x = 0; $x < $indent_level; $x++) {
		$indent_string .= "\t";
	}

	if( $indent_level > 1 ){
		for (my $x = 0; $x < $indent_level - 1; $x++) {
			$indent_string_bracket .= "\t";
		}
		if( $non_menu == 1 ){
			$indent_string_bracket .= "\t";
		}
	}

#	print "Total indent: |$indent_string|\n";

	$file_contents .= $indent_string_bracket . "# Indentation: ". ( $indent_level - 1 ) ."\n";
	$file_contents .= $indent_string_bracket . "#$include_line\n";
	if( ! -e $filename ){
		#print $indent_string . "~~~ File |$include| doesn't exist\n";
		return $file_contents;
	}

	if( $indent_level != 0 && $non_menu != 1){
		$file_contents .= $indent_string_bracket . "MENU BEGIN ". $title ."\n";
	}

#	print "+++ Found: $filename\n";

	open ($file_handler, $filename);
	while (<$file_handler>) {
		chomp;
		my $line = $_;
		#if( $line =~ /menu/ ){
		#	print "Found a menu #1: $line\n";
		#}
		if( $line =~ /^\s*menu\s+include\s+([^\s]*)\s+(.*)$/i ){
			my $next_filename = $1;
			my $next_name = $2;
			$next_filename =~ s/^\///;
#			print $indent_string . "Found a menu:\n";
#			print $indent_string . "\t$line\n";
#			print $indent_string . "\tFilename: $next_filename\n";
#			print $indent_string . "\tMenu Name: $next_name\n";

			my $next_indent = $indent_level + 1;

			$line = read_file( $next_filename, $next_name, $cwd, $next_indent, $line) ."\n";

			$file_contents .= "$line";
		} elsif( $line =~ /^\s*menu\s+include\s+([^\s]*)\s*$/i ){
			my $next_filename = $1;
			my $next_name = $2;
			$next_filename =~ s/^\///;
#			print $indent_string . "Found a menu:\n";
#			print $indent_string . "\t$line\n";
#			print $indent_string . "\tFilename: $next_filename\n";
#			print $indent_string . "\tMenu Name: $next_name\n";

			my $next_indent = $indent_level + 1;

			$line = read_file( $next_filename, "", $cwd, $next_indent, $line, "1") ."\n";

			$file_contents .= "$line";

		} else {
			$file_contents .= $indent_string . "$line\n";
		}
	}
	close ($file_handler);

	if( $indent_level != 0 && $non_menu != 1){
		$file_contents .= $indent_string_bracket . "MENU END\n";
	}

	return $file_contents;
}

my($filename) = @ARGV;

#print "Filename: $filename\n";

my $merged_file = read_file( $filename, "", "/", 0, "");


#print "=============================\n";
#print "=============================\n";
#print "=============================\n";
#print "=============================\n";

print "$merged_file\n";
