#!/bin/tcsh -f

# Usage:
#   ./merge_components.csh [directory]
#
# If no directory is given, use the current directory.

if ($#argv >= 1) then
    set workdir = "$argv[1]"
else
    set workdir = "."
endif

if (! -d "$workdir") then
    echo "Error: directory '$workdir' does not exist."
    exit 1
endif

cd "$workdir"

# Find unique base names by stripping ".E.miniseed", ".N.miniseed", or ".Z.miniseed"
set bases = (`find . -maxdepth 1 -type f -name "*.miniseed" \
    | sed 's#^\./##' \
    | sed -n 's/\.[ENZ]\.miniseed$//p' \
    | sort -u`)

if ($#bases == 0) then
    echo "No component miniseed files found in $workdir"
    exit 0
endif

foreach base ($bases)
    set efile = "${base}.E.miniseed"
    set nfile = "${base}.N.miniseed"
    set zfile = "${base}.Z.miniseed"
    set outfile = "${base}.all.miniseed"

    # Check that all three components exist
    if (! -e "$efile") then
        echo "Skipping $base : missing $efile"
        continue
    endif

    if (! -e "$nfile") then
        echo "Skipping $base : missing $nfile"
        continue
    endif

    if (! -e "$zfile") then
        echo "Skipping $base : missing $zfile"
        continue
    endif

    echo "Creating $outfile"
    cat "$efile" "$nfile" "$zfile" >! "$outfile"
end

echo "Done."
