#! /bin/sh

mawk '
BEGIN {
    Magic = 0
    Page = 0
    catOpen = 0
}

/^L / {
    LineLength = $2
}

/^P / {
    if (Page && catOpen) {
	close("cat 1>&2")
    }
    ++Page
    printf "{%d}", Page | "cat 1>&2"
    catOpen = 1
}

#  %LL ww min best --- word parameters
# best is expressed as a fraction, e.g.
# %LL ww 56 1.5
# specifies a min word width of 56u and a preferred width of 1.5*56= 84u
#
/^%LL ww / {
    minWordWidth = $3
    bestWordWidth = $4 * $3
    if ($5 == "") {
	maxWordWidth =  $3 * 3
    } else {
	maxWordWidth = $5 * $3
    }
    # print
    next
}

/^%%LL+/ {
    Magic = 1
    # print
    next
}

(Magic == 0) { 
    print
    next
}

/^%%LL-/ {
    Magic = 0
    # print
    next
}

/^N f j/ {
    spaceCount = $4

    if (spaceCount == 0) {
	print
	next
    }
    oldSlack = $5
    perSpace = oldSlack / spaceCount
    if (perSpace > maxWordWidth) {
	$2 = "b"
	$3 = "l"
	printf "<" | "cat 1>&2"
	catOpen = 1
    } else {
	print
	next
    }
}

/^N b l/ {
    spaceCount = $4
    if (spaceCount == 0) {
	print
	next
    }
    oldSlack = $5
    if (oldSlack > 0) {
	# see how much space we have got
	extraWanted = (bestWordWidth - minWordWidth) * spaceCount
	spaceUsed = LineLength - oldSlack
	spaceAvailable = LineLength - (spaceUsed + minWordWidth * spaceCount)

	if (oldSlack <= extraWanted) {
	    # justify the line:
	    printf "N f j %d %d\n", spaceCount, oldSlack
	    printf ">" | "cat 1>&2"
	    catOpen = 1
	    next
	}
	# justifying would make the line too wide, do this instead:
	printf "L %d\n", spaceUsed + extraWanted
	needLineLength = 1
	printf "N f j %d %d\n", spaceCount,  extraWanted
	printf "." | "cat 1>&2"
	catOpen = 1
	next
    }
}

{
    print
}

/^n/ {
    if (needLineLength) {
	printf "L %d\n", LineLength
    }
}

END {
    print "" | "cat 1>&2"
    catOpen = 1
}
' ${@+"$@"}

exit $?


# examples:
X ps 300 1 1
Y P default letter 2550 3300 21 17 56 25 2400 3210
L 1950
N n c 8 546		<-------- centred line
N f j 7 55		<-------- filled justified
N b l 6 164		<-------- forced break, left
= (the data (fi)les have been altogether removed.)
