#! /usr/bin/env bash

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

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

inputfile=$1

if [[ "$1" != "" ]]; then
  if [[ ! -f $inputfile ]]; then inputfile=$inputfile.csv; fi
  if [[ ! -f $inputfile ]]; then echo
     "csv2html: $inputfile not found"
     exit 2
  fi
fi
cat $inputfile | csv2bellsv | awk -F \
  'BEGIN {print "<table id=\"'${inputfile%.*}'\">";}
   NR==1 {printf "<thead><tr>"; for (i=1;i<=NF;i++) printf "<th>"$i"</th>"; print "</tr></thead>"; print " <tbody>";}
   NR>1 {printf " <tr>"; for (i=1;i<=NF;i++) printf "<td>"$i"</td>"; print "</tr>";}
   END {print " </tbody>"; print " </table>";}
  ' | bellsv2csv
