#!/bin/sh

# $dir/*/*.sml $B$N%U%!%$%k$rD4::$7!$<!$N#2<oN`$N0lMwI=$r:n@.(B
# (1) $B%U%!%$%kL>!$HoDj5A(B signature $BL>$NNs(B
# (2) $BDj5A%U%!%$%kL>!$;HMQ(B signature $BL>!$;HMQ%U%!%$%kL>(B

### files= */*.sml 
files=`ls ../sprint/*.sml ../term_rewriting/*.sml ../rwchecker/*.sml ../util/*.sml`

table=structures-defined.txt
outfile=structures-used.txt

structures_defined () { infile=$1
    cat $infile |
    grep '^structure' |
    sed 's/^structure  *\([A-Z_][A-Za-z0-9_]*\)[ :=].*/\1/' |
    sort | uniq |
    tr '\n' ' '
}

structures_used () { infile=$1
    # $BJLL>Dj5A$5$l$?(B structure
    cat $infile |
    grep 'structure  *[A-Z][A-Z]*  *=' |
    sed 's/.*structure.*= *\([A-Z_][A-Za-z0-9_]*\).*/\1/'
    # $B4X?tL>$r8BDj$9$k(B signature
    cat $infile |
    grep '[A-Z_][a-zA-Z0-9_]*[.]' |
    perl -ne 'if (/([A-Z_]\w*)\./) { printf "%s\n", $1 }' |
    sort | uniq
}

get_core='s/.*\/\(.*\/.*\).sml/\1/'

# $BDj5A$5$l$?(B structure $B$NCj=P(B

for file in $files; do
    core=`echo $file | sed $get_core`
    structures=`structures_defined $file`
    echo "$core: $structures"
done > $table

#cat $table; exit

# $B;H$o$l$?(B structure $B$NCj=P(B

abbrev_name='^[A-Z][A-Z]*$'
local_name='^_'
wrong_name="(${abbrev_name}|${local_name})"

for file in $files; do
    core=`echo $file | sed $get_core`
    structures=`structures_used $file | egrep -v $wrong_name`
    #echo [$core]
    #echo $structures
    for s in $structures; do
	found=`egrep ' '$s'( |$)' $table | head -1 | cut -d : -f 1`
	echo "$core $s $found"
    done
done > $outfile
