#!/usr/bin/mawk -We
# *********************************************************************
#  Written by and copyright Carlo Strozzi <carlos@linux.it>.
#
#  tabletotbl: converts a NoSQL table into tbl(1) directives.
#  Copyright (C) 1999-2001 Carlo Strozzi <carlos@linux.it>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#  2001-01-03 Ported to NoSQL v3
#
# *********************************************************************
#
#  Usage: tabletotbl [-f|--format specs]
#
#  Example: tabletotbl < table | groff -P-f -t -Tlatin1
#
# *********************************************************************

# $Id: tabletotbl,v 1.1.1.1 2003/03/17 09:49:20 carlo Exp $

BEGIN {
  NULL = "" ; FS = OFS = "\t"

  while ( ARGV[++i] != NULL ) {
    if (ARGV[i] == "-f" || ARGV[i] == "--format") {
       fmt = ARGV[++i] ; split(fmt, F, ",")
    }
    else if (ARGV[i] == "-i" || ARGV[i] == "--input") i_file = ARGV[++i]
    else if (ARGV[i] == "-o" || ARGV[i] == "--output") o_file = ARGV[++i]
  }

  ARGC = 1					# Fix argv[]

  if (o_file == NULL) o_file = "/dev/stdout"
  if (i_file != NULL) { ARGV[1] = i_file; ARGC = 2 }

  # Print table-start request.
  printf(".TS\n") > o_file
}

NR == 1 {
  # Output justification defaults to "left".
  for (i = 1; i <= NF; i++) {if (F[i] == NULL) F[i] = "l"}

  # Print table header, in tbl(1) format.

  # Print header specs.
  printf("|") > o_file
  for (i = 1; i <= NF; i++) printf(" c |") > o_file
  printf("\n") > o_file

  # Print body specs.
  printf("|") > o_file
  for (i = 1; i <= NF; i++) printf(" %c |", F[i]) > o_file
  printf(".\n_\n") > o_file

  # Print column names.
  printf("%s\n_\n", $0) > o_file
}

NR > 2 {
  # Escape backslashes and leading dots. Escape also those 
  # characters that are special to tbl(1) if found at the 
  # beginning of a line.

  gsub(/\\/, "\\\\e")			# backslash
  sub(/^\./, "\\[char46]")		# leading dot
  sub(/^_/, "\\_")			# underscore
  sub(/^=/, "\\=")			# equal sign

  print " " $0 > o_file
}

# Print table-end request.
END { printf("_\n.TE\n") > o_file }

#
# End of program.
#
