#!/bin/bash

usage() {
cat << EOF
	PhenoProphet:
		PhenoProphet program assigns each TF a score representing its confidence that deletion of that TF will yield some phenotypic change of interest

	Usage:
		phenoprophet [options] -n networkFile -f regulatorGeneNamesFile -g targetGeneNamesFile -p phenotypeLinkedGenesFile

	Options:
		-i				Number of next most confident edges to add to the 
						network of most confident edges.
						The deafult is 500 edges. 
		-s				Largest number of most confident edges to consider.
						Set to the size of the largest network that has
						better than random recovery of true interactions
						The default is 40,000 edges.
	 
EOF
}

checkFileParam(){
	if [ -z $2 ]
	then
		echo "Option: -${1} is not defined!"
		usage
		exit 1
	fi

	if [ ! -f $2 ]
	then
		echo "The argument of option -${1} cannot be found: ${2}"
		usage
		exit 1
	fi
}

checkIntegerParam(){
	if [ -z $2 ]
	then
		echo "Option: -${1} is not defined!"
		usage
		exit 1
	fi

	if ! [ $2 -eq $2 2>/dev/null ]
	then
		echo "The argument of option -${1} is not an integer: ${2}"
		usage
		exit 1
	fi
}

checkDirectoryParam(){
	if [ -z $2 ]
	then
		echo "Option: -${1} is not defined!"
		usage
		exit 1
	fi

	if [ ! -d $2 ]
	then
		mkdir $2
	fi
}

networkFile=
regulatorGeneNamesFile=
targetGeneNamesFile=
phenotypeLinkedGenesFile=
cutoffInterval=500
cutoffStop=40000
outputDir=`pwd`

while getopts “:hi::s::n:f:g:p:” OPTION
do
	case $OPTION in
		h)
			usage
      exit 0
			;;
		n)
			networkFile=$OPTARG
			checkFileParam ${OPTION} ${OPTARG}
			;;
		f)
			regulatorGeneNamesFile=$OPTARG
			checkFileParam ${OPTION} ${OPTARG}
			;;
		g)
			targetGeneNamesFile=$OPTARG
			checkFileParam ${OPTION} ${OPTARG}
			;;
		
		p)
			phenotypeLinkedGenesFile=$OPTARG
			checkFileParam ${OPTION} ${OPTARG}
			;;
		i)
			cutoffInterval=$OPTARG
			checkIntegerParam ${OPTION} ${OPTARG}
			;;
		s)
			cutoffStop=$OPTARG
			checkIntegerParam ${OPTION} ${OPTARG}
			;;
		?)
			usage
			exit
			;;
	esac
done

if [[ -z $networkFile ]] || [[ -z $regulatorGeneNamesFile ]] || [[ -z $targetGeneNamesFile ]] || [[ -z $phenotypeLinkedGenesFile ]]
then
	echo "ERROR: You must specify arguments for options: -n -f -g -p"
	usage
	exit 1
fi

## Running in the sequential fashion
R --no-save --slave --no-init-file --args ${networkFile} ${regulatorGeneNamesFile} ${targetGeneNamesFile} ${phenotypeLinkedGenesFile} ${cutoffInterval} ${cutoffStop} ${outputDir} < ${PHENOPROPHET_DIR}/run_phenoprophet.r
