#!/bin/csh -f
#
# This script assumes that a mount to adcp data has been setup and files are named like
# /local/users/pstar/Acoustics/OS75kHz/raw_data/OS075_DY039004_000000.ENR  
# /local/users/pstar/Acoustics/OS150kHz/raw_data/OS150_DY039002_000000.LOG
# Works on dy039 might may need to modify on next cruise
#
# Go through loop once for each adcp
foreach adp ('75' '150')
  cd /local/users/pstar/cruise/data
  cd va$adp
  if ($adp == '75') then  
	  set adpx = '075'
	  echo $adpx
  else if ($adp == '150') then
	  set adpx = '150'
	  echo $adpx
  endif  

  echo "Synchronising raw data for the v$adp"
#  rsync -av /local/users/pstar/Acoustics/OS${adp}kHz/raw_data/OS${adpx}* rawdata
  rsync -av /mnt/adcp${adp}/JC145/raw_data/OS* rawraw

# --------------------------------------------------
# These next steps were needed as nameing of files was not correct and need to add an extra underscore
  cd rawdata
  foreach fl (`ls ../rawraw/*`)
    #set aa = `echo $fl | awk '{print substr($1,11,11)}'`
    set aa = `echo $fl | awk '{print substr($1,11,length($1)-24)}'`
    #set bb = `echo $fl | awk '{print substr($1,22,14)}'`
    set bb = `echo $fl | awk '{print substr($1,length($1)-13,length($1))}'`
    set fl2 = ${aa}_${bb}
    echo $fl
    echo $fl2
    if (! -e $fl2) then
      ln -s $fl $fl2
    endif
  end
  cd ..
# --------------------------------------------------

  echo "Creating directories for OS$adp"
  foreach i (`ls rawdata/*`)
    set num = `echo $i | awk -F'_' '{print substr($3,length($3)-2,3)}'`
# Extract file extension, e.g. for i = rawdata/OS150_DY039005_000000.ENX, num = 'ENR'
    set fname = `echo $i | awk '{print substr($1,9,26)}'`
    set movedir = rawdata{$num}

# Create new directory like 'rawdataENX' if does nto already exist
   if (! -e $movedir) then
     echo making $movedir
     mkdir $movedir
   endif

# Now create links from new directories to original files in rawdata with corresponding suffix
   set rfile = ../${i}
   set lfile = ${movedir}/${fname}
   if (! -e ${lfile}) then
     echo linking ${lfile} to ${rfile}
     ln -s ${rfile} ${lfile}
   endif
   end
end