#!/bin/bash

if [ "$#" != 1 ]; then
  echo "usage: xrep <directory>"
  echo "compress and move all output files into <directory>, then copy the last image into image/<directory>.png"
  exit
fi

if [ -e "$1" ]; then
  echo "sorry, this directory already exists !"
  exit
fi

COM_FILE="comment.txt"
if [ ! -f $COM_FILE ]; then
  vi $COM_FILE
fi

echo "creating $1"
mkdir $1

NB_VEL=$(ls -1 *.vel | wc -l)
if [ $NB_VEL != 0 ]; then
  echo -n "compression of .vel files (y/n) ?"
  read ans
  if [ "$ans" == "y" ] || [ "$ans" == "yes" ]; then
    echo "compressing velocity files"
    gzip *.vel
  fi
fi

LOG_FILE="RESCAL.log"
#PAR_FILE=`grep "\.par" $LOG_FILE | head -1 | awk '{print $5}'`
PAR_FILE=$(grep "param" $LOG_FILE | head -1 | awk '{print $5}')
echo "parameter file: $PAR_FILE"
WIND_FILE=$(grep "Wind_file =" $LOG_FILE | head -1 | awk '{print $3}')
echo "wind file: $WIND_FILE"

echo "compressing data files"
gzip *.bin
gzip *.csp
gzip *.data
gzip *.tar
gzip *.car
#gzip ALTI*.txt
#gzip AUTOCORREL*.txt

echo "moving output files into $1"
mv *.png $1/
mv *.jpg $1/
mv *.jpeg $1/
#mv *.txt $1/
mv $COM_FILE $1/
mv *.log $1/
mv *.out $1/
mv *.bin.gz $1/
mv *.csp.gz $1/
mv *.data.gz $1/
mv *.vel.gz $1/
mv *.car.gz $1/
mv *.vel $1/
mv ReSCAL.tar.gz $1/

echo "copying entry files"
#cp *.m $1/
cp $PAR_FILE $1/
#cp -r ./wind $1/
if [ $WIND_FILE ]; then
  cp -a $WIND_FILE $1/
fi
cp genesis $1/
cp regenesis $1/
#cp rescal $1/
cp rescal*.tar.gz $1/
cp genesis*.tar.gz $1/
#rm -f *.bin 

if [ -e images ]; then
  img=$(ls -1 $1/*.png | tail -1)
  if [ -e "$img" ] && [ ! -f images/$1.png ]; then
    echo "creating $1.png"
    cp $img images/$1.png 
  else
    echo "file images/$1.png already exists"
  fi
fi

echo "done"

