#!/usr/bin/env bash

# FROM 2/21/11: APPARENTLY WORKS FOR CSV FILES WITH NO COMMAS INSIDE A FIELD

# Usage: csv2tex fileroot [separator]

# Fileroot is the given file name with any extension stripped.  So you
# get the same behavior from "csv2tex foo" or "csv2tex foo.csv".
# Separator defaults to comma.

if [[ $# -lt 1 ]]; then
    echo "Usage: csv2tex fileroot [separator]"
    exit 2
fi

if [[ $# -lt 2 ]]; then
    separator=','
else
    separator=$2
fi

fileroot=${1%.*}

sed "s+[#$%&_^{}]+\\\\&+g
     s+$separator+\&+g" $fileroot.csv | awk -F'&' '{if (NR==1) print "\\begin{longtable}{|*{"NF"}{c|}}\\hline "$0"\n\\\\\\hline\\endhead"; else print $0 "\n\\\\\\hline"}\
                                                   END {print "\\end{longtable}"}'
