#!/bin/bash

usage(){
echo "
Written by Brian Bushnell
Last modified October 1, 2024

Description:  Trims contigs to remove sequence unsupported by read alignment.
The coverage range file can be generated by pileup.sh.

Usage:  trimcontigs.sh in=<assembly> ranges=<ranges> out=<trimmed assembly>

Parameters:
in=<file>       File containing input assembly.
ranges=<file>   File generated by pileup with the 'ranges' flag.
out=<file>      Destination of clean output assembly.
outdirty=<file> (outd) Optional dirty output containing removed contigs.
gffin=<file>    Optional gff file.
gffout=<file>   Modified gff file.
mincov=1        Discard contigs with lower average coverage than this.
minlen=1        Discard contigs shorter than this, after trimming.
trimmin=0       Trim the first and last X bases of each sequence.
trimmax=big     Don't trim more than this much on contig ends.
trimextra=5     Trim an additional amount when trimming.
maxuncovered=3  Don't trim where there are at most this many uncovered bases.
break=t         Break contigs where uncovered areas are present.
breaklist=      Optional file to report the list of broken contigs.
skippolyn=t     Don't break around uncovered poly-Ns (scaffold breaks).

Java Parameters:
-Xmx            This will set Java's memory usage, overriding autodetection.
                -Xmx20g will specify 20 gigs of RAM, and -Xmx200m will specify 200 megs.
                    The max is typically 85% of physical memory.
-eoom           This flag will cause the process to exit if an out-of-memory
                exception occurs.  Requires Java 8u92+.
-da             Disable assertions.

Please contact Brian Bushnell at bbushnell@lbl.gov if you encounter any problems.
For documentation and the latest version, visit: https://bbmap.org
"
}

#This block allows symlinked shellscripts to correctly set classpath.
pushd . > /dev/null
DIR="${BASH_SOURCE[0]}"
while [ -h "$DIR" ]; do
  cd "$(dirname "$DIR")"
  DIR="$(readlink "$(basename "$DIR")")"
done
cd "$(dirname "$DIR")"
DIR="$(pwd)/"
popd > /dev/null

#DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/"
CP="$DIR""current/"

z="-Xmx800m"
set=0

if [ -z "$1" ] || [[ $1 == -h ]] || [[ $1 == --help ]]; then
	usage
	exit
fi

calcXmx () {
	source "$DIR""/calcmem.sh"
	setEnvironment
	parseXmx "$@"
	if [[ $set == 1 ]]; then
	return
	fi
	freeRam 800m 84
	z="-Xmx${RAM}m"
	z2="-Xms${RAM}m"
}
calcXmx "$@"

function trimcontigs() {
	local CMD="java $EA $EOOM $z -cp $CP jgi.TrimContigs $@"
	echo $CMD >&2
	eval $CMD
}

trimcontigs "$@"
