#!/usr/bin/mawk -We
# *********************************************************************
# widest: print the max. width of each column in the input table.
# Copyright (c) 2006 Carlo Strozzi
#
# 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; version 2 dated June, 1991.
#
# 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.
#
# *********************************************************************
#  $Id: widest 39 2007-05-02 14:46:09Z carlo $

BEGIN {
  NULL = ""; FS = OFS = "\t"; s = 1; a = A = 0

  # Get local settings.
  nosql_install = ENVIRON["NOSQL_INSTALL"]
  stdout = ENVIRON["NOSQL_STDOUT"]
  stderr = ENVIRON["NOSQL_STDERR"]

  # Set default values if necessary.
  if (nosql_install == NULL) nosql_install = "/usr/local/nosql"
  if (stdout == NULL) stdout = "/dev/stdout"
  if (stderr == NULL) stderr = "/dev/stderr"

  while (ARGV[++i] != NULL) {
     if (ARGV[i] == "-i" || ARGV[i] == "--input") i_file = ARGV[++i]
     else if (ARGV[i] == "-s" || ARGV[i] == "--separator") s=length(ARGV[++i])
     else if (ARGV[i] == "-a" || ARGV[i] == "--add") a = ARGV[++i]
     else if (ARGV[i] == "-r" || ARGV[i] == "--report") report = 1
     else if (ARGV[i] == "-R" || ARGV[i] == "--row") row = 1
     else if (ARGV[i] == "-H" || ARGV[i] == "--include-header") with_hdr = 1
     else if (ARGV[i] == "-N" || ARGV[i] == "--no-header") no_hdr = 1
     else if (ARGV[i] == "-h" || ARGV[i] == "--help") {
	system("grep -v '^#' " nosql_install "/help/widest.txt")
	exit(rc=1)
     }
     else if (ARGV[i] == "--show-copying") {
	system("cat " nosql_install "/doc/COPYING")
	exit(rc=1)
     }
     else if (ARGV[i] == "--show-warranty") {
	system("cat " nosql_install "/doc/WARRANTY")
	exit(rc=1)
     }
  }

  ARGC = 1					# Fix argv[]

  if (i_file != NULL) { ARGV[1] = i_file; ARGC = 2 }
}

#
# Main loop
#

NR == 1 {
   if (!no_hdr && !row) print
   if (!with_hdr) next
   gsub(/\001/,"")			# exclude SOH chars from count.
}

{ for (i=1; i<=NF; i++) if ((l=length($i)) > L[i]) L[i] = l }

NR > 1 && !row && report { print }

END {
   if (rc) exit(rc)

   if (row) {
      for (i in L) tot += L[i]
      printf("%d\n",tot+NF*s-s+a)
   }
   else {
      if (!no_hdr && report) {
	 gsub(/[^\t]*/,"-")
	 print
      }
      for (i=1; i<=NF; i++) {
	  if (i==NF) s=0
	  printf("%d", L[i]+s+a)
	  if (i<NF) printf("\t")
      }
      printf("\n")
   }
}

# End of program.
