#!/bin/bash
# SABAMESE - Simple Awk & Bash AMES Extractor
# by Sylwester Arabas, 29.07.2006

# help message
if test ! $1; then
  echo
  echo "usage:"
  echo "  to extract the data: #sabamese input_filename column_no_1 [ : column_no_2 [ :column_no_3 ] ]"; \
  echo "  to list the fields: #sabamese input_filename"; \
  echo
  exit;
fi

# filename command-line option handling
filename=$1

# just show header if only filename is present
if test ! $2; then
  #get the number of variables
  variableno=`head -10 $filename | tail -1 | cut -d"{" -f 1`; \
  head -n `echo 12 $variableno | awk 'BEGIN {RS=" "; sum=0} {sum+=$0} END {print sum}'` $filename | awk 'NR>12 {print "field " NR-12 ":\t" $0}'; \
  exit;
fi

# fieldnums command-line option handling
awkprintf=`echo $2 | awk '
BEGIN {
  FS=":"; 
  printf("printf(")
} 
{
  printf("\"%%d");
  for (i=1; i<=NF; i++) 
    printf("\t%%g");
  printf("\", \$1-zero");
  for (i=1; i<=NF; i++) 
    printf(", \$%d", $i+1);
} 
END {
  printf(")\n")
}
'`
echo $awkprintf

# getting the number of header lines
headlinesno=`head -1 $filename | cut -d' ' -f1`

# parsing the file and outputing the data
awk "BEGIN {zero=0; last=0;} NR>$headlinesno {if (false && zero==0) zero=\$1; else if (last>\$1) zero-=24*60*60; $awkprintf; print \"\"; last=\$1}" $filename
