#!/bin/bash

# MultiSpace2Comma.bash
# Fri Mar 12 14:22:19 PST 2010
# Chieh Cheng
# http://www.CynosureX.com/

# GNU General Public License (GPL) Version 2, June 1991

  scriptDir=`dirname "$0"`
  scriptName=`basename "$0"`

function process ()
{
  for file
  do
    if [ "${file}" = "-" ]
    then
      processStdIn
    else
      processFile "${file}"
    fi
  done
}

function processFile ()
{
  file="$1"

  if [ -f "${file}" ]
  then
    cat "${file}" | sed 's/   */,/g'
  else
    # send error to stderr
    echo "${file} does not exist!" >&2
  fi
}

function processStdIn ()
{
  tempFile=`GetTempPathName.ksh "${scriptName}"`

  while read line
  do
    echo "${line}" >> "${tempFile}"
  done

  processFile "${tempFile}"
    
  rm "${tempFile}"
}

function usage ()
{
  echo "  Usage:   ${scriptName} \"file 1\" [ . . . \"file N\" ]"
  echo
  echo "             You may substitute '-' in place of a file to read from STDIN."
}

  if [ $# -gt 0 ]
  then
    process "$@"
  else
    usage
  fi
