#!/bin/bash

#
# flashScan
#
# script distributed with the MC-Flashfold software.
# Paul Dallaire, UdeM, Labo Major, 2013-Jul-09, Version 1.0
#
# v0.01: 20130710 Paul Dallaire: 
#  - all sequences to uppercase and T->U convertion
#  - Incremental windows at begining of mRNA starting with length of miRNA up to W for modes s and z
#
# This script accepts a microRNA and a mRNA and computes hybridization at every position along the mRNA using MC-Flashfold
# Three types of scan are possible: s-> Simple duplex, z-> zip NCM and zz->zip zip (2_2_2 NCMs only) all matches.
# 
# If the mode is zip zip, then the window size is set to the length of the microRNA
# Otherwise, the window size is either 40 or is user specified.
#
# mcff binary is required for flashScan to function. If it is not in your path, then you can proceed as follows:
# The binary can be specified in exactly one of two ways (call examples given lower): 
#      1- as an alias in your ~/.bashrc called mcff. Aliases defined elsewhere or under another name WILL NOT WORK.
#      2- by a fully qualified name (including the -tables and other parameter values as required) as last argument on the command line
#
# Examples:
### these will work IF an alias called mcff is properly set in your ~/.bashrc
####
## On a mac or Linux box, add a line like the following to your ~/.bashrc for this to work:
## alias mcff='/Users/paul/binaries/mcff -tables /Users/paul/binaries/tables'
## if you are named paul and if you placed your binary and tables directory as shown. Change paths at will.
####

### scan using simple duplex mode using a wintow of length 40 keeping the 10 best candidates
# flashScan 10 GCGCGCGCGCAAUCUCUCUCUCU CGACGACAGCAGCGACGACAGCAGGCGCGCGCGCAAUCUCUCUCUCUGCGCGCGCGCAAUCUCUCUCUCU 

### scan using zip zip duplex mode
# flashScan 10 GCGCGCGCGCAAUCUCUCUCUCU CGACGACAGCAGCGACGACAGCAGGCGCGCGCGCAAUCUCUCUCUCUGCGCGCGCGCAAUCUCUCUCUCU zz

### scan using simple duplex mode on a window of length 60
# flashScan 10 GCGCGCGCGCAAUCUCUCUCUCU CGACGACAGCAGCGACGACAGCAGGCGCGCGCGCAAUCUCUCUCUCUGCGCGCGCGCAAUCUCUCUCUCU 60 

### scan using a window 34 in simple duplex mode
# flashScan 10 GCGCGCGCGCAAUCUCUCUCUCU CGACGACAGCAGCGACGACAGCAGGCGCGCGCGCAAUCUCUCUCUCUGCGCGCGCGCAAUCUCUCUCUCU 34 s

### scan using a window 34 in zip duplex mode
# flashScan 10 GCGCGCGCGCAAUCUCUCUCUCU CGACGACAGCAGCGACGACAGCAGGCGCGCGCGCAAUCUCUCUCUCUGCGCGCGCGCAAUCUCUCUCUCU 34 z

### scan using a window of length 40 in simple duplex mode using a user specified path to flashfold 
# flashScan 10 GCGCGCGCGCAAUCUCUCUCUCU CGACGACAGCAGCGACGACAGCAGGCGCGCGCGCAAUCUCUCUCUCUGCGCGCGCGCAAUCUCUCUCUCU 40 s "./mcff -tables tables"

### ERROR: this line will run the zz mode but NOT USING window 34, using window 23 (that of the microRNA)
# flashScan 10 GCGCGCGCGCAAUCUCUCUCUCU CGACGACAGCAGCGACGACAGCAGGCGCGCGCGCAAUCUCUCUCUCUGCGCGCGCGCAAUCUCUCUCUCU 34 zz
### ERROR: undefined behaviour
# flashScan 10 GCGCGCGCGCAAUCUCUCUCUCU CGACGACAGCAGCGACGACAGCAGGCGCGCGCGCAAUCUCUCUCUCUGCGCGCGCGCAAUCUCUCUCUCU zz s
### This is OK and the only way to run in zz mode while specifying a binary name
# flashScan 10 GCGCGCGCGCAAUCUCUCUCUCU CGACGACAGCAGCGACGACAGCAGGCGCGCGCGCAAUCUCUCUCUCUGCGCGCGCGCAAUCUCUCUCUCU zz zz "./mcff -tables tables"
#

