#!/bin/awk -f
## (c) Sphynkx 2023 GPL3++
## Script parses input stream, modifyes headings (add 'id"-s and <a name> tags). Also collect them 
## to separate div as list. List places on page according css options. To hide this list for some separate 
## page put tag "<NOTOC>" in any place in source of page.

BEGIN { n = 0; notoc = 0 }

function mk_toc_item(tag, id, i, n)
	{
	margin = ""
	while(i--) margin = margin "&nbsp;"
	return "<li>" margin "<a href=\"\#" n "_" id "\">" tag "</a></li>"
	}

{
if($0 ~ /<NOTOC>/) notoc++
tag = $0
split("123456", arr, "")
for (i in arr)
    {
    _ = "<h"i">"
    if($0 ~ _)
		{
		gsub("<h"i">", "", tag)
		gsub("</h"i">", "", tag)
		id = tag
		gsub(" ", "_", id)
		toc_item[n] = mk_toc_item(tag, id, i, n)
		tag = "<a name=\"" tag "\"></a><a name=\"" n "_" id "\"></a><h" i " id=\"" id "\">" tag "</h" i ">"
		n++
		}
    }
print tag
}

END {
	if(notoc > 0) n=0
	if(n == 0) hide_div=" style=\"display: none\""
	print "</div><div class=\"div_toc\"" hide_div "><ul class=\"ul_toc\">"
	for(i = 0; i < length(toc_item); i++) print toc_item[i]
	print "</ul></div><style>.div_after_toc {position: relative; top: " 16*n+50 "px;}</style>"
	}