#!/bin/bash

RM_CTRL_CHR_CMD=`basename $0`
RM_CTRL_CHR_REPEAT=20
i=0
j=0


if [ $# -ne 1 -o ! -f "$1" ]; then
  echo "Usage: $RM_CTRL_CHR_CMD file" 1>&2
  exit 1
fi

cp $1 $1.tmp.a$i

sed 's/.*\x0D\([^$]\)/\1/g' $1.tmp.a$i > $1.tmp.a`expr $i + 1`
rm -f $1.tmp.a$i
i=`expr $i + 1`
sed 's/\x0D//g' $1.tmp.a$i > $1.tmp.a`expr $i + 1`
rm -f $1.tmp.a$i
i=`expr $i + 1`
sed 's/\x07//g' $1.tmp.a$i > $1.tmp.a`expr $i + 1`
rm -f $1.tmp.a$i
i=`expr $i + 1`
sed 's/\x1B\[K//g' $1.tmp.a$i > $1.tmp.a`expr $i + 1`
rm -f $1.tmp.a$i
i=`expr $i + 1`
sed 's/\x1B]0;//g' $1.tmp.a$i > $1.tmp.a`expr $i + 1`
rm -f $1.tmp.a$i
i=`expr $i + 1`
sed 's/\x1B\[\([0-9]\{2\}\)\{0,1\}\(;[0-9]\{2\}\)\{0,1\}m//g' $1.tmp.a$i > $1.tmp.a`expr $i + 1`
rm -f $1.tmp.a$i
i=`expr $i + 1`

mv $1.tmp.a$i $1.tmp.b0

for j in `seq 0 $RM_CTRL_CHR_REPEAT`; do
  sed 's/[^\x08]\{'$j'\}\(\x08*\)\x1B\['$j'P/\1/g' $1.tmp.b$j > $1.tmp.b`expr $j + 1`
  rm -f $1.tmp.b$j
done

mv $1.tmp.b`expr $RM_CTRL_CHR_REPEAT + 1` $1.tmp.c0

for j in `seq 0 $RM_CTRL_CHR_REPEAT`; do
  sed 's/[^\x08]\x08//g' $1.tmp.c$j > $1.tmp.c`expr $j + 1`
  rm -f $1.tmp.c$j
done
mv -f $1.tmp.c`expr $RM_CTRL_CHR_REPEAT + 1` $1


unset RM_CTRL_CMD
unset RM_CTRL_CHR_REPEAT
unset i
unset j