#END INTRO


#source aliases ( in particular mcff is defined there )
shopt -s expand_aliases
. ~/.bashrc

R=$(mcff 2>&1)
if [[ $R == "ERROR: parameter seq must be set." ]] ; then
    Call_Type="Alias"
else
    Call_Type="Unknown"
fi

#return this many best hits
Many_hits=${1-20}

#return all hits whose energy is better than Threshold
Threshold=1000000 #default to some large positive number later we will set it to the value of $Many_hits if that value is negative 

MI=$2 #microRNA
M=$3  #messengerRNA


W=${4-"40"} #length of window (or 'zz')

mode=${5-"s"} #mode of scan s:simple, z:anyNCM, zz:only2_2_2


# if the user wants to specify the location of the binary to run, then use that value
# otherwise, the previously set alias will be used.
binary=${6} #binary code
if [[ $binary != "" ]]; then
    Call_Type="User_Text"
fi

# if the user provided window has value 'zz' then set the mode accordingly 
if [[ $W == "zz" ]] ; then
    mode=$W
    W=1 #for parameters integrity verification
fi

### Check for a call for help
HELP=
for arg in $@; do
    matchLen=$(expr ${arg} : "-*[Hh][Ee][Ll][Pp]")
    if [ $matchLen -ge 4 ]; then
	HELP="help"
	mode="help"
    fi
done


