#! /bin/csh -f

set usage = "$0 [-reverse] INI FIN < INFILE > OUTFILE"

# Extracts from a INFILE which may be .flc, .fla, flv, .fcv, .cvc, etc.)
# the samples for a segment with range INI..FIN.
# Handles wrap-around cases properly.
# If "-reverse" is specified, reverses the order
# of the samples (but does not complement them).

if ( "x$1" == "x-reverse" ) then
  set sortdir = "r"; shift
else
  set sortdir = ""
endif

if ( $#argv != 2 ) then
  echo "usage: ${usage}"; exit 1
endif

set ini = "$1"; shift;
set fin = "$1"; shift;

set tmp = "/tmp/$$"
set eln = "/tmp/$$.end"

/bin/cat \
  | /n/gnu/bin/gawk \
      -v ini="${ini}" -v fin="${fin}" \
      -v tmp="${tmp}" -v eln="${eln}" \
      ' BEGIN{ k=0; ni=999999; } \
        /^samples =/ { \
          ni = $3; ini=ini%ni; fin=fin%ni; \
          no=(fin-ini+ni)%ni+1; \
          printf "ini = %d fin = %d\n", ini, fin > "/dev/stderr"; \
          printf "samples = %d\n", no; next; \
        } \
        / = / { print; next; } \
        /^(begin |[|])/ { print; next; } \
        /^end / { print $0 > eln; next; } \
        /./ { \
          if(ini < fin) { ok = ((ini <= k)&&(k <= fin)); } \
          else { ok = ((k <= fin) || (k >= ini)); } \
          if(ok) { printf "%6d %s\n", (k-ini+ni)%ni, $0 > tmp; } \
          k++; next \
        } \
      '
/bin/cat ${tmp} \
  | sort +0 -1n${sortdir} \
  | sed -e 's/^.......//g' \

/bin/cat ${eln}

/bin/rm -f ${tmp} ${eln}