#!/bin/sh

awk -F '[\t ]*' '
function rewriteLine() {
	split(m[1], opts, ",")
	for(optsI = 1; optsI < length(opts); optsI++) {
		lines[linesLen++] = currentLineRewrite opts[optsI] substr(slice, mEnd)
	}
	currentLineRewrite = currentLineRewrite opts[optsI]
}
function rewriteLines() {
	for(linesI = 0; linesI < linesLen; linesI++) {
		currentLineRewrite=""
		mI=1 # match index relative to head
		mCount=0
		mEnd=0
		slice=lines[linesI]
		while(mI != 0) {
			mI = match(slice, /{([^}]*)}/, m)
			if(mI == 0) {
				currentLineRewrite = currentLineRewrite slice
				continue
			} else {
				currentLineRewrite = currentLineRewrite substr(slice, 0, mI - 1)
			}
			mCount++
			mEnd = mI + length(m[0])
			rewriteLine()
			slice = substr(slice, mEnd)
		}
		lines[linesI]=currentLineRewrite
	}
}
function endBlock() {
	if(blockState == 0) {
		return
	}
	if(blockState == 1) {
		delete bindLines
		bindLinesCount=0
		blockState=0
		return
	}
	delete lines
	lines[0]=body
	linesLen=1
	rewriteLines()
	body=""
	for(i = 0; i < linesLen; i++) {
		for(j = 0; j < bindLinesCount; j++) {
			print bindLines[j][i] " { " lines[i] " }"
		}
	}
	delete bindLines
	bindLinesCount=0
	blockState=0
}

BEGIN {
	blockState=0
	bindLinesCount=0
}
/^[\t ]*\#/ || length($0) == 0 { next }
/^[^\t ].*/ {
	if(blockState > 1) {
		endBlock()
	}
	sub(/^[ \t]+/, "");
	sub(/[ \t]+$/, "");
	delete lines
	lines[0]=$0
	linesLen=1
	rewriteLines()
	for(i = 0; i < linesLen; i++) {
		bindLines[bindLinesCount][i]=lines[i]
	}
	bindLinesCount++
	blockState=1
	next
}
/^[\t ]+/ && blockState > 0 {
	blockState=2
	sub(/^[ \t]+/, "");
	sub(/[ \t]+$/, "");
	body=body " " $0
	next
}

END {
	endBlock()
}' ../binds
