#!/bin/bash

# Does the following operations on the files passed as arguments:
#  - Remove trailing space from lines
#  - Remove trailing blank lines
#  - Remove/convert DOS-style line breaks
#  - Expand tabs to spaces with a tabspace of 8

# I once had an error where the conversion had an error (the computer
# didn't have dos2unix), resulting in the converted files being empty.
# The result was that every file got replaced by an empty file! That
# was not so nice, so this script stops operation as soon as any error
# occurs, and it also checks that only space has been changed before
# it overwrites the original file with a space-fixed version.

for f in $*; do echo $f;

  tr -d '\r' < $f > __spaceTmp0;
  if [ $? != 0 ]; then echo "There was an error removing DOS-style line breaks."; exit 1; fi;

  expand -4 < __spaceTmp0 > __spaceTmp1;
  if [ $? != 0 ]; then echo "There was an error expanding tabs."; exit 1; fi;

  sed 's/[[:blank:]]*$//g' < __spaceTmp1 > __spaceTmp2;
  if [ $? != 0 ]; then echo "There was an error eliminating trailing space from lines."; exit 1; fi;

  # Make completely sure that we only changed the spaces
  diff -EbwB -q $f __spaceTmp2;
  if [ $? != 0 ]; then echo "There was an error. Conversion not confirmed correct."; exit 1; fi;

  sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' < __spaceTmp2 > __spaceTmp3;
  if [ $? != 0 ]; then echo "There was an error eliminating trailing blank lines."; exit 1; fi;

  # We have to do diff twice, because diff will not ignore trailing
  # lines that consist only of spaces. It will ignore changes to space and removal of
  # completely empty lines, so if we do it twice we get the right thing.

  # Make completely sure that we only changed the spaces
  diff -EbwB -q __spaceTmp2  __spaceTmp3;
  if [ $? != 0 ]; then echo "There was an error. Conversion not confirmed correct."; exit 1; fi;

  diff -q $f __spaceTmp3 1>/dev/null;
  if [ $? != 0 ]; then
    mv -f __spaceTmp3 $f;
    if [ $? != 0 ]; then echo "There was an error moving fixed file into place."; exit 1; fi;
    echo "Fixed space issue for $f."
  fi

  rm -f __spaceTmp0 __spaceTmp1 __spaceTmp2 __spaceTmp3;
  if [ $? != 0 ]; then echo "There was an error removing temporary files."; exit 1; fi;
done;
