#!/bin/bash

BasePath=../..;source $BasePath/Commons.sh

diags=('radial' 'vertical')   
FG="RigolDG1022Z-a"
DAS="Oscilloscopes/RigolMSO5204-e/HorizontalStabilization Oscilloscopes/RigolMSO5204-a/VerticalStabilization"

FG="RigolDG1022Z-a"

DeviceList="FunctionGenerators/$FG/Stabilization Amplifiers/KepcoStabilizationRack/Basic Infrastructure/Switches/PositionStabilization/Basic $DAS"

cesta=$SHM0/Infrastructure/PositionStabilization
#cesta=$SHM0/$whereami



function OpenSession()
{

    InitFunctGen 
}

StabilizationON () {
Call $SHMS/Devices/Infrastructure/Switches/PositionStabilization Engage
}

StabilizationOFF () {
Call $SHMS/Devices/Infrastructure/Switches/PositionStabilization DisEngage
}

InitFunctGen ()
{
for channel in 1 2; do 
    echo ":OUTP$channel OFF"|netcat -w 1 $FG 5555 #Turn off output of channel
    sleep 0.1;
    echo "Burst mode"
    echo ":SOUR$channel:BURS ON"|netcat -w 1 $FG 5555
    echo ":SOUR$channel:BURS:MODE:TRIG;:SOUR$channel:BURS:TRIG:SOUR EXT;:SOUR$channel:BURS:NCYC 1 "|netcat -w 1 $FG 5555 #Set trigger to manual/external and number of 
done

}


FunctGen () {
raw=$1
channel=$2 
echo 'channel:'$channel
raw=$(echo $raw | tr -s ',' ' ')
raw=$(echo $raw | tr -s ';' ' ')

time=()
value=()
a=0
for i in $raw
    do
      if [[ a%2 -eq 0 ]]    
      then
        time+=($i)
      else
        value+=($i)
      fi
    let "a+=1"
    done

echo Time points: ${time[@]}
echo Values: ${value[@]}

sign () { echo "$(( $1 < 0 ? -1 : 1 ))"; } #absolute value

#looks for the max value
Max=0
for m in ${value[@]} 
    do
      m=$(( $m * $(sign "$m") ))    
      if [[ $m -gt $Max ]]
      then 
         Max=$m 
      fi
    done
echo Max value: $Max

#generate sequence of points for the frequency generator
sequence=()
j=0
l=1
for ((i=${time[0]};i<=${time[-1]};i+=100))
   do
     k=${value[$l-1]}
     sequence+=$(python -c "print(round(${k}.0 / ${Max}.0,1),',')") #strange but functional
     if [[ $i -eq ${time[$l]} ]]
     then
        let "l+=1"
     fi
    let "j+=1"
   	done

c=${sequence::-2} #remove last two characters ( ,) 
c=$(echo $c | tr -s ' ,' ',') #replace " ," with ","
VerboseMode "Final sequence: $c"

echo ":OUTP$channel OFF"|netcat -w 1 $FG 5555 #Turn off output of channel
sleep 0.1;
echo "Waveform pars"
echo ":SOUR$channel:APPL:ARB 10000,$Max,0"|netcat -w 1 $FG 5555 #Arbitrary 
echo ":SOUR$channel:DATA VOLATILE, $c"|netcat -w 1 $FG 5555 #predefined function
# Zkusime pres InitFreqGen
#echo "Burst mode"
echo ":SOUR$channel:BURS ON"|netcat -w 1 $FG 5555
#echo ":SOUR$channel:BURS:MODE:TRIG;:SOUR$channel:BURS:TRIG:SOUR EXT;:SOUR$channel:BURS:NCYC 1 "|netcat -w 1 $FG 5555 #Set trigger to manual/external and number of 
sleep 0.2;
echo ":SOUR$channel:BURS:TDEL 0.00${time[0]}"|netcat -w 1 $FG 5555 #Set time delay (in seconds)
}   

FG_channel_radial=1
FG_channel_vertical=2

