#!/bin/tcsh


# path to executable
set cbin = /remote/trond/PDL/APipe

# check for files which can be merged
touch list ; \rm list ; touch list
echo Scanning:
#foreach c ( 601 605 636 638 652 654 656 658 666 668 670 673 675 677 679 787 854 856 858 860 604 635 637 651 653 655 657 665 667 669 671 674 676 678 714 788 855 857 859 861 )
#foreach c ( 787 861 635 714 666 859  )
foreach c ( 787  )

echo DIR=$c
foreach n ( `ls /remote/kirgisien/Bishkek14/data/$c/14????/????????.$c ` )
# replace ls by ls -tr for files with correct file creation times
# check if filesize > 1000 
	set fs = `ls -alsi $n | awk '{print $7}'`
	if ( $fs > 1000 ) then
		set fno = `$cbin/get_cube_fileno_mc $n`	
		echo $n	$fno  >> list
		echo 0 | awk '{printf"."}'
	endif
end
echo 0 | awk '{printf"\n"}'
end


# 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}' list >! list2

#awk '{if ($2==0) {if (NR>1) printf"\n"} {printf"%s ",$1} }' list >! list2



# conversion
# IMPORTANT
# if you have CUBES with data streams including large (>1day) GPS reception gaps 
#     add option -s to $cbin/pcube2asc_mc
# if you have CUBES moved significantly (> 1 degree) during data acquisition (what you should NOT have done anyway!)
#     add option -m to $cbin/pcube2asc_mc
# very minor time shifts (a few 100 mks) might occur

set nos = `wc list2 | awk '{print $1+1}'`

set i = 1
while ( $i <= $nos )
 echo working on data stream $i/$nos
 set file_list = `awk '{if ("'$i'"==NR) print $0}' list2`
echo $file_list
 $cbin/cube_merge_mc $file_list | $cbin/pcube2asc_mc  | $cbin/add_time_mc | $cbin/resamp_mc | $cbin/asc2mseed_mc -v
# $cbin/cube_merge_mc $file_list | $cbin/pcube2asc_mc -c | $cbin/gps_check_mc | $cbin/add_time_mc | $cbin/resamp_mc | $cbin/asc2mseed_mc -v
# $cbin/cube_merge_mc $file_list | $cbin/pcube2asc_mc -t >! $nos.time 
# $cbin/cube_merge_mc $file_list | $cbin/pcube2asc_mc -g >! $i.gps 
# $cbin/cube_merge_mc $file_list | $cbin/pcube2asc_mc -m -t -f $i.log 
 set i = `echo $i | awk '{print $1+1}'`
end

#\rm list list2

