#!/bin/sh
if [ "$1" = "-m" ]; then
	shift;
	CODES="4:7:1:1"
else
	if [ "$CDIFFCOLORS" != "" ]; then
		CODES=$CDIFFCOLORS
	else
		CODES="1:34:31:35"
	fi
fi
(if [ "$1" != "" ]; then
    while [ "$1" != "" ]; do
        case $1 in
        *.bz2)
            cat="bzcat"
            ;;
        *)
            cat="zcat -f"
            ;;
        esac
    	case $1 in
    	http:*|https:*|ftp:*|file:*)
            if [ -z "$CDIFF_FETCH" ]; then
                # Wget doesn't do file:// URLs... :(
                if which curl >/dev/null 2>&1; then
                    CDIFF_FETCH="curl -s"
                elif which lwp-request >/dev/null 2>&1; then
                    CDIFF_FETCH="lwp-request -m GET"
                fi
                if [ -z "$CDIFF_FETCH" ]; then
                    echo "Error: no program to fetch from URLs found."
                    exit 1
                fi
            fi
            $CDIFF_FETCH $1 | $cat
	    ;;
    	*)
            $cat $1
	    ;;
        esac
	shift;
    done
else
	cat
fi) | perl -p -mconstant=CODES,${CODES} -e '
no warnings qw(utf8);
($at, $m, $p, $c) = split /:/, CODES;
while (s/\t/" " x (8 - ((length($`)-1) % 8))/e) {}
s/^(\+.*)$/\033[${p}m$1\033[0m/o;
s/^(-.*)$/\033[${m}m$1\033[0m/o
	if !s/^(--- \d+,\d+ ----.*)$/\033[1m$1\033[0m/o;
s/^(\*\*\* \d+,\d+ *\*\*\*.*)$/\033[1m$1\033[0m/o;
s/^(\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*)$/\033[1m$1\033[0m/o;
s/^(!.*)$/\033[${c}m$1\033[0m/o;
s/^(@@.*$)/\033[${at}m$1\033[0m/o;
if (/^1.(\d+)(\s+\(\w+\s+\d{2}-\w{3}-\d{2}\):\s)(.*)/) {
	$lastcol = $lastcol || 0;
	$lastcol++ if defined($lastrev) && $lastrev != $1;
	$lastrev = $1;
	$lastcol %= 6;
	$_ = "\033[3" . ($lastcol + 1) . "m1.$1$2\033[0m$3\n";
}
' | less -R
