#!/bin/bash

# Derived from https://github.com/pegasus-isi/1000genome-workflow/blob/ee083a8a55436d437e3cf9f542f12d491b739c21/bin/sifting.
#
# 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.

input=$1
c=$2

newfile='ALL.chr'$c'.vcf.gz'

unzipped=${newfile%.*z}
gunzip -c $1 > $unzipped
set -x
siftfile='SIFT.chr'$c'.vcf'

header=$(head -n 1000 $unzipped | grep "#" | wc -l)
echo $header

echo 'taking columns from '$unzipped
grep -n "deleterious\|tolerated" $unzipped | grep "rs" > $siftfile

lines='line.txt'
ids='id.txt'
info='info.txt'
sifts='sift.txt'

awk '{print $1}' $siftfile | awk -F ":" '{print $1-'$header'}' > $lines #.txt
awk '{print $3}' $siftfile > $ids #.txt
awk '{print $8}' $siftfile > $info #.txt
awk -F "|" '{print $5"\t"$17"\t"$18}' $info | sed 's/(/\t/g' | sed 's/)//g' > $sifts

final='sifted.SIFT.chr'$c'.txt'
pr -m -t -s $lines $ids $sifts | gawk '{print $1,$2,$3,$5,$7}' > $final

echo 'line, id, ENSG id, SIFT, and phenotype printed to '$final

rm $lines
rm $ids
rm $info
rm $sifts
rm $unzipped
