#!/bin/bash
# cut a file in smaller bits
file=$1
bits=$2
base=${1/.txt/}
nl="`wc -l $file | cut -f1 -d" "`"
output=$base-cells.txt
rm -rf $output
touch $output

echo Cutting $file, $nl lines in bits of $bits lines, output to $output \( one bit per line \)

prev=1
index=1

while [ $index -lt $nl ]; do
  echo -n "$index..."
  index=`expr $index + $2`
  prevm=`expr $prev - 1`
  nt1=/tmp/$base-$prev-$index-1.txt
  nt2=/tmp/$base-$prev-$index-2.txt
  cmd="1,"$prevm"d"
  cmd2="101,"$nl"d"
  if [ $prevm -gt 0 ]; then
    sed $cmd $file > $nt1
    if [ $index -lt $nl ]; then
      sed $cmd2 $nt1 > $nt2
    else
      sed $cmd $file > $nt2
    fi
    sed -n -f all-on-one-line.sed $nt2 >> $output
  else
    sed $cmd2 $file > $nt1
    sed -n -f all-on-one-line.sed $nt1 >> $output
  fi
    echo "done"
  prev=$index
done

rm -rf /tmp/$base-*.txt
