#!/bin/bash

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

DAS="Oscilloscopes/RigolMSO5104-a/CurrentStabilization"

FG="RigolDG1022Z-b"

DeviceList="FunctionGenerators/$FG/CurrentStabilization Amplifiers/CurrentStabilizationKepcoRack/Basic $DAS Infrastructure/Switches/CurrentStabilization/Basic"

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


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

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


function OpenSession()
{

    InitFunctGen 
}


InitFunctGen ()
{
channel=1
    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 
}


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.currentstabilization"
    
    if [ $( <$cesta/Parameters/main_switch) == "on" ] ; then
    StabilizationON
    FunctGen  $(<$cesta/Parameters/waveform) 1
    fi
 }
 

function Arming()
{
       if [ $( <$cesta/Parameters/main_switch) == "on" ] ; then
                echo ":OUTP1 ON"|netcat -w 1 $FG 5555 
        else 
            echo Current Stabilization main switch OFF
        fi
}  

function SecurePostDischargeState
{
    StabilizationOFF
}

 
 
function PostDischargeAnalysis
{


    echo ":OUTP1 OFF"|netcat -w 1 $FG 5555 #Turn off output of ch1

    
    #for i in $DAS; do echo $i;Call $SHM0/Devices/$i RawDataAcquiring;done
 
local cesta=Infrastructure/CurrentStabilization

GenerateDiagWWWs
}

function GenerateDiagWWWs
{
local cesta="Infrastructure/$instrument"

echo "<h3>Current stabilization</h3><table><tr>
Parameters <a href=$cesta/Parameters/ title="Parameters">$parametersicon</a>:`cat $SHM0/Production/Parameters/infrastructure.currentstabilization`" >include.html;

echo "<table><tr>
<td><a href=$cesta/port_$port.jpg title="Infrastructure placement"><img src=$cesta/port_$port.jpg width='$iconsize'/></a></td>
<td><img src="$cesta/setup.png" width="$iconsize"></td>

<td><a href=https://www.dropbox.com/$DropBox title="Photogallery@DropBox"><img src=$cesta/Overview-thumb.jpg /></a></td></tr></table>

" >> include.html

i=1
       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 "
           <td valign=bottom><a href=$cesta/><img src=$cesta/name_${diags[$i-1]}.png  width='$namesize'/></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><a href=$cesta/ScreenShot${diags[$i-1]}.png><img src='$cesta/ScreenShot${diags[$i-1]}.png'  width='$iconsize'/></a></td>" >> include.html

}
 
function GenerateDiagWWWsZMB
{


 echo "
<tr><td colspan="100%"><b>Current stabilization: </b>`cat $SHM0/Production/Parameters/infrastructure.currentstabilization`</td></tr>
<tr>" > include.html
i=1
       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 "
           <td valign=bottom><a href=$cesta/><img src=$cesta/name_${diags[$i-1]}.png  width='$namesize'/></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><a href=$cesta/ScreenShot${diags[$i-1]}.png><img src='$cesta/ScreenShot${diags[$i-1]}.png'  width='$iconsize'/></a></td>" >> include.html
    
    echo "<td valign=bottom><a href=$cesta/analysis.html><img src=$cesta/graph.png  width='$iconsize'/></a></td>
    <td>
    <a href=$cesta/Parameters/ title="Parameters">$parametersicon</a><br></br>
    <a href=$gitlabpath/$whoami.ipynb title="JupyterNotebook$cesta">$pythonicon</a>
    $rightarrowicon
    <a href=$cesta/analysis.html title="Analysis$cesta">$resultsicon</a><br></br>
    <a href=$gitlabpath/$cesta/ title="Gitlab4$cesta">$gitlabicon</a>
    <a href=$cesta/ title="Directory">$diricon</a>
    <a href=$dbpath/Diagnostics/$diag_id/ title="Database">$sqlicon</a>
    </td>
    </tr>" >> 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
    
}



