#! /usr/local/bin/jperl
#	@(#)mkimport 00-09-28
#
#	C/C++  EXPORT ؿѿȴФIMPORT 롣
#	(C) Copyright 1994-2000 by Personal Media Corporation
#
#	إåե˼Τ褦ʷǡɤΥե뤫 IMPORT 
#	뤫ꤹ롣
#
#	#if IMPORT_DEFINE
#	/* foo.c */
#	/* bar.c */
#	#endif
#
#	/* foo.c */ ʤ foo.c  IMPORT ʬࡣ
#
#	#if IMPORT_DEFINE
#	/* foo.c */
#	IMPORT void foo(void);
#	/* bar.c */
#	IMPORT int bar(int a);
#	#endif
#
#	ʤIMPORT κˤϸŤϺΤǡ֤¹Ԥ
#	ƤǿǤĤ롣
#
$usage = 'usage: mkimport file_list';

#
# EXPORT ȴФIMPORT 
#
sub mkextern
{
	local($src) = @_;

	open(SRC, "$src") || die "can not open $src\n";

	while ( <SRC> ) {
		chop;

		next if !/^EXPORT/;

		s@/\*[^\*]*\*/@@g;		# Ⱥ
		s@/\*[^\*]*$@@;
		s@//.*$@@;
		s/\s*$//;			# ζ

		while ( s/{[^{}]*(}|$)//g ) {}	# ؿΤޤѿ
						# ֥å

		if ( !/\)\s*$/ ) {		# ؿ = ϻĤ
			s/=[^,;]*([,;])/\1/g;	# ѿν
			s/=[^,;]*$/;/g;
		}

		s/(\w)\[[^\]]*\]/\1[]/g;	# Ƭǿ

		s/\)\s*$/);/;			# ؿΤȤǸ ; ɲ

		s/^EXPORT/IMPORT/;

		print OUT "$_\n";
	}

	close(SRC);
}

# ----------------------------------------------------------------------------

# ޥɰå
if ( $#ARGV < 0 ) {
	print STDERR "$usage\n";
	exit(1);
}

# ե뤴Ȥ˽
foreach $out ( @ARGV ) {

	# ե¸
	$in = "#$out";
	if ( -e $in ) {
		print STDERR "$in is already exist.\n";
		next;
	}
	rename("$out", "$in") || die "can not rename $out to $in\n";

	open(IN, "$in")    || die "can not open $in\n";
	open(OUT, ">$out") || die "can not open $out\n";

	$imp_def = 0;
	while ( <IN> ) {

		if ( $imp_def == 0 ) {
			# IMPORT_DEFINE ʳʬ
			print OUT;
			$imp_def++ if /^\s*#\s*(if|ifdef)\s+IMPORT_DEFINE/;
		} else {
			# IMPORT_DEFINE 
			if ( /^\s*#/ ) {
				$imp_def-- if /^\s*#\s*endif/;
				$imp_def++ if /^\s*#\s*if/;
				print OUT;
			} else {
				print OUT if !/^IMPORT/;
				if ( ($src) = m@^/\*\s*(\S+)\s*\*/@ ) {
					# IMPORT 
					&mkextern($src);
				}
			}
		}
	}

	close(OUT);
	close(IN);
}

exit(0);
