#!/bin/bash
#
# Converts output from the gcodetools extension for Inkscape into
# a usable format for an FSE laser cutter/engraver.
#
# TODO: Allow line width to control spindle speed/velocity
# TODO: Use 'better' gcodes like E* or something else to handle
#       activating the laser after it's in motion.
#
# Matti Kariluoma Nov 17 2010 <matti.kariluoma@gmail.com>
DATA=""
SPINDLE=0
VELOCITY=1000

if readlink /proc/$$/fd/0 | grep -q "^pipe:"; then
  # echo "Pipe input:"
  if  [ $# -lt 2 ]; then
    echo "usage: spindle_speed movement_speed"
    exit 1
  fi
  if ! [[ "$1" =~ ^[0-9]+([.][0-9]+)?$ ]] ; then
    echo "spindle_speed must be an integer or decimal."
    exit 1
  fi
  if ! [[ "$2" =~ ^[0-9]+([.][0-9]+)?$ ]] ; then
    echo "movement_speed must be an integer or decimal."
    exit 1
  fi
  DATA=$(cat)
  SPINDLE=$1
  VELOCITY=$2
elif file $( readlink /proc/$$/fd/0 ) | grep -q "character special"; then
  # echo "Standard input:"
  if  [ $# -lt 3 ]; then
    echo "usage: $0 gcode_file spindle_speed movement_speed"
    exit 1
  fi
  if ! [ -e $1 ]; then
    echo "File \"$1\" does not exist!"
    exit 1
  fi
  if ! [[ "$2" =~ ^[0-9]+([.][0-9]+)?$ ]] ; then
    echo "spindle_speed must be an integer or decimal."
    exit 1
  fi
  if ! [[ "$3" =~ ^[0-9]+([.][0-9]+)?$ ]] ; then
    echo "movement_speed must be an integer or decimal."
    exit 1
  fi
  DATA=$(cat $1)
  SPINDLE=$2
  VELOCITY=$3
else
  # echo "File input:"
  if  [ $# -lt 2 ]; then
    echo "usage: spindle_speed movement_speed"
    exit 1
  fi
  if ! [[ "$1" =~ ^[0-9]+([.][0-9]+)?$ ]] ; then
    echo "spindle_speed must be an integer or decimal."
    exit 1
  fi
  if ! [[ "$2" =~ ^[0-9]+([.][0-9]+)?$ ]] ; then
    echo "movement_speed must be an integer or decimal."
    exit 1
  fi
  DATA=$(cat)
  SPINDLE=$1
  VELOCITY=$2
fi

if [ "$SPINDLE" -lt 0 ]; then
  echo "spindle_speed must be > 0"
  exit 1
fi
if [ "$SPINDLE" -gt 1000 ]; then
  echo "spindle_speed must be < 1000"
  exit 1
fi
if [ "$VELOCITY" -lt 80 ]; then
  echo "movement_speed must be > 80"
  exit 1
fi
if [ "$VELOCITY" -gt 2000 ]; then
  echo "movement_speed must be < 2000"
  exit 1
fi

echo "$DATA" | sed -e 's/[G0 ]*Z[-]*[0-9][0-9]*\.[0-9]*//' -e 's/G01 F[0-9]*\.[0-9]*//' -e 's/M3//' -e 's/M5//' -e '/G00 X0[0]*\.[0]* Y0[0]*\.[0]*/ d' | \
  sed -e '/G00 X[0-9]*\.[0-9]* Y[0-9]*\.[0-9]*/ {
    a\
S'$SPINDLE'
    a\
M3
    i\
M5
}' -e '/M2/ {
    i\
M5
    i\
G00 X0.000000 Y0.000000
}' -e 's/F[0-9]*\.[0-9]*/F'$VELOCITY'/'