function GetReadyTheDischarge ()
   {
    GeneralTableUpdateAtDischargeBeginning "infrastructure.positionstabilization"
    
    if [ $( <$cesta/Parameters/main_switch) == "on" ] ; then
    StabilizationON
    for i in radial vertical; do
       if [ $( <$cesta/Parameters/"$i"_switch) == "on" ] ; then
        act_channel=$( eval "echo \${FG_channel_$i}")
        act_setup=$( <$cesta/Parameters/"$i"_waveform)
        echo $act_setup
        FunctGen  $act_setup $act_channel
      fi
    done
    fi
 }
 

function Arming()
{
       if [ $( <$cesta/Parameters/main_switch) == "on" ] ; then
            for i in radial vertical; do
                if [ $( <$cesta/Parameters/"$i"_switch) == "on" ] ; then
                    act_channel=$( eval "echo \${FG_channel_$i}")
                    echo ":OUTP$act_channel ON"|netcat -w 1 $FG 5555 
                else
                    echo ":OUTP$act_channel OFF"|netcat -w 1 $FG 5555 
                fi
            done
        else 
            echo Stabilization main switch OFF
        fi
}  
 
 
function PostDischargeAnalysis
{


    echo ":OUTP2 OFF"|netcat -w 1 $FG 5555 #Turn off output of ch2
    echo ":OUTP1 OFF"|netcat -w 1 $FG 5555 #Turn off output of ch1
    StabilizationOFF
    
    #for i in $DAS; do echo $i;Call $SHM0/Devices/$i RawDataAcquiring;done
 
local cesta=Infrastructure/PositionStabilization

 
echo "
<h3>Position stabilization <a href=$cesta/ title="Directory">$diricon</a>: </h3>
Parameters <a href=$diagpath/Parameters/ title="Parameters">$parametersicon</a>:`cat $SHM0/Production/Parameters/infrastructure.positionstabilization`" >include.html;

echo "<table>" >> include.html
    for i in 1 2; do
       CurrDAS=`echo $DAS|awk "{print $"$i"}"|xargs dirname` 
       echo doing $CurrDAS
       cp ../../Devices/$CurrDAS/*.csv .
       cp ../../Devices/$CurrDAS/ScreenShotAll.png ScreenShot${diags[$i-1]}.png
       ln -s ../../Devices/$CurrDAS/ DAS_raw_data_dir_${diags[$i-1]}
       echo "
           <tr><td valign=bottom><a href=$cesta/><img src=$cesta/name_${diags[$i-1]}.png  width='$namesize'/></a></td>
           <td valign=bottom><a href=$cesta/><img src=$cesta/port_${diags[$i-1]}_stab.jpg  width='$iconsize'/></a></td>
           <td valign=bottom><a href=$cesta/${diags[$i-1]}_setup.png><img src=$cesta/${diags[$i-1]}_setup.png width='$iconsize'/></a></td>
            <td valign=bottom>&nbsp;<a href=https://www.dropbox.com/scl/fo/inva4lpnh2v9npwou6p69/h?rlkey=z16a8p0vozqngdurin0811jq1&dl=0 title="Photogallery@DropBox"><img src=$cesta/Overview-thumb.jpg /></a>
    </td>
           <td valign=bottom><a href=$cesta/ScreenShot${diags[$i-1]}.png><img src='$cesta/ScreenShot${diags[$i-1]}.png'  width='$iconsize'/></a></td></tr>" >> include.html
    done
    
    echo "</table>" >> include.html
    Analysis
      
}      
      
function Analysis
{
local nb_id="Stabilization"

    mkdir Results
    sed -i "s/shot_no\ =\ 0/shot_no\ =\ $(<$SHMS/shot_no)/g" $nb_id.ipynb
    jupyter-nbconvert  --ExecutePreprocessor.timeout=60  --to html --execute $nb_id.ipynb --output analysis.html > >(tee -a jup-nb_stdout.log) 2> >(tee -a jup-nb_stderr.log >&2) #Lokalni vypocet
    convert -resize $icon_size icon-fig.png graph.png
    
}



