#!/bin/csh
#++++++++++++++++
# Copyright:    (C) 2008-2016 UDS/CNRS
# License:       GNU General Public License
#.IDENTIFICATION reshape
#.LANGUAGE       C-shell
#.AUTHOR         Francois Ochsenbein [CDS]
#.ENVIRONMENT    
#.KEYWORDS       
#.VERSION  1.0   18-Oct-1996
#.VERSION  1.1   11-Mar-1998: Allow combination of lr's
#.PURPOSE        Right-align a file assumed to have a fixed number of columns.
#.COMMENTS       Input file either as argument, or standard input
#----------------

## Some help...
while ("$1" =~ -*)
  switch("$1")
  case "-[lr]*"
    set tabdef = `echo "$1" | cut -c2-`
    set verdef = `echo "$tabdef" | tr -d lr`
    if ($#verdef > 0) then
      echo "****Column definition '$1' not made only of l and r's"
      goto show_help
    endif
    breaksw
  show_help:
  default:
    echo "Usage: $0 [-lr...] [file]"
    echo "  -[lr...] indicates the alignment of colums: l for left, r for right"
    echo "         (Example: lllr for 4 columns, 3 left then right)"
    echo "         The defaut is right-alignment,"
    echo "  The program assumes a file with a constant number of columns"
    echo "  and it realigns the columns"
    exit 1
  breaksw
  endsw
  shift
end

set tt = /tmp/Rs$$	# Temporary file name

## Remove contiguous, heading, trailing blanks, into a temporary file
sed 's/  */ /g' $* | sed 's/^ //' | sed 's/ *$//' > $tt.dat

### Compute the max length of each field
if ($?tabdef) then	# Columns Specified
  awk 'BEGIN{t="'$tabdef'"; m=length(t)}\
    {for (i=1;i<=NF;i++) { l=length($i); if (l>s[i]) s[i]=l}} \
    END{for (i=1; i<=m; i++) \
	printf("-i -f%d%s%d%s\n", i,"%",s[i],substr(t,i,1))}\
  ' $tt.dat > $tt.col
else
  awk '{if(m<NF)m=NF; for (i=1;i<=NF;i++) { l=length($i); if (l>s[i]) s[i]=l}} \
    END{for (i=1; i<=m; i++) \
	printf("-i -f%d%s%d%s\n", i,"%",s[i],substr(t,i,1))}\
  ' $tt.dat > $tt.col
endif

### Reshape the file
acut -d" " `cat $tt.col` $tt.dat | tr '\11' ' '

### Delete temporary files
rm -f $tt.*
exit 0
##############################################################
