#!/bin/bash

# convert dlm file to json 
# quotes are removed from dlm before converting to json
#
# dlm2json [-d DFS] {-k} {-h} dlmfile .. (or pipe)
# 
#-----------------------------------------------------------------------
DFS="\t"; BLANK=1; HELP=;
#-----------------------------------------------------------------------
TF="OUT_dlm2json"
trap "[ -e $TF ] && rm $TF" EXIT
#-----------------------------------------------------------------------

while getopts d:kh OPTVAL 
do
    case $OPTVAL in
	d) DFS=$OPTARG;;
	k) BLANK=;;
        h) HELP=1;;
        *) echo "dlm2json -h for help"; exit -1;;
    esac
done
shift $((OPTIND-1))

if [ $HELP ]; then
  echo "dlm2json [-d DFS] {-h}   file.dlm ... (or pipe)"
  echo '-d DFS, delimiting character for input table ["\t"]'
  echo "-k keep leading and trailing blanks"
  echo "convert dlm file to json file"
  exit
fi

#-----------------------------------------------------------------------
# check to see if data is being supplied by pipe
#-----------------------------------------------------------------------

case $# in
    0) if [ -p /dev/stdin ]; then
          set -- "/dev/stdin"                     #set $1=/dev/stdin
        else
          echo "no file given nor is there a trailing pipe"
          exit -1;
       fi
       cat $1 > $TF; IF=$TF;;
    1) IF=$1;;
    *) echo "can accept only one file"; exit -1;;
esac

#-----------------------------------------------------------------------
# The big lift
#-----------------------------------------------------------------------

awk -F "$DFS" 'BEGIN{q="\""; print "["}
     NR==1{nf=NF
           for (i=1;i<=nf;i++){
             gsub(/"/,"")
             if (BLANK){sub(/^ */,"",$i); sub(/ *$/,"",$i)}
             hdr[i]=$i}
          }
     NR>1 {if (length(notlast)>0){print ","}; notlast=1
           printf " {"
           for (i=1;i<=nf;i++){
             gsub(/"/,"")
             if (BLANK){sub(/^ */,"",$i); sub(/ *$/,"",$i)}
             if (i<nf){
               printf("%c%s%c:%c%s%c,",q,hdr[i],q,q,$i,q)}
             else
               printf("%c%s%c:%c%s%c}",q,hdr[i],q,q,$i,q)
           }
          }
     END{printf "\n]\n"}' BLANK=$BLANK $IF
