#!/bin/csh -f
# Find column numbers delimiting the column with the heading specified
# as an argument (cannot contain spaces).  Always examines standard input.
# Assumes no line is more than 1000 characters longer than the first line,
# which is the one containing the headers; when the argument does not
# appear as a header, the column numbers are set to be beyond that threshhold.

set complement = 0
if ($#argv > 0) then
  if ("$argv[1]" == "-v") then
    set complement = 1
    shift
  endif
endif

if ($#argv < 1) then
  echo "Usage: findcol [-v] colname"
  exit 1
endif

cat | head -n 1 | \
 awk '{linelen=length($0); \
       for (colbeg=1; colbeg<=linelen; colbeg=colend) { \
          for (nmbeg=colbeg; nmbeg<=linelen && substr($0,nmbeg,1)==" ";)\
             nmbeg++; \
          for (colend=nmbeg; colend<=linelen && substr($0,colend,1)!=" ";)\
             colend++; \
          if (nmbeg<=linelen) if (substr($0,colbeg,colend-colbeg)~/^ *'"$1"'$/)\
                                break; \
          } \
       if (! '$complement') { \
          if (colbeg>linelen) print colbeg+1000, colbeg+1000 \
          else print colbeg, colend-1 \
          } \
       else { \
          if (colbeg>linelen) print 1, linelen \
          else if (colbeg == 1) print colend, linelen \
               else print colend, colbeg-1; \
          } \
      }'
