#!/bin/bash

EASY_VERSION="1.1"

bb=`tput bold`
nn=`tput sgr0`

# help
if [ $# -eq 0 ]; then
    echo "${bb}-------------------------------------------------------------------${nn}"
    echo "${bb}Tests the output from easySPARK_calibration.sh"
    echo " "
    echo "- This script is executed automatically at the end of"
    echo "  easySPARK_calibration.sh"
    echo "- It has to be called from the directory containing the products to check"
    echo "- This script checks the coherence of XCAL, YCAL and LCAL products as"
    echo "  easySPARK-calibration.sh is creating them."
    echo "  - The number of products of each categrory is checked"
    echo "  - The file sizes are checked"
    echo "  - The number of extensions is checked"
    echo "  - The angles contained are checked"
    echo "     - If they match for every extension"
    echo "     - If the number of angles is modulo 3 (for every detector)"
    echo "     - If the angles are the same for each detector"
    echo " "
    echo "${bb}Usage:${nn}"
    echo "  easySPARK_test.sh"
    echo " "
    echo "Version: "$EASY_VERSION
    echo "${bb}-------------------------------------------------------------------${nn}"
    exit
fi

# init
printVers=0
all_ok=1
my_path=

# extract all arguments beginning with KMOS, eventually imethod and sof
while [ "$1" ] ; do
    if [[ $1 == vers ]]; then
        printVers=1
    else
        my_path=$1
    fi
    shift
done

if [ $printVers = 1 ]; then
    echo $EASY_VERSION
    exit
fi

if [ ! -e "$my_path" ]; then
    echo "${bb}ERROR:${nn} Path '"$my_path"' is not existing"
    exit
fi

myPwd=$(pwd)
cd $my_path

######################################################################################
# parse files
######################################################################################
unalias ls  2>/dev/null

# parse xcal
nr_xc=0
for xc in xcal_*.fits; do
    if [ -e "$xc" ]; then
        xc_b[$nr_xc]=$(ls -l $xc| awk '{ print $5 }')
        xc_mb[$nr_xc]=$(ls -lh $xc| awk '{ print $5 }')
        xc_rot[$nr_xc]=$(dfits -x 0 $xc | grep "PRO ROT NAANGLE")
        xc_ext[$nr_xc]=$(echo "${xc_rot[$nr_xc]}" | wc -l)
#printf "          %-18s: %d (%s) (%d ext)\n" "$xc" "${xc_b[$nr_xc]}" "${xc_mb[$nr_xc]}" "${xc_ext[$nr_xc]}"
        nr_xc=$[$nr_xc+1]
    fi
done

# parse ycal
nr_yc=0
for yc in ycal_*.fits; do
    if [ -e "$yc" ]; then
        yc_b[$nr_yc]=$(ls -l $yc| awk '{ print $5 }')
        yc_mb[$nr_yc]=$(ls -lh $yc| awk '{ print $5 }')
        yc_rot[$nr_yc]=$(dfits -x 0 $yc | grep "PRO ROT NAANGLE")
        yc_ext[$nr_yc]=$(echo "${yc_rot[$nr_yc]}" | wc -l)
#printf "          %-18s: %d (%s) (%d ext)\n" "$yc" "${yc_b[$nr_yc]}" "${yc_mb[$nr_yc]}" "${yc_ext[$nr_yc]}"
        nr_yc=$[$nr_yc+1]
    fi
done

# parse lcal
nr_lc=0
for lc in lcal_*.fits; do
    if [ -e "$lc" ]; then
        lc_b[$nr_lc]=$(ls -l $lc| awk '{ print $5 }')
        lc_mb[$nr_lc]=$(ls -lh $lc| awk '{ print $5 }')
        lc_rot[$nr_lc]=$(dfits -x 0 $lc | grep "PRO ROT NAANGLE")
        lc_ext[$nr_lc]=$(echo "${lc_rot[$nr_lc]}" | wc -l)
#printf "          %-18s: %d (%s) (%d ext)\n" "$lc" "${lc_b[$nr_lc]}" "${lc_mb[$nr_lc]}" "${lc_ext[$nr_lc]}"
        nr_lc=$[$nr_lc+1]
    fi
done

if [[ $nr_xc -eq 0 && $nr_yc -eq 0 && $nr_xc -eq 0 ]]; then
    echo "${bb}WARNING:${nn} Didn't find any XCAL, YCAL and LCAL products!"
    exit
fi
######################################################################################
# #XCAL == #YCAL == #LCAL
######################################################################################
echo "--------------------------------------------------------------------"
echo "Check if number of XCAL, YCAL and LCAL products is equal"
if [[ $nr_xc -eq $nr_yc && $nr_xc -eq $nr_lc ]]; then
    echo "yes"
else
    all_ok=0
    echo "${bb}ERROR:${nn} the number of calibration products for XCAL, YCAL and LCAL differs!"
    echo "Nr. of XCALs      : "$nr_xc
    echo "Nr. of YCALs      : "$nr_yc
    echo "Nr. of LCALs      : "$nr_lc
fi

######################################################################################
# bytes(XCAL_xxx) == bytes(XCAL_yyy)
######################################################################################
if [ $nr_xc -gt 1 ]; then
    echo "--------------------------------------------------------------------"
    echo "Check if size (bytes) of all XCALs is equal"

    ok=1
    first=${xc_b[0]}
    for i in "${xc_b[@]}"; do
        if [ $first -ne $i ]; then
           ok=0
        fi
    done

    if [ $ok -eq 1 ]; then
        echo "yes"
    else
        all_ok=0
        echo "${bb}ERROR:${nn} the byte size for XCALs differs!"
        i=0
        for xc in xcal_*.fits; do
            printf "%-18s: %d bytes\n" "$xc" "${xc_b[$i]}"
            i=$[$i+1]
        done
    fi
fi

######################################################################################
# bytes(YCAL_xxx) == bytes(YCAL_yyy)
######################################################################################
if [ $nr_yc -gt 1 ]; then
    echo "--------------------------------------------------------------------"
    echo "Check if size (bytes) of all YCALs is equal"

    ok=1
    first=${yc_b[0]}
    for i in "${yc_b[@]}"; do
        if [ $first -ne $i ]; then
           ok=0
        fi
    done

    if [ $ok -eq 1 ]; then
        echo "yes"
    else
        all_ok=0
        echo "${bb}ERROR:${nn} the byte size for YCALs differs!"
        i=0
        for yc in ycal_*.fits; do
            printf "%-18s: %d bytes\n" "$yc" "${yc_b[$i]}"
            i=$[$i+1]
        done
    fi
fi

######################################################################################
# bytes(LCAL_xxx) == bytes(LCAL_yyy)
######################################################################################
if [ $nr_lc -gt 1 ]; then
    echo "--------------------------------------------------------------------"
    echo "Check if size (bytes) of all LCALs is equal"

    ok=1
    first=${lc_b[0]}
    for i in "${lc_b[@]}"; do
        if [ $first -ne $i ]; then
           ok=0
        fi
    done

    if [ $ok -eq 1 ]; then
        echo "yes"
    else
        all_ok=0
        echo "${bb}ERROR:${nn} the byte size for LCALs differs!"
        i=0
        for lc in lcal_*.fits; do
            printf "%-18s: %d bytes\n" "$lc" "${lc_b[$i]}"
            i=$[$i+1]
        done
    fi
fi

######################################################################################
# mega_bytes(XCAL) == mega_bytes(YCAL) == mega_bytes(LCAL)
######################################################################################
if [ $(echo "$nr_xc+$nr_yc+$nr_lc"|bc) -gt 1 ]; then
    echo "--------------------------------------------------------------------"
    echo "Check if size (MB) of all XCALs, YCALs and LCALs is equal"

    ok=1
    first=${xc_mb[0]}
    for i in "${xc_mb[@]}"; do
        if [ "$first" != "$i" ]; then
           ok=0
        fi
    done
    for i in "${yc_mb[@]}"; do
        if [ "$first" != "$i" ]; then
           ok=0
        fi
    done
    for i in "${lc_mb[@]}"; do
        if [ "$first" != "$i" ]; then
           ok=0
        fi
    done

    if [ $ok -eq 1 ]; then
        echo "yes"
    else
        all_ok=0
        echo "${bb}ERROR:${nn} the size in MB for XCALs, YCALs and LCALs differs!"
        i=0
        for xc in xcal_*.fits; do
            strlen=$(echo "${#xc_mb[$i]}-1"|bc)
            printf "%-18s: %d MB\n" "$xc" "${xc_mb[$i]:0:$strlen}"
            i=$[$i+1]
        done
        i=0
        for yc in ycal_*.fits; do
            strlen=$(echo "${#xc_mb[$i]}-1"|bc)
            printf "%-18s: %d MB\n" "$yc" "${yc_mb[$i]:0:$strlen}"
            i=$[$i+1]
        done
        i=0
        for lc in lcal_*.fits; do
            strlen=$(echo "${#xc_mb[$i]}-1"|bc)
            printf "%-18s: %d MB\n" "$lc" "${lc_mb[$i]:0:$strlen}"
            i=$[$i+1]
        done
    fi
fi

######################################################################################
# #extensions(XCAL) == #extensions(YCAL) == #extensions(LCAL)
######################################################################################
if [ $(echo "$nr_xc+$nr_yc+$nr_lc"|bc) -gt 1 ]; then
    echo "--------------------------------------------------------------------"
    echo "Check if the number of extensions of all XCALs, YCALs and LCALs is equal"

    ok=1
    first=${xc_ext[0]}
    for i in "${xc_ext[@]}"; do
        if [ "$first" != "$i" ]; then
           ok=0
        fi
    done
    for i in "${yc_ext[@]}"; do
        if [ "$first" != "$i" ]; then
           ok=0
        fi
    done
    for i in "${lc_ext[@]}"; do
        if [ "$first" != "$i" ]; then
           ok=0
        fi
    done

    if [ $ok -eq 1 ]; then
        echo "yes"
    else
        all_ok=0
        echo "${bb}ERROR:${nn} the number of extensions of all XCALs, YCALs and LCALs differs!"
        i=0
        for xc in xcal_*.fits; do
            printf "%-18s: %d extensions\n" "$xc" "${xc_ext[$i]}"
            i=$[$i+1]
        done
        i=0
        for yc in ycal_*.fits; do
            printf "%-18s: %d extensions\n" "$yc" "${yc_ext[$i]}"
            i=$[$i+1]
        done
        i=0
        for lc in lcal_*.fits; do
            printf "%-18s: %d extensions\n" "$lc" "${lc_ext[$i]}"
            i=$[$i+1]
        done
    fi
fi

######################################################################################
# pro_rot_naangle(XCAL) == pro_rot_naangle(YCAL) == pro_rot_naangle(LCAL)
######################################################################################
pro_test_ok=0
if [ $(echo "$nr_xc+$nr_yc+$nr_lc"|bc) -gt 1 ]; then
    echo "--------------------------------------------------------------------"
    echo "Check if the PRO ROT NAANGLE keyword in all extensions of all XCALs, YCALs and LCALs are equal"

    ok=1
    first=
    for (( fi=0,si=1; si<=${xc_ext[0]}; si++,fi++ )); do
        first="$first $(echo "${xc_rot[0]}" | sed -n "$si"p | gawk '{print $7}')"
    done

    for (( nr=0; nr<$nr_xc; nr++ )); do
        my_x=
        for (( fi=0,si=1; si<=${xc_ext[$nr]}; si++,fi++ )); do
            my_x="$my_x $(echo "${xc_rot[$nr]}" | sed -n "$si"p | gawk '{print $7}')"
        done
        if [ "$first" != "$my_x" ]; then
            ok=0
        fi
    done

    for (( nr=0; nr<$nr_yc; nr++ )); do
        my_y=
        for (( fi=0,si=1; si<=${yc_ext[$nr]}; si++,fi++ )); do
            my_y="$my_y $(echo "${yc_rot[$nr]}" | sed -n "$si"p | gawk '{print $7}')"
        done
        if [ "$first" != "$my_y" ]; then
            ok=0
        fi
    done

    for (( nr=0; nr<$nr_lc; nr++ )); do
        my_l=
        for (( fi=0,si=1; si<=${lc_ext[$nr]}; si++,fi++ )); do
            my_l="$my_l $(echo "${lc_rot[$nr]}" | sed -n "$si"p | gawk '{print $7}')"
        done
        if [ "$first" != "$my_l" ]; then
            ok=0
        fi
    done

    if [ $ok -eq 1 ]; then
        echo "yes"
        pro_test_ok=1
    else
        all_ok=0
        echo "${bb}ERROR:${nn} PRO ROT NAANGLE keyword not the same in all extensions of all XCALs, YCALs and LCALs!"
        nr=0
        for xc in xcal_*.fits; do
            my_x=
            for (( fi=0,si=1; si<=${xc_ext[$nr]}; si++,fi++ )); do
                my_x="$my_x $(echo "${xc_rot[$nr]}" | sed -n "$si"p | gawk '{print $7}')"
            done
            printf "%-18s: %s\n" "$xc" "$my_x"
            nr=$[$nr+1]
        done

        nr=0
        for yc in ycal_*.fits; do
            my_y=
            for (( fi=0,si=1; si<=${yc_ext[$nr]}; si++,fi++ )); do
                my_y="$my_y $(echo "${yc_rot[$nr]}" | sed -n "$si"p | gawk '{print $7}')"
            done
            printf "%-18s: %s\n" "$yc" "$my_y"
            nr=$[$nr+1]
        done

        nr=0
        for lc in lcal_*.fits; do
            my_l=
            for (( fi=0,si=1; si<=${lc_ext[$nr]}; si++,fi++ )); do
                my_l="$my_l $(echo "${lc_rot[$nr]}" | sed -n "$si"p | gawk '{print $7}')"
            done
            printf "%-18s: %s\n" "$lc" "$my_l"
            nr=$[$nr+1]
        done
    fi
fi

######################################################################################
# check if PRO ROT NAANGLE the same for all 3 detectors
######################################################################################
if [ $pro_test_ok -eq 1 ]; then
    pro_mod_ok=0
    echo "--------------------------------------------------------------------"
    echo "Check if the number of angles is modulo 3 (extension for every detector)"
    mod=$(expr ${xc_ext[0]} % 3)
    if [ $mod -eq 0 ]; then
        echo "yes"
        pro_mod_ok=1
    else
        all_ok=0
        echo "${bb}ERROR:${nn} There is at least one file with "${xc_ext[0]}" extensions!"
    fi

    if [ $pro_mod_ok -eq 1 ]; then
        summary=
        echo "--------------------------------------------------------------------"
        echo "Check if the PRO ROT NAANGLE keyword is the same for all 3 detectors"

        ok=1
        for (( nr=1; nr<=${xc_ext[0]}; nr=nr+3 )); do
            one=$(echo $first | gawk -v r=$nr '{print $r}')
            two=$(echo $first | gawk -v r=$(expr $nr + 1) '{print $r}')
            three=$(echo $first | gawk -v r=$(expr $nr + 2) '{print $r}')

            if [[ "$one" != "$two" || "$one" != "$three" ]]; then
                ok=0
            fi
            summary="$summary $one"
        done

        if [ $ok -eq 1 ]; then
            echo "yes"
            echo "${bb}--------------------------------------------------------------------${nn}"
            echo "${bb}Angles:${nn} "$summary
        else
            all_ok=0
            echo "${bb}ERROR:${nn} PRO ROT NAANGLE isn't the same for all 3 detectors!"
            det1="Det 1: "
            det2="Det 2: "
            det3="Det 3: "
            for (( nr=1; nr<=${xc_ext[0]}; nr=nr+3 )); do
                det1="$det1 $(echo $first | gawk -v r=$nr '{print $r}')"
                det2="$det2 $(echo $first | gawk -v r=$(expr $nr + 1) '{print $r}')"
                det3="$det3 $(echo $first | gawk -v r=$(expr $nr + 2) '{print $r}')"
            done
            echo $det1
            echo $det2
            echo $det3
        fi
    fi
else
    echo "--------------------------------------------------------------------"
    echo "${bb}WARNING:${nn} Skipped following test because last test failed anyway!"
    echo "   Check if the number of angles is modulo 3 (extension for every detector)"
fi

if [ $all_ok -eq 1 ]; then
    echo "${bb}Passed:${nn} All tests on XCAL, YCAL and LCAL are fine."
    echo "${bb}--------------------------------------------------------------------${nn}"
else
    echo "${bb}At least one test failed !!!${nn}"
    echo "${bb}--------------------------------------------------------------------${nn}"
fi

cd $myPwd
