#!/bin/bash

# Derived from https://github.com/pegasus-isi/1000genome-workflow/blob/ee083a8a55436d437e3cf9f542f12d491b739c21/bin/individuals_merge.
#
# Copyright 2007-2012 University Of Southern California
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -x
c=$1

mkdir -p merged

for data in "${@:2}"
do
  echo "Merging $data..."
  mkdir -p tmp
  cp $data tmp/
  cd tmp
  tar zxf $data
  for f in *
  do
    cat $f >> ../merged/$f
  done
  cd ..
  rm -rf tmp
done

cd merged
outputfile='chr'$c'n.tar.gz'
echo "Creating merged file $outputfile..."
tar -zcf ../$outputfile .

cd ..
rm -rf merged
