clear();  // Clears window

var total_loops = 100;      // How many times we sweep through the inputs values
var average_duration = 1;   // How long to sample amplifier output
var lower_end = -20;        // Smallest mV to test
var upper_end = 20;         // Largest mV to test
var step_size = 0.5;        // Step size in mV

if(!('Scope' in this)) throw "Please open a Scope instrument";
if (!('Wavegen' in this)) throw "Please open a Wavegen instrument";

Wavegen.Channel1.Mode.text = "Simple";

Wavegen.run();
Scope.run();

// Set the scope window width
Scope1.Time.Position.value = 0;
Scope1.Time.Base.value = average_duration;  // Total window width
Scope1.Channel1.Range.value = 10;


// Turn on the power supplies
Supplies.Output.PositiveSupply.Enable.Value = 1;
Supplies.Output.NegativeSupply.Enable.Value = 1;
 
Supplies.Output.PositiveSupply.Voltage.value = 5;
Supplies.Output.NegativeSupply.Voltage.value = -5;

Supplies.MasterEnable.checked = 1;

print("Wavegen Output (mV),Wavegen Measured (mV),Diff Amplifier Measured (V),Single Amplifier Measured (V),Ideal Wavegen Gain,Real Wavegen Gain");

for (var i = 0; i < total_loops; i++) {
    for (var offset = lower_end; offset <= upper_end; offset += step_size) {
        var desired_output_voltage = offset / 1000
        Wavegen.Channel1.Simple.Offset.value = desired_output_voltage; // Set offset for desired output voltage
        
        wait(average_duration + 0.2);       // Waiting for 0.2 extra seconds allows the data to be fully cleared
        
        var diff_amp_out = Scope.Channel1.measure("Average");
        var average_wavegen_reading = Scope.Channel2.measure("Average");

        var single_amp_out = diff_amp_out + 5;  // Single ended assuming we provided GND and 10V

        var real_gain = diff_amp_out / average_wavegen_reading;
        var ideal_gain = diff_amp_out / offset * 1000;

        var output = offset + "," + ((average_wavegen_reading)*1000).toFixed(3) + "," + (diff_amp_out.toFixed(3)) + "," + (single_amp_out.toFixed(3)) + ","+ (ideal_gain.toFixed(3)) + "," + real_gain.toFixed(3);
        print(output);
    }
}

Wavegen.Channel1.Simple.Offset.value = 0;  // Turn off the wavegen
Supplies.MasterEnable.checked = 0;  // Turn off the supplies