#!/bin/bash

if [ $# -lt 1 ]; then
  echo 1>&2 "Use: `basename $0` <mappings1> <mappings2> ..."
  echo 1>&2 "Synopsis: detect shrimp/SAM output format and merge headers appropriately"
  exit 1
fi

if [ ! -r $1 ]; then
  echo 1>&2 "error: cannot read file [$1]"
  exit 1
fi

if [ -z "$SHRIMP_FOLDER" ]; then
  echo 1>&2 "warning: SHRIMP_FOLDER undefined; assuming ."
  SHRIMP_FOLDER="."
fi

if [ ! -d "$SHRIMP_FOLDER/utils/" ]; then
  echo 1>&2 "error: cannot find directory $SHRIMP_FOLDER/utils/"
  exit 1
fi

HEADER=`head -1 <$1 | cut -c 1`

case $HEADER in
"@" )
  echo 1>&2 "Detected SAM output"

  FIRST_FILE=$1
  head -1 $FIRST_FILE

  while [ $# -gt 0 ]; do
    if [ ! -r $1 ]; then
      echo 1>&2 "error: cannot read file [$1]"
      exit 1
    fi
    $SHRIMP_FOLDER/utils/mappings-extract-headers $1 2>/dev/null | grep "^@SQ"
    shift
  done

  $SHRIMP_FOLDER/utils/mappings-extract-headers 2>/dev/null $FIRST_FILE | grep "^@PG"
  ;;
"#" )
  echo 1>&2 "Detected shrimp output"

  head -1 $1
  ;;
* )
  echo 1>&2 "error: cannot detect output format"
  exit 1
  ;;
esac
