#!/bin/bash

# Directly adapted from 
# http://genome.sph.umich.edu/wiki/EMMAX


nosuffix=$1

if [ "x" -eq "x$nosuffix" ]; then
	echo "Usage: plink2emmax.sh <plinkfile>"
	echo
	echo "The plinkfile should not have a suffix. <plinkfile>.ped or <plinkfile.bed> need to exist."
	echo
	exit -1
fi

set -e

# preparing genomic input
if [ ! -r $nosuffix.ped ]; then
	if [ -r $nosuffix.bed ]; then
		echo "I: Could not find ped file at '$nosuffix.ped' but found bedfile. Transforming that to .ped to later read phenotypes, expected at column 6."
		p-link --bfile $nosuffix --recode --out $nosuffix
	else
		echo "E: Could not find '$nosuffix.ped' or '$nosuffix.bed'."
		exit -1
	fi
fi
echo
echo "I: Transforming .ped file into .tped"
echo
p-link --file $nosuffix --recode12 --output-missing-genotype 0 --transpose --out $nosuffix

# Preparing phenotype input
# Exchange -9 and 0 as phenotypes with NA
echo
echo "I: Reading phenotypes from .ped file into file '$nosuffix.emmax_phenotypes'"
echo
awk '{print $1,$2,$6}' $nosuffix.ped > $nosuffix.emmax_phenotypes
sed -i 's/-9$/NA/' $nosuffix.emmax_phenotypes
sed -i 's/0$/NA/' $nosuffix.emmax_phenotypes


# Rynnung emmax - first creating matrix, then using it

echo
echo "I: Creating Marker-Based Kinship Matrix"
echo
emmax-kin -v -d 10 $nosuffix

echo
echo "I: Run EMMAX Association"
echo
emmax -v -d 10 -t $nosuffix -p $nosuffix.emmax_phenotypes -k $nosuffix.BN.kinf -o $nosuffix.emmax

echo 
echo "I: emmax completed successfully. Find results in '$nosuffix.emmax.ps'."
