#!/usr/bin/awk -f

# This AWK script implements the second variant.
# It renumbers the footnotes in the text and then reorders the footnote descriptions.
# Renumbering happens line per line, but sorting of footnotes needs an array.
#
# usage: ./footnotes.awk < sample4.txt

BEGIN {
	ORS = ""
	footnotesSection = 0;
	footnoteCounter = 1;
	lastSortedFootnote = 0;
}

/^@footnote:$/ {
	footnotesSection = 1;
	next;
}

# matches lines with footnotes in the main text
/\[[0-9]+\]/ && footnotesSection == 0 {
	scannerOffset = 1;
	footnoteStartOffset = 1;

	while(0 != (footnoteStartOffset = match(substr($0, scannerOffset), "\\[[0-9]+\\]"))) {

		print substr($0, scannerOffset, footnoteStartOffset -1);

		footnoteStartOffset = footnoteStartOffset + scannerOffset - 1;
		footnoteStopOffset = index(substr($0, footnoteStartOffset), "]");

		footnote = substr($0, footnoteStartOffset + 1, footnoteStopOffset - 2);
		if(footnote in footnoteMap) {
			print "[" footnoteMap[footnote] "]";
		} else {
			print "[" footnoteCounter "]";
			footnoteMap[footnote] = footnoteCounter;
			footnoteCounter++;
		}

		scannerOffset = footnoteStartOffset + footnoteStopOffset;
	}

	print substr($0, scannerOffset) "\n";
	next;
}

# matches lines with footnotes in the footnote section
/^\[[0-9]+\]/ && footnotesSection == 1 {
	footnote = substr($0, 2, index($0, "]") - 2);
	lastSortedFootnote = footnoteMap[footnote];
	footnoteContainer[lastSortedFootnote] = "[" lastSortedFootnote "]" substr($0, index($0, "]") + 1) "\n";
	next;
}

# matches lines without footnotes in the main text
// && footnotesSection == 0 {
	print $0 "\n";
	next;
}

# matches lines without footnotes in the footnote section
// && footnotesSection == 1 {
	footnoteContainer[lastSortedFootnote] = footnoteContainer[lastSortedFootnote] $0 "\n";
	next;
}

# print sorted footnote section
END {
	print "@footnote:\n";
	for (x = 0; x < footnoteCounter; x++) {
		if(length(footnoteContainer[x]) == 0) {
			print "[" x "] \n";
		} else {
			print footnoteContainer[x];
		}
	}
}