#!/bin/dash
cat << 'EEE' > /dev/null
/* ljt .... joint line, connect two lines. bourne-shell script
 * Copyright (C) 2018 Momi-g
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
EEE

#optcheck--------
buf=`./rdopt ":h1:2:rn:s:" "$@"`
if [ $? -ne 0 ] ; then echo "$0: optErr see -h. sleep 1000" >/dev/stderr;sleep 1000; exit 1; fi
eval "$buf"
#echo "___$buf"
#exit 0	#0.040

f_regex="$opt_1"
s_regex="$opt_2"
ereflg="$opt_r"
lncmd="$opt_n"
sep="$opt_s"
err=1
mode=""

buf=`echo "$lncmd" | tr -d '0123456789 \-' `
if [ "$lncmd" != "" ] && [ "$buf" = "" ] ; then
	err=0
	mode="mode_n-"
fi

if [ "$f_regex" != "" ] && [ "$s_regex" != "" ] && [ "$lncmd" = "" ] ; then
	err=0
	mode="mode_reg"
fi

if [ "$opt_h" = "1" ] ; then
cat << 'EEE'
HowTo (joint line, connect in front and behind lines. bourne-shell script)
opt: -h, -1(st reg), -2(nd reg), -s(eparator), -r(extended-regex), -n(line num)
------
ex.)
echo "ABA
BBB
ABB
BBA" | ljt -1 '/B/' -2 '/BB/'	

... -s "" is default
>>>
AAABBB
ABBBBA		...not 'AAABBBABB', only once just behind.

ex.) ... | ljt -n 2-4		#>>> combine line number 2 to 4
 
regex mode: -1/-2 option, sed regex.	linenum mode: -n option.
ensuring max 8192 byte at 1 line.
 ...support only stdin/stdout.
EEE
exit 0
fi

if [ "$err" != "0" ]; then
	echo "$0: opt err. see -h. sleep"  >/dev/stderr
	sleep 1000
	exit 1
fi





# -n - mode
if [ "$mode" = "mode_n-" ] ; then	
	buf=`echo "$lncmd" | tr '-' ' ' `
	set -- $buf
	ss=$1
	ee=$2

	buf=`echo "$lncmd" | tr '-' ',' `
cmd="sed -ne '$buf {
s#\$#$sep#g
H
}
$ee {
	g
	s#\n##g
	s#$sep\$##g
	p
}
$buf ! p'"
	
	cat - | eval "$cmd"
	exit
fi

# regex mode
if [ "$mode" = "mode_reg" ] ; then
	if [ "$ereflg" != "" ] ; then
		ereflg="-r"
	fi
	
	cmd="sed $ereflg -ne '
$ {p; q;}
$f_regex {h; n; b label1}
$f_regex !{p; b label2}

:label1
$s_regex {
s#^#$sep#g
H; g;
s#\n##g
p
b label2}

$s_regex !{H; g; p; b label2}
:label2'
"
	#printf '%s\n' "$cmd"
	cat - | eval "$cmd"
	exit
fi
