using System;

public void averageCalData(FileStream fileStream, UInt32[] average)
{
    int i = 0;
    int j = 0;
    UInt32[] s = new UInt32[8];
    UInt32[] total = new UInt32[8];
    Byte[] buffer = new Byte[131072]; //128k Recieve Buffer
    UInt32 samplePtr = 32; // We start with the first sample, header is 32 bytes

    int toRead = buffer.Length;
    inLength = fileStream.Read(buffer, totalRead, toRead);

    for (i = 0; i < 8; i++)
    {
        total[i] = 0;
        s[i] = 0;
        average[i] = 0;
    }

    for (i = 0; i < 100; i++)
    {
        for (j = 0; j < 8; j++)
        {
            s[j] = (UInt32)buffer[samplePtr];
            s[j] |= ((UInt32)buffer[samplePtr + 1] << 8) & 0x00FF00;
            s[j] |= ((UInt32)buffer[samplePtr + 2] << 16) & 0x00FF0000;
            samplePtr += 4;
            total[j] += s[j];
        }

    }

    for (i = 0; i < 8; i++)
    {
        average[i] = total[i] / 100;
    }
}

public void CalibrationCalculate()
{
    int i;
    double ma = new double[8];
    double[] ma = new double[8];
    UInt32[] b = new UInt32[8];
    UInt32[] average_5v = new UInt32[8];
    UInt32[] average_0v = new UInt32[8];
    UInt32[] b = new double[8];



    string ZeroVFileName = @"C:\ERPSData\0V_board1_binrecord06302018201157.bin";
    string FiveVFileName = @"C:\ERPSData\5v_board1_binrecord06302018202901.bin";
    string calFile = @"C:\ERPSData\goldenCal.dat";

    var ZeroVStream = new FileStream(ZeroVFileName, FileMode.Open);
    var FiveVStream = new FileStream(FiveVFileName, FileMode.Open);
    var OutFile = new FileStream(calFile, FileMode.Create, FileAccess.Write);

  
    averageCalData(FiveVStream, average_5v);
    averageCalData(ZeroVStream, average_0v);

    
    for (i = 0; i < 8; i++)
    {
        // y = mx + b
        //ma = (yH - yL) / (xH - xL)
        if (average_0v[i] & 0x800000)
        {
                ma[i] = (double)(average_5v[i] - (average_0v[i] - 0xFFFFFF)) / 0x7FFFFF;
        }
        else
            ma[i] = (double)(average_5v[i] - average_0v[i]) / 0x7FFFFF;
            if (average_0v[i] & 0x800000)
            {
                (average_0v[i] - 0xFFFFFF) * ma[i];
            }
            else
                b[i] = average_0v[i] * ma[i];
        }


        fprintf(write_fd, "%f %f %f %f %f %f %f %f \n", ma[0], ma[1], ma[2], ma[3], ma[4], ma[5], ma[6], ma[7]);
        fprintf(write_fd, "%x %x %x %x %x %x %x %x \n", b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]);
        fclose((FILE*)read_5v_fd);
        fclose((FILE*)read_0v_fd);
        fclose((FILE*)write_fd);
    }

