#!/bin/bash

f1=$1
f2=$2
f3=$3

if [ $f1 == "" ] || [ $f2 == "" ] || [ $f3 == "" ]
then
  echo "usage:   $0 <label1> <label2> <outputname>"
  echo "example: $0 rh.BA3a.label rh.BA3b.label rh.BA3ab.intersect.label"
  exit 1
fi

# save header 
f1header=$(grep "^#" $f1)
f2header=$(grep "^#" $f1)

# save-away line counts
f1vertexcount=$(head -2 $f1 | tail -1)
f2vertexcount=$(head -2 $f2 | tail -1)

# create new label file with file 1 header
echo $f1header > $f3

# compute intersection
join \
  -o '1.1,1.2,1.3,1.4,1.5' \
  -1 1 -2 1 \
  <(cat $f1 | tail -${f1vertexcount} | sort -k 1b,1 ) \
  <(cat $f2 | tail -${f2vertexcount} | sort -k 1b,1 ) \
  | sort -k 1n,1 \
  >> $$.tmp

# insert vertex count
f3vertexcount=$(wc -l $$.tmp | awk '{print $1}') 
echo $f3vertexcount >> $f3

# write data
cat $$.tmp >> $f3

# clean up
rm $$.tmp