### Check integrity of parameters
if [ "$HELP" != "help" ]; then

    ### Check number of parameters passed 
    if [ $# -lt 3 ] ; then
	echo "Too few parameters"
	echo "type $0 help for more information"
	exit 0
    fi


    #Check if paramter $1 (now in Many_hits) is a negative real value.
    #if so, then assign it to Threshold and set Many_hits to some value > length mRNA
    #assuming that M is ok
    if [ ${#Many_hits} -eq $(expr $Many_hits : "-[0-9.]*" ) ] ; then
	Threshold=$Many_hits
	Many_hits=$((${#M}+1))
    fi

    if [ ${#Many_hits} -ne $(expr $Many_hits : "[0-9]*") ] || [ ${Many_hits} -lt 1 ]; then
	echo "Parameter $Many_hits is not a valid number (Should be the number of suboptimals to return)"
	echo "(use -help to get usage information)"
	exit 0 
    fi

    if [ ${#MI} -ne $(expr $MI : "[ACGUTacgut]*") ]; then
	echo "Parameter $MI is not a microRNA"
	echo "(use -help to get usage information)"
	exit 0 
    fi

    if [ ${#M} -ne $(expr $M : "[ACGUTacgut]*") ]; then
	echo "Parameter $M is not an mRNA"
	echo "(use -help to get usage information)"
	exit 0 
    fi
    
    if [ ${#W} -ne $(expr $W : "[0-9]*") ] || [ ${W} -lt 1 ]; then
	echo "Parameter $W is not a valid number (should be the window size)"
	echo "(use -help to get usage information)"
	exit 0 
    fi
    
    if [ ${mode} != "s" -a ${mode} != "z" -a ${mode} != "zz" ]; then
	echo "Parameter $mode does not describe a valid mode (should be one of s, z or zz)"
	echo "(use -help to get usage information)"
	exit 0 
    fi

    # Clean up input sequences
    MI=$(echo $MI | tr [:lower:] [:upper:] | tr 'T' 'U' )
    M=$(echo $M | tr [:lower:] [:upper:] | tr 'T' 'U' )

    # Check that length of mRNA is sufficient to accomodate the miRNA
    if [ ${#MI} -gt ${#M} ]; then
	echo "mRNA too short for miRNA"
	exit 0
    fi
fi


#inverts a string
function invert {
    read IN
    OUT=''
    for i in $(seq 1 ${#IN}); do
	OUT=$OUT${IN:$((${#IN}-i)):1}
    done
    echo $OUT
}


function match_symbol {
    a=$(echo $1 | tr [:lower:] [:upper:])
    b=$(echo $2 | tr [:lower:] [:upper:])
    chosen=':' #non canonical by default
    if [ $a == A -a $b == U ] || [ $a == U -a $b == A ] || [ $a == C -a $b == G ] || [ $a == G -a $b == C ] || [ $a == G -a $b == U ] || [ $a == U -a $b == G ] ; then
	chosen='|'
    fi
    echo $chosen
}
#transform output of mcff in zip modes to a more readable format
function convert {
    read name
    read seq
    #db forward, db backwards
    read dbf dbb score

    #positions along the mRNA
    from=$(echo $name | sed 's/>\([0-9]*\)\.\.\([0-9]*\)/\1/')
    to=$(echo $name | sed 's/>\([0-9]*\)\.\.\([0-9]*\)/\2/')

    #mRNA sequence in segment
    M=${seq:0:$((to-from))}
    #miRNA sequence in 3'->5' configuration
    MI=$(echo ${seq:$((to-from+2)):${#seq}} | invert)
    #dot bracket corresponding to the miRNA
    dbb=$(echo $dbb | invert )    

    # Forward sequence, Backwards sequence, Matches
    f=''
    b=''
    m=''

    # p iterates in mRNA, q on miRNA
    p=0
    q=0
    while [ $p -lt ${#dbf} ] || [ $q -lt ${#dbb} ] ; do
	#dot brackets agree on this position ?
	if [[ ${dbf:p:1} == ${dbb:q:1} ]] || [ ${dbf:p:1} == '(' ] && [ ${dbb:q:1} == ')' ] ; then
	    f=$f${M:p:1}
	    b=$b${MI:q:1}
	    #double missmatch?
	    if [[ ${dbf:p:1} == '.' ]]; then
		m="${m}."
	    else #match
		vertical=$(match_symbol ${f:${#f}-1:1} ${b:${#b}-1:1})
		m="${m}${vertical}"
	    fi
	    p=$((p+1))
	    q=$((q+1))
	    #missmatch in mRNA? (gap in miRNA)
	elif [[ ${dbf:p:1} == '.' ]]; then
	    f=$f${M:p:1}
	    b=$b'-'
	    m="${m}-"
	    p=$((p+1))
	    #missmatch in miRNA (gap in mRNA)
	else 
	    f=$f'-'
	    b=$b${MI:q:1}
	    m="${m}-"
	    q=$((q+1))
	fi
    done

    
    #formatted output

    echo
    echo "$from $f $to      $score"
    
    spacer="$(echo $from | sed 's/./ /g' ) "
    echo "$spacer$m" | tr '-' ' '

    #Fooling around to get rid of leading '-' characters in miRNA sequence
    #There is no gap there because there is no more seqeunce to match there.
    #(I have problems here because bash seams to remove trailing spaces in various places,
    # this scheme works on my mac)
    hd=$(echo $b | sed 's/^\([-]*\)[^-].*/\1/' | tr '-' '_')
    tl=$(echo $b | sed 's/^[-]*//')
    echo "$spacer$hd$tl" | tr '_' ' '
}

#min of two INTEGERS
function min {
    if [ "$1" -lt "$2" ] ; then
	echo $1
    else
	echo $2
    fi
}

#max of two INTEGERS
function max {
    if [ "$1" -lt "$2" ]; then
	echo $2
    else
	echo $1
    fi
}

#check that window is at least the length of the miRNA
W=$(max ${#MI} $W)

# main loop, runs the code
case $mode in
    "s" | "z"  )
	case $Call_Type in 
	    "Alias" )
		Start=$(min ${#MI} $W)
		Best_positions=$( for T in $(seq $Start ${#M} ); do
		    echo -n "$T    "$'\r' 1>&2
		    ThisW=$(min $T $W)
		    sc=$(mcff -n "$((T-ThisW))..$T" -s ${M:$((T-ThisW)):$ThisW} -${mode}d $MI)
		    goodenough=$( echo "$sc <= $Threshold" | bc )
		    if [ $goodenough -eq 1 ]; then
			echo -n "$T "
			echo $sc;
		    fi
		    done | sort -t ' ' -k 2 -g | head -n $Many_hits | cut -f 1 -d ' ' )

		for p in $Best_positions; do 
		    ThisW=$(min $p $W)
		    mcff -n "$((p-ThisW))..$p" -s ${M:$((p-ThisW)):$p} -${mode}d $MI -v 2>&1 | grep -v INFO | grep -v Explored | convert;
		done


#		Best_positions=$( for T in $(seq 1 $(( ${#M} - $W )) ); do
#		    echo -n "$T    "$'\r' 1>&2
#		    sc=$(mcff -n "$T..$((T+W))" -s ${M:$T:$W} -${mode}d $MI)
#		    goodenough=$( echo "$sc <= $Threshold" | bc )
#		    if [ $goodenough -eq 1 ]; then
#			echo -n "$T "
#			echo $sc;
#		    fi
#		    done | sort -t ' ' -k 2 -g | head -n $Many_hits | cut -f 1 -d ' ' )
#		for p in $Best_positions; do 
#		    mcff -n "$p..$((p+W))" -s ${M:$p:$W} -${mode}d $MI -v 2>&1 | grep -v INFO | grep -v Explored | convert;
#		done
		;;
	    "User_Text")

		Start=$(min ${#MI} $W)
		Best_positions=$( for T in $(seq $Start ${#M} ); do
		    echo -n "$T    "$'\r' 1>&2
		    ThisW=$(min $T $W)
		    sc=$($binary -n "$((T-ThisW))..$T" -s ${M:$((T-ThisW)):$ThisW} -${mode}d $MI)
		    goodenough=$( echo "$sc <= $Threshold" | bc )
		    if [ $goodenough -eq 1 ]; then
			echo -n "$T "
			echo $sc;
		    fi
		    done | sort -t ' ' -k 2 -g | head -n $Many_hits | cut -f 1 -d ' ' )

		for p in $Best_positions; do 
		    ThisW=$(min $p $W)
		    $binary -n "$((p-ThisW))..$p" -s ${M:$((p-ThisW)):$p} -${mode}d $MI -v 2>&1 | grep -v INFO | grep -v Explored | convert;
		done

		;;
	    *)
		echo "Funny. an error occured in the bash script. ONE"
		echo $Call_Type
		exit 1;
		;;
	esac
	;;
    
    "zz" )
        W=${#MI}; 
	 case $Call_Type in
	     "Alias")	
		 Best_positions=$( for T in $(seq 1 $(( ${#M} - $W )) ); do
		    echo -n "$T    "$'\r' 1>&2
		    sc=$(mcff -n "$T..$((T+W))" -s ${M:$T:$W} -zzd $MI)
		    goodenough=$( echo "$sc <= $Threshold" | bc )
		    if [ $goodenough -eq 1 ]; then
			echo -n "$T "
			echo $sc;
		    fi
  		 done | sort -t ' ' -k 2 -g | head -n $Many_hits | cut -f 1 -d ' ' )
		 for p in $Best_positions; do 
		      mcff -n "$p..$((p+W))" -s ${M:$p:$W} -zzd $MI -v 2>&1 | grep -v INFO | grep -v Explored | convert; 
		 done
		 ;;
	     "User_Text")
		 Best_positions=$( for T in $(seq 1 $(( ${#M} - $W )) ); do
		    echo -n "$T    "$'\r' 1>&2
		    sc=$($binary -n "$T..$((T+W))" -s ${M:$T:$W} -zzd $MI)
		    goodenough=$( echo "$sc <= $Threshold" | bc )
		    if [ $goodenough -eq 1 ]; then
			echo -n "$T "
			echo $sc;
		    fi
  		 done | sort -t ' ' -k 2 -g | head -n $Many_hits | cut -f 1 -d ' ' )
		 for p in $Best_positions; do 
		      $binary -n "$p..$((p+W))" -s ${M:$p:$W} -zzd $MI -v 2>&1 | grep -v INFO | grep -v Explored | convert; 
		 done
		 ;;
	     *)
		 echo "Funny. an error occured in the bash script."
		 exit 1;
		 ;;
	 esac
	 ;;
    
    *)
	# output comment at begining of script file
	cat $0 | sed -n '1d;/END INTRO/q;2,$s/#/ /gp' 
	# and then some...
	cat <<EOF
ARGUMENTS:
    Number of best solutions to output (if value > 1) or maximal energy of the hybrid (if value < 0)
    microRNA (5'->3') 
    mRNA (5'->3')
    window size (40 is typical) or 'zz'
    one of 's', 'z' or 'zz'
    full path to binary (including specific parameters such as -tables path/to/tables or -alt, use quotes to protect this entry)
         Note that if you have defined an alias called mcff in your ~/.bashrc, 
         including -tables specification, then the last parameter is not required
EOF
;;
esac

