#!/bin/awk -f
{
	lines[NR]=$0
	off=0
	line=$0
	while(match(line, FIND)){
		line=substr(line, RSTART+RLENGTH)
		matches[NR]=matches[NR] ? matches[NR] SUBSEP off + RSTART : off + RSTART
		lengths[NR]=lengths[NR] ? lengths[NR] SUBSEP RLENGTH : RLENGTH
		off+=RSTART+RLENGTH-1
	}
}

END{
	charlen=split("asdfghjkl;qwertyuiopzxcvbnm,.123456789ASDFGHJKL:QWERTYUIOPZXCVBNM<>!@#$%^&*()", chars, "")
	charn=1
	
	for(l=NR;l>0;l--){
		if(l in matches){
			delete a
			split(matches[l], a, SUBSEP)
			delete b
			split(lengths[l], b, SUBSEP)
			for(n in a){
				keys[chars[charn]] = l SUBSEP a[n] SUBSEP b[n]
				access[l, n] = chars[charn]
				if(++charn > charlen) {
					break
				}
			}
		}
	}
	for(l=1;l<=NR;l++){
		# printf "\n%s:", l
		print "" > "/dev/stderr"
		if(!(l in matches)) {
			continue
		}
		delete a
		split(matches[l], a, SUBSEP)
		delete b
		split(lengths[l], b, SUBSEP)
		off_pre=0
		for(n in a){
			off=a[n]
			while(off_pre<off) {
				printf " " > "/dev/stderr"
				off_pre++
			}
			off+=b[n]
			while(off_pre<off) {
				printf "%s", access[l,n] ? access[l,n] : "▒" > "/dev/stderr"
				off_pre++
			}
		}
	}
	"tty-readbyte </dev/stderr" | getline input
	if(input in keys) {
		split(keys[input], i, SUBSEP)
		printf "%s+%s-%s:%s\n", i[1], i[2], i[3], lines[i[1]]
		printf "%s\n%s\n", substr(lines[i[1]], 1, i[2]-1), substr(lines[i[1]], i[2]) | "plumb-click"
		#system("sleep 5")
		#printf "%s", lines[i[1]] | "plumb -a click=" i[2] " -i"
	} else {
		printf "\nUnhandled input '%s'\n", input > "/dev/stderr"
		exit 1
	}
}