#! /usr/bin/env bash

# Convert csv file $1 to txt.  Works on $1.csv if $1 not found.  With no $1, uses standard input.

# $var:t    ${var##*/}
# $var:h    ${var%/*}
# $var:e    ${var##*.}
# $var:r    ${var%.*}

debug=0

tempbase=/tmp/csv2txt.$$

inputfile=$1

if [[ "$1" != "" ]]; then
  if [[ ! -f $inputfile ]]; then inputfile=$inputfile.csv; fi
  if [[ ! -f $inputfile ]]; then echo
     "csv2txt: $inputfile not found"
     exit 2
  fi
fi
# Thinking about removing sed part of next line.
cat $inputfile | csv2bellsv | sed 's+ +-+g' | tee $tempbase.bsv | awk -F \
  '{for (i=1;i<=NF;i++) {if (length($i)>width[i]) width[i]=length($i)}; if (NF>maxF) maxF=NF;}
   END {width[1]--; for (i=1;i<=maxF;i++) print "{printf \"%"width[i]+1"s\", $"i"}"; print "{print \"\"}";}
  ' > $tempbase.awk
awk -F -f $tempbase.awk $tempbase.bsv

if (( $debug )); then
  exit
fi
rm $tempbase.awk $tempbase.bsv
