//---------- 010 Editor v2.x Script File --------------------------
// File:     Linear Sums
// Author:   Bernhard Foltz, Munich, Germany
// Revision: 1
// Purpose:  Compute checksums byte-, word-, dword-, qword-wise
//-----------------------------------------------------------------

const int entire_always = 0; // 1: sum entire file always, 0: if no selection

string LinSum(quad adr, quad siz, string range)
{
  quad idx[2];   // idx, ~idx;
  uint64 sum[8]; // b, sum1, sum2b, sum2l, sum4b, sum4l, sum8b, sum8l;
  int j, m;
  string s1, s2;

  SPrintf(s1, "Linear Sums for %s (%LX ..%LX):\n", range, adr, adr + siz - 1);
  s1 += "  Bytes/Word   Sum(BigEndian)  Sum(LittleEndian)\n";
  for (idx[0] = 0; idx[0] < siz; idx[0] ++) {
    idx[1] = ~ idx[0];
    sum[0] = ReadUByte(adr + idx[0]);
    for (j = 1; j < 8; j ++) {
      m = (1 << (j >> 1)) - 1;  
      sum[j] += sum[0] << ((idx[j & 1] & m) * 8);
    } // for j  
  } // for i
  sum[0] = sum[1];
  for (j = 0; j < 8; j += 2) {
    m = (1 << (j >> 1)) - 1; 
    SPrintf(s2, " %8d   %16LX   %16LX\n", m + 1, sum[j], sum[j + 1]);
    s1 += s2;
  } // for j
  return s1 + "\n";
} // LinSum

// main:
string s;

s = "";

// At least, one file must be open
if (FileCount() == 0) {
  MessageBox(idOk, "Linear Sums", "No file is open." );
  return -1;
}

// Sums for entire file (if entire_always or no selection available)
if ((entire_always != 0) | (GetSelSize() <= 0))
  s += LinSum(0, FileSize(), "entire file");

// Sums for selection (if selection available)
if (GetSelSize() > 0)
  s += LinSum(GetSelStart(), GetSelSize(), "selection");

// Display the results
Printf(s);  // (not visible if this editor window is not open. -> MessageBox)
MessageBox(idOk, "Linear Sums", s);
