#!/bin/sh

cbin=/remote/trond/PDL/APipe

logfile=test.log
logfile=`date | awk '{print $6"_"$2"_"$3"_"$4}'`.log

touch tmp1.$$ ; \rm tmp1.$$ ; touch tmp1.$$
echo Scanning:

# check for files which can be merged
for n in `ls  /remote/posiseis/Data/cube-00?/??????/????????.??? ` 
do
# replace ls by ls -tr for files with correct file creation times
# check if filesize > 100000 	
	fs=`ls -alsi $n | awk '{print $7}'`	
	if [ $fs -ge 100000 ]; then
		fno=`$cbin/get_cube_fileno_mc $n`
		echo $n	$fno  >> tmp1.$$		
		echo 0 | awk '{printf"."}'
	fi
done
echo 0 | awk '{printf"\n"}'

# sort into new list:
# put all files of a data stream in one line
awk 'BEGIN {old=0} {if (($2==0) || (($2-old)!=1)) {if (NR>1) printf"\n"} {printf"%s ",$1} old=$2}' tmp1.$$ > tmp2.$$
#awk '{if ($2==0) {if (NR>1) printf"\n"} {printf"%s ",$1} }' tmp1.$$ > tmp2.$$

# conversion loop

nos=`wc tmp2.$$ | awk '{print $1+1}'`

# ini logfile
echo Logfile from `date` > $logfile

i=1
while [ "$i" -le "$nos" ]
do
	echo working on data stream $i of $nos
	echo working on data stream $i of $nos >> $logfile
	file_list=`awk '{if ("'$i'"==NR) print $0}' tmp2.$$`
	((($cbin/cube_merge_mc $file_list ) 3>&1 1>&2 2>&3| tee -a $logfile) 3>&1 1>&2 2>&3) | ((($cbin/pcube2asc_mc -s ) 3>&1 1>&2 2>&3| tee -a $logfile) 3>&1 1>&2 2>&3) | ((($cbin/add_time_mc ) 3>&1 1>&2 2>&3| tee -a $logfile) 3>&1 1>&2 2>&3) | ((($cbin/resamp_mc ) 3>&1 1>&2 2>&3| tee -a $logfile) 3>&1 1>&2 2>&3) | ((($cbin/asc2mseed_mc ) 3>&1 1>&2 2>&3| tee -a $logfile) 3>&1 1>&2 2>&3)
	i=`expr $i + 1`
done

\rm tmp1.$$ tmp2.$$

