NICE="nice -n10"
RANGER=~/SW/ranger/build/ranger
ROOT2CSV=~/SW/FACT++/build/root2csv
CSV2ROOT=~/SW/FACT++/build/csv2root
OUT=ranger.csv
TRAINRATIO=0.7

# Classical reconstruction parameters
TRUEVAR="log10(Energy)"
#TRUEVAR="Phi*TMath::RadToDeg()"
#TRUEVAR="Theta*TMath::RadToDeg()"
#TRUEVAR="MeanX*conv"
#TRUEVAR="MeanY*conv"

# Impact on ground
#TRUEVAR="TMath::Hypot(X,Y)"
#TRUEVAR="atan2(X,Y)*TMath::RadToDeg()"

echo --------------------------------- Creating input files -------------------------

cat > ${OUT}.rc <<EOF
# Do some magic to simplify the leaf names
auto-alias=MHillas.f/
auto-alias=MHillasSrc.f/
auto-alias=MHillasExt.f/
auto-alias=MNewImagePar.f/
auto-alias=MMcEvt.MMcEvtBasic.f/
auto-alias=MCorsikaEvtHeader.f/

# Some cuts to remove events with strange contents
selector=NumUsedPixels>2.5 && lgArea>-1 && abs(SlopeTrans/conv)<1

# Define some alias for easier use and use in the selector
[alias]
conv=1.14112295210361481e-01
lgArea=log10(TMath::TwoPi()*Width*Length*conv^2)

# Add additonal columns
[add]
lgSize   = log10(Size)
lgArea   = lgArea
WovL     = Width/Length
Width    = Width*conv
Length   = Length*conv
Dist     = Dist*conv
Delta    = Delta
Angle    = atan2(MeanX, MeanY)
M3L      = M3Long*TMath::Sign(1, CosDeltaAlpha)*conv
M3T      = M3Trans*conv
Asym     = Asym*conv
Alpha    = Alpha
Leakage1 = Leakage1
Leakage2 = Leakage2
Conc1    = Conc1
ConcCore = ConcCore
ConcCOG  = ConcCOG
SlopeL   = SlopeLong*TMath::Sign(1, CosDeltaAlpha)/conv
SlopeT   = SlopeTrans/conv

TimeSpread  = TimeSpread
SlopeSpread = SlopeSpread

CosDeltaAlpha = CosDeltaAlpha
NumUsedPixels = NumUsedPixels

TimeSpreadWeighted = TimeSpreadWeighted
SlopeSpredWeighted = SlopeSpreadWeighted

# Be careful, this is true MC information
#GroundR   = TMath::Hypot(X,Y)
#GroundPhi = atan2(Y,X)
#GroundX   = X
#GroundYY  = Y
EOF

# Write files
${NICE} ${ROOT2CSV} \
	"~/SW/data/star/*_Events.root" -o ${OUT} --config ${OUT}.rc \
        --force --header 1 --skip \
        --split-quantile=${TRAINRATIO} \
        --add.True=${TRUEVAR}

if [ $? != 0 ]; then
  exit 1
fi

TRAIN=${OUT}-0
TEST=${OUT}-1

# Training
echo ------------------------------------- Training ---------------------------------
${NICE} ${RANGER} \
	--file ${TRAIN} --outprefix ${OUT} --depvarname True \
	--verbose --treetype 3 --impmeasure 1 --write

echo ""
cat ${OUT}.importance | sed -E 's/([^:]*): (.*)/\2: \1/g' | LC_ALL=C sort -g -r
echo ""
#cat ${OUT}.confusion
#echo ""

# Testing
echo ------------------------------------- Testing ----------------------------------
${NICE} ${RANGER} \
        --file ${TEST} --outprefix ${OUT} --predict ${OUT}.forest \
	--verbose --treetype 3

echo --------------------------------- Creating root file ---------------------------
${NICE} ${CSV2ROOT} ${TEST} ${OUT}.root --force
if [ $? != 0 ]; then
  exit 1
fi

${NICE} ${CSV2ROOT} ${OUT}.prediction ${OUT}.root --update
if [ $? != 0 ]; then
  exit 1
fi

