#!/bin/bash

# This example requires bash.

[ -z $GTKDIALOG ] && GTKDIALOG=gtkdialog

# Gtkdialog is a C program and the C library will execute a system command
# using /bin/sh so we need to make sure that bash executes any commands.
# Ubuntu users whose /bin/sh links to dash should take note of this fact.
USE_BASH=; [ "`readlink /bin/sh`" != bash ] && USE_BASH="bash -c "

# Tech-Tech by SFR'2013
# GPLv2 applies
# Req: Gtkdialog >=0.8.0, Bash

TEMPDIR=/dev/shm/tech-tech_$$
mkdir $TEMPDIR
trap 'rm -rf $TEMPDIR' EXIT

export PIC=$TEMPDIR/pic.svg
export SINUS=$TEMPDIR/sinus_table
export LINES=$TEMPDIR/lines

: > $SINUS
# Create sinus table
for i in {0..63}; do
  RAD=$(echo "$i*(3.14/32)" | bc -l)
  VAL=$(printf "%.0f" $(echo "s($RAD) * 12" | bc -l))
  echo $VAL >> $SINUS
done

# Convert bitmap (stripped xpm) to SVG's "stroke-dasharray" attributes
cnt=1;curline=0
while read LINE; do
  L[$curline]="0"
  for a in `seq 0 $((${#LINE}))`; do
    [[ "${LINE:$a:1}" != "${LINE:$(($a+1)):1}" ]] && L[$curline]=${L[$curline]}",$cnt" && cnt=1 || ((cnt++))
  done
  ((curline++))
done << EOF
[encoded data, 8995 characters]
EOF

echo ${L[@]} > $LINES
# -----------------------------------------------------------------------------

techtech () {
L=( $(<$LINES) )
SIN=( $(<$SINUS) )

echo '<svg width="256" height="64">' > $PIC
#for a in `seq 0 $((${#L[@]}-1))`; do
for ((a=0; a<${#L[@]}; a++)); do
  echo '<line x1="'${SIN[$a]}'" y1="'$(($a+16))'" x2="'$((512+${SIN[$a]}))'" y2="'$(($a+16))'" stroke-dasharray="'${L[$a]}'" stroke="black" stroke-width="2" />' >> $PIC
done
echo '</svg>' >> $PIC

echo ${SIN[63]} ${SIN[@]:0:63} > $SINUS

}
export -f techtech

export MAIN='
<window title="Tech-Tech" resizable="false">
  <pixmap>
    <variable>PICTURE</variable>
    <input file>'$PIC'</input>
  </pixmap>
  <timer visible="false" milliseconds="true" interval="50">
    <action>'$USE_BASH'techtech</action>
    <action>refresh:PICTURE</action>
  </timer>
<action signal="hide">exit:abort</action>
</window>
'

case $1 in
	-d | --dump) echo "$MAIN" ;;
	*) $GTKDIALOG -cp MAIN ;;
esac
