// http://akelpad.sourceforge.net/forum/viewtopic.php?p=13770#13770
// Version: 1.1
// Author: Shengalts Aleksander aka Instructor
//
//
// Description(1033): Get composition number members. For example: 0x7 is expaned to 0x1|0x2|0x4 and 7 expaned to 1+2+4.
// Description(1049): Получить составные части числа. Например: 0x7 разворачивается в 0x1|0x2|0x4 и 7 разворачивается в 1+2+4.
//
// Arguments:
// -Template="${m16}"  -output string template (default is "${n10}=${m10}${newline}${n16}=${m16}"). Variables:
//                        ${n10}     -decimal number.
//                        ${m10}     -decimal members.
//                        ${n16}     -hexadecimal number.
//                        ${m16}     -hexadecimal members.
//                        ${newline} -new line.
// -Output=1           -output string to (one of the following):
//                        0  edit window (default).
//                        1  clipboard.
//                        2  Log::Output panel.
//
// Usage:
// Call("Scripts::Main", 1, "GetNumberMembers.js", `-Template="${m10}" -Output=1`)

//Arguments
var pTemplate=AkelPad.GetArgValue("Template", "${n10}=${m10}${newline}${n16}=${m16}");
var nOutput=AkelPad.GetArgValue("Output", 0);

//Variables
var pSelText=AkelPad.GetSelText();
var dwInitNumber=parseInt(pSelText);

if (dwInitNumber)
{
  var pInitNumber10="" + dwInitNumber.toString(10);
  var pInitNumber16="0x" + dwInitNumber.toString(16);
  var pMembers10="";
  var pMembers16="";
  var dwNumber=dwInitNumber;
  var dwCount;

  for (dwCount=0x00000001; dwCount <= 0x80000000; dwCount*=2)
  {
    if (dwNumber & dwCount)
    {
      pMembers10+=(dwNumber == dwInitNumber?"":"+") + dwCount.toString(10);
      pMembers16+=(dwNumber == dwInitNumber?"0x":"|0x") + dwCount.toString(16);
      if (!(dwNumber=dwNumber & ~dwCount))
        break;
    }
  }
  pTemplate=pTemplate.replace(/\$\{n10\}/g, pInitNumber10);
  pTemplate=pTemplate.replace(/\$\{m10\}/g, pMembers10);
  pTemplate=pTemplate.replace(/\$\{n16\}/g, pInitNumber16);
  pTemplate=pTemplate.replace(/\$\{m16\}/g, pMembers16);
  pTemplate=pTemplate.replace(/\$\{newline\}/g, "\n");

  if (nOutput == 0)
    AkelPad.ReplaceSel(pTemplate);
  else if (nOutput == 1)
    AkelPad.SetClipboardText(pTemplate);
  else if (nOutput == 2)
    AkelPad.Call("Log::Output", 4, pTemplate);
}
