#!/usr/bin/perl -w

#  Copyright 2008 Google Inc.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

use strict;
use Getopt::Long;
use Text::CSV;
use FileHandle;

my ($h, $d, $i, $o);

$d = $ENV{DELIMITER} || chr(0xfe);

&GetOptions("help"     => \$h,
            "delim=s"  => \$d,
            "output=s" => \$o,
           );

if ($h) {
  print STDERR <<__USAGE__;

converts a csv file to delimited format.

usage: $0 [-d <delim>] [--output <outfile>] [infile ...]

Options:
  -d, --delim <D>   use D as the field separator for output (default: )
  -o, --output <F>  use F as the output file (default: stdout)

__USAGE__

  exit(1);
}

my $fhout;
if ($o) {
  open(OUT, "> $o") or die "$0: $o: $!\n";
  $fhout = \*OUT;
} else {
  $fhout = \*STDOUT;
}

my $csv = Text::CSV->new();
while (<>) {
  $csv->parse($_);
  @_ = $csv->fields();
  print $fhout join($d, @_), "\n";
}

exit(0);
