#!/bin/sh
cat << 'EEE' > /dev/null
/* lcat, linecat, show lines. sed parse bourne-sh script
 * Copyright (C) 2017-2019 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

if [ "$1" = "-h" ] || [ "$#" = "0" ]; then
cat << 'EEE'
HowTo (linecat, show lines. sed parser)
option: -h (this) -n(umber)
------
ex) cat hoge.txt | lcat 10-20
ex) lcat 10-20 unko.txt
ex) lcat -n unko.txt 10-20		# 3, 10-20, 5-, -11, 15-+2 (...13-17) 
>>>
10 aaa
11 bbb
...
20 ccc

-n option format is 'line nun'+'space 1char'+'line'
EEE
	exit 1
fi

func_lcat () {
bklcat_nflg="$lcat_nflg"
bklcat_file="$lcat_file"
bklcat_range="$lcat_range"
bklcat_buf="$buf"
bklcat_ii="$ii"
lcat_file='-'
for ii
do
	if [ "$ii" = "-n" ] ; then
		lcat_nflg='1'
		continue
	fi
	if [ -e "$ii" ] && [ "$lcat_file" = "-" ] ; then
		lcat_file="$ii"
		continue
	fi
	
	lcat_range=`echo "$ii" | sed -ne '
	/^[123456789][0123456789]*[-][123456789][0123456789]*$/ s#[-]#,#p
	/^[123456789][0123456789]*[-]$/	s#-#,$#p	
	/^[-][123456789][0123456789]*$/	s#-#1,#p	

	/^[123456789][0123456789]*$/ s#$#-+0#	
	/^[123456789][0123456789]*[-][+][0123456789]*$/	p'`	#num only

	if [ -z "$lcat_range" ] ; then
		echo "$@: invalid args. sleep." >/dev/stderr
		while :
		do
			sleep 1000
		done
	fi
done
#cal -+ 
buf=`echo "$lcat_range" | sed -ne '/[-][+]/ s#[-][+]# #p'`
if [ "$buf" != "" ] ; then
	set -- $buf
	buf=$(($1 - $2))
	if [ $buf -le 0 ] ; then
		buf=1
	fi
	lcat_range="$buf"','$(($1 + $2))	# 10,14 etc
fi

#make comm
#cat -n "unko.txt" | sed -n -e '1,$p'
if [ "$lcat_nflg" != "1" ] ; then
	cat "$lcat_file" | sed -n -e "$lcat_range"p
else
	cat "$lcat_file" | sed -e '=' | sed -e '
N
s#\
# #g' | sed -n -e "$lcat_range"p
fi

lcat_nflg="$bklcat_nflg"
lcat_file="$bklcat_file"
lcat_range="$bklcat_range"
buf="$bklcat_buf"
ii="$bk_ii"
}

# ---main
func_lcat "$@"
