#get .3d file contents using survex parser
# Is this in any way related to the data incaves-tabular.html by Radost ??
>&2 echo "Processing: $1"

summary=$(cavern "./$1/$1.svx" -o "./$1/$1.3d")
contents=`dump3d -d ./$1/$1.3d`

if [[ "$2" = "--verbose" ]]; then
    echo "Processing file: ./$1/$1.3d" 
fi

#find most recent leg
lastdate=$(echo "$contents" | grep ^LINE | rev | cut -f1 -d " " | rev | grep [1234567890.-] | sort | tail -n1)

if [[ "$2" = "--verbose" ]]; then
    echo "Cave last visited on: $lastdate"
fi

#find all legs done most recently
lastlegs=$(echo "$contents" | grep ^LINE | grep "$lastdate")

#find last survey full name
lastsurvey=$(echo "$lastlegs" | grep -o '\[.*\]' | sort | uniq | tr -d "[" | tr -d "]" | tail -n1)

#find last survey name
lastsurvey=$(echo "$lastsurvey" | rev | cut -f1 -d "." | rev)

#find deepest point of most revent survey
lastdepth=$(echo "$lastlegs" | cut -f4 -d " " | tr -d "m" | sort -n | tail -n1)

#find file containing last survey
lastfile="./"$(grep -ril "begin ****$lastsurvey" "$1" | tail -n1)

#display results
if [[ "$2" = "--verbose" ]]; then
    echo "Last visit on survey name:"
    echo "$lastsurvey"
    echo "Located in the file:"
    echo "$lastfile"
fi

#find team members of last survey
visitors=$(cat "$lastfile" | grep team | cut -f2- -d " " | tr "\n" "\t")

#find total length from summary
leng=$(echo "$summary" | grep "Total length of survey legs" | tr -s " " |cut -f7 -d " ")

#find vertical span from summary
vert=$(echo "$summary" | grep "Vertical range" | cut -f4 -d " ")

#renaming
cavename="$1"
cavedepth="$vert"
cavelength="$leng"
lastdate="$lastdate"
lastdepth="$lastdepth"
lastpeople="$visitors"
lastfile="$lastfile"


#output
if [[ "$2" == "--table" ]]; then
    echo "<tr>"
    
    echo "<td>$cavename</td>"
    echo "<td>$cavedepth</td>"
    echo "<td>$cavelength</td>"
    echo "<td>$lastdate</td>"
    echo "<td>$lastpeople</td>"
    echo "<td>$lastdepth</td>"
    echo "<td>$lastfile</td>"
    
    echo "</tr>"

else	  
    echo "Last surveyed leg on:"
    echo "Date, Survex file, Depth"
    echo "$lastdate $lastdepth $lastfile"

    echo "Last visited by:"
    echo "$lastpeople"

    echo "Total length:"
    echo "$cavelength"

    echo "Total depth:"
    echo "$cavedepth"
    echo ""
    echo ""
fi