#! /bin/sh

# $Id: mkdocfromc,v 1.5 95/09/08 19:20:12 lee Exp Locker: lee $

PATH=`pwd`/bin:$PATH
export PATH

/bin/rm -rf Categories
mkdir Categories

for dir in h liblqerror liblqtext liblqutil lqtext # menu
do
    i=../../src/$dir
    echo "**** $dir **** "
    if test -d "$i/."
    then
	find $i -type f -name '*.[ch]' -print | xargs gnugrep -l '<Function' |
	xargs onefile |
	mawk '

BEGIN {
    Initialize()
}

(NR == 1) {
    SomethingThere = 1
}

/<Entry>/ {
    InEntry = 1;
    sub(/<Entry>/, "<Entry dir=\"'"$dir"'\">")
    sub(/><Entry/, ">\n<Entry")
    Text($0)
    next
}

/<\/Decl>/ {
    InEntry = 0
    Text(sprintf("%s\n</Entry>", $0))
    Initialize()
    next
}

/<\/Entry>/ {
    if (!InEntry) {
	next
    }
}

/<Function/ {
    if (!InEntry) {
	Text("<Entry dir=\"'"$dir"'\">")
	InEntry = 1
	Text($0)
	next
    }
}

/<Class>/ {
    Class = $0
    sub(/^ *<Class>[ 	]*/, "", Class)
    gotClass = 1
    if (gotName) {
	StartPrinting()
    }
}

/<Name>/ {
    Name = $0
    sub(/^.*<Name>[ 	]*/, "", Name)
    sub(/[ 	]*<\/Name>.*$/, "", Name)
    gotName = 1
    if (gotClass) {
	StartPrinting()
    }
}

/<\/Function>/ {
    InEntry = 0;
}

{
    Text($0)
}

function Initialize()
{
    if (SavedLineCount) {
	StartPrinting()
    }

    if (FileName) {
	close(FileName)
    }
    InEntry = 0
    SomethingThere = 0
    Class = "Other"
    Name = "Other"
    FileName = "not-set-yet"
    SavedLineCount = 0
    printing = 0
    gotName = 0
    gotClass = 0
    OtherClasses = ""
}

function Text(Line)
{
    if (printing) {
	print Line >> FileName
    } else {
	Lines[++SavedLineCount] = Line
    }
}

function StartPrinting(			i)
{
    if (Class ~ /,/) {
	OtherClasses = Class
	sub(/[^,]*, */, "", OtherClasses)
	sub(/[ 	]*,.*$/, "", Class)
    }

    FileName = "Categories/" Class "/" Name
    gsub(/ /, "_", FileName);
    t = Class;
    gsub(/ /, "_", t)
    system("mkdir -p \"Categories/" t "\"" )
    printf "**** ";
    s = \
"test -f \"" FileName "\" || ( echo '"'"'<!DOCTYPE File PUBLIC \"-//Liam Quin//DTD C API Documentation v1.1//EN\" \"doc.dtd\"><File>'"'"' > \"" FileName "\"; echo -n \"Created \" 1>&2 )"

    system(s)
    printf "%s\n", FileName

    for (i = 1; i <= SavedLineCount; i++) {
	print Lines[i] >> FileName
    }
    printing = 1
    SavedLineCount = 0
}

END {
    if (SomethingThere) {
	if (!printing) {
	    StartPrinting()
	}
    } else {
	print "**** empty"
    }

    if (OtherClasses != "") {
	n = split(OtherClasses, Names, /[ 	]*,[ 	]*/)
	while (n > 0) {
	    printf "** %s links to %s\n", FileName, Names[n]
	    gsub(/ /, "_", Names[n]);
	    system("mkdir -p `dirname \"Categories/" Names[n] "\"`" )
	    system(sprintf("ln -s %s %s", FileName, Names[n]))
	    n--;
	}
    }
}
	'
    fi
done
