#!/usr/bin/awk -f
# "Modern" Fortran has USE and INCLUDE which makes modular builds
# difficult. However, standard old fort77(1posix) plays well with Gcc
# and Make. (C) Andrew Buckeridge 2013. I hear by release this in to
# the public domain so that it may be used with both free and
# proprietary software or any other use.
BEGIN {
	FS="[ \t:,]+"
	OFS=" "
	RS="\r?[\n\f]"
	ORS="\n"
}
FILENAME != src {
	src=FILENAME
	obj=FILENAME
	sub(/\.f90$/,".o",obj)
}
{
	i=1
	while($i=="") {
		i++
		if(i>NF) { next }
	}
	dir=tolower($i)
	i++
	while($i=="") {
		i++
		if(i>NF) { next }
	}
	mod=tolower($i) ".mod"
}
dir == "use" {
#	print obj ":", mod, "#", $0 | "sort -u>dependso.mak"
	print mod, obj | "sort -u>requires.dat"
}
dir == "module" {
#	print mod ":", obj, "#", $0 | "sort -u>dependsm.mak"
	print mod, obj | "sort -u>provides.dat"
}
END {
#	close("sort -u>dependso.mak")
#	close("sort -u>dependsm.mak")
	close("sort -u>requires.dat")
	close("sort -u>provides.dat")

	keep=""
	len=0
	while (\
"join -t' ' requires.dat provides.dat|cut -d' ' -f2-|sort -u" | \
getline ) {
		if($1==$2) {
			keep=$1
			continue
		}
		if(keep==$1) {
			if(length($2)+len+1>78) {
				printf "\\\n %s", $2
				len=length($2)+1
			} else {
				printf " %s", $2
				len+=length($2)+1
			}
		} else {
			printf "\n%s: %s", $1, $2
			keep=$1
			len=length($1)+length($2)+2
		}
	}
	printf "\n\n"
}
