#!/bin/csh -f

# input is a .c file, output is a .c file without redundant includes
#	or redundant defines
# 	(as a side effect, all the includes and defines are moved to
#	 the beginning of the new file)

if ($#argv != 1) then
	echo Usage fix_includes filename
	exit(-1)
endif

set input = $argv[1]
#echo $input
#echo $argv[0]

# create a file without includes or defines, i.e., code only
grep -v '^#include ' $input | grep -v '^#define ' > /tmp/fi.$USER.code

# create a file with only includes
grep '^#include ' $input > /tmp/fi.$USER.includes

# create a file with only defines
grep '^#define ' $input > /tmp/fi.$USER.defines

# uniquify the includes, but preserve the order!
$cwd/../../bin/uniq-ordered /tmp/fi.$USER.includes >/tmp/fi.$USER.uniq

# uniquify the defines, but preserve the order!
$cwd/../../bin/uniq-ordered /tmp/fi.$USER.defines >/tmp/fi.$USER.uniq2

# create a file with the uniquified includes, defines and the code
cat /tmp/fi.$USER.uniq /tmp/fi.$USER.uniq2 /tmp/fi.$USER.code >/tmp/fi.$USER.new

# save the input file

mv $input $input.old
cp /tmp/fi.$USER.new $input

# clean up
/bin/rm -f /tmp/fi.$USER.{code,uniq,uniq2,includes,new}

