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

# -n opt removed. why? > echo -n parsed
fl="/dev/stdin"
opt_n=""

for i in "$@"
do
	if [ "$i" = "-h" ] ; then	#readable
		opt_h=1
		shift
		continue
	fi
	
	if [ "$i" = "-n" ] ; then	#readable
		opt_n="-n"
		shift
		continue
	fi

	if [ -r "$i" ] ; then	#readable
		fl="$i"
		shift
		continue
	fi
	
	# 10-20 param get only once
	if [ "$range" != '' ] ; then
		continue
	fi
	
	#parse args.
	#10-20	10-20	10,20	sed -n -e "10,20p"
	#5-		5-z		5,$
	#-11	1-11	
	#3		3-+0
	#15-+2	15-+2
	
	range=`echo "$i" | sed -n -e '
		/^[123456789][0123456789]*[-][123456789][0123456789]*$/	{
			s#[-]#,#g
			p
		}
		
		/^[123456789][0123456789]*[-]$/	{
			s#-#,$#g
			p
		}
		
		/^[-][123456789][0123456789]*$/	{
			s#-#1,#g
			p
		}
		
		/^[123456789][0123456789]*$/	{
			s#$#-+0#g
			p
		}
		
		/^[123456789][0123456789]*[-][+][0123456789]*$/	{
			p
		}'`	#num only

	if [ "$range" != '' ] ; then
		shift
		continue
	fi
	
	#no hit args
	echo "$0: invalid args or nofile. see -h. sleep." >/dev/stderr
	sleep 1000
	exit 1
done

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

if [ "$opt_h" = "1" ] ; 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'
to remove use 'sed' as   ... | sed -e 's/^[0123456789]*[ ]//g'
EEE
	exit 1
fi
#no range / no input data
if ! [ -p /dev/stdin ] && [ "$fl" = "/dev/stdin" ] || [ "$range" = "" ]; then
	echo "$0: args err. see -h. sleep." >/dev/stderr
	sleep 1000
	exit 1
fi
#---optEnd


#cal -+ 
buf=`echo "$range" | sed -n -e '
	/[-][+]/{
		s#[-][+]# #g
		p
		}
	'`
if [ "$buf" != "" ] ; then
	set -- $buf
	l=`expr $1 - $2`
	h=`expr $1 + $2`
	if [ $l -le 0 ] ; then
		l=1
	fi
	range="$l,$h"
fi

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