#!/bin/bash

DELAY=1
[ $# -gt 0 ] && DELAY=$1

CSI() {
	echo -n -e "\033[$*"
}

# Ensure we return to the default buffer on exit
exit_handler() {
	# Reset to default colors
	CSI "0m"
	# Clear the screen
	CSI "2J"
	# Switch to normal (non-alternate) screen buffer (xterm)
	CSI "?47l"
}
trap exit_handler EXIT

# Switch to alternate screen buffer (xterm)
CSI "?47h"

# Set both colors to black
CSI "30;40m"
# Clear the screen
CSI "2J"
# Set both colors to white
CSI "37;47;1m"

FIRST=1
# Read lines from the standard input
while read X Y COLOR REST ; do
	# If not the first time, remove the @ from the current position
	[ $FIRST -eq 0 ] && echo -n -e " \010"
	FIRST=0
	# If we were given a color, use it
	[ -n $COLOR ] && CSI "3${COLOR};4${COLOR}m"
	# Move the cursor to the given point, and write @ <backspace> there
	CSI "$[$Y +1];$[$X +1]H@\010"
done

# Remove the @
[ $FIRST -eq 0 ] && echo -n -e " \010"

# Sleep a few seconds before exiting, to show the final drawing.
sleep $DELAY
