: !/bin/sh
# NAME
#	wrap
# SYNOPSIS
# 	wrap [-nnn] [-s] [file]
# DESCRIPTION
#	Wrap wraps lines to nnn chars (default 80): BITNET does not like
#	lines longer than that.
#	It reads file (standard input if no file is specified) and
#	writes lines of specified maximal length to standard output,
#	embedded in a shell script running of which restores the original.
#	If file is specified, wrap checks if it is a shar file (by searching
#	for the string "# This is a shell archive" at the start of a line)
#	and, if so, adapts the surrounding shell script appropriately.
#	Specifying -s makes wrap behave as if it were wrapping a shar file
#	without checking.
#	Recommended use:		shar foo ... | wrap -s >bar
#		to be restored with	sh bar
# VERSION
#	1.1
# BUGS
#	This should of course be an option of shar.
# AUTHOR
#	Rob Gerth, Eindhoven University of Technology
#	wsinrobg@eutrc3.urc.tue.nl or WSDCROBG@HEITUE5.BITNET
#	
#
FILE=
SHAR=
DEFAULT=79
LEN=$DEFAULT
LINE=
CL="+"
LL="-"

for i
do
  case $i in
	-[0-9] | -[0-9][0-9] | -[0-9][0-9][0-9]) LEN=`expr $i : '-\(.*\)'`;;
	-s)	SHAR=1;;
	-*)	echo "Usage: wrap [-nnn] [-s] [file]" 1>&2; exit 1;;
	 *)	FILE="$i"; break;;
  esac
done

test \( -z "$SHAR" \) -a \( -n "$FILE" \) &&
			SHAR=`egrep '^# This is a shell archive' $FILE`

if test $LEN -eq 0 
then	echo "Linelength ($LEN) set to default: `expr $DEFAULT + 1`" 1>&2;
	LEN=$DEFAULT
fi

LINE=`yes | sed "
	H
	$LEN {	g
		s/\\n//g
		y/y/./
		q
	}
	d" 2>/dev/null`

cat <<\EOF
: !/bin/sh
# Remove everything before the previous line and pipe through sh.
#
EOF
if test "$SHAR"
then echo "{ sed '"
else echo "sed '"
fi
cat <<EOF
	s/^$LL//
	x
	t last
	/^$CL/ {
		x
		s/^$CL//
		H
	}
	d
  : last
	/^$CL/ {
		x
		H
		s/^.*$//
	}
	x
	s/^$CL//
	s/\n//g
' <<"EOF_CUT"
EOF
#
# ULTRIX sed has buggy code for the t function
#
#sed "
#  : start
#	h
#	s/^\($LINE\)..*/$CL\1/p
#	t large
#	s/^/$LL/
#	b
#  : large
#	g
#	s/^$LINE//
#	t start
#" $FILE
#
sed "
  : start
	h
	s/^\($LINE\)..*/$CL\1/p
	/^$CL$LINE/ !{
		s/^/$LL/
		b
	}
	g
	s/^$LINE//
	b start
" $FILE
echo EOF_CUT
test "$SHAR" && echo '} | sh'
