// debug alerts thru # 12
var debugpipe_cp = false;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function makeHideMiddleEchoSpt()
{
	return ("set echo middle;\necho \"\";\n");
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function makeConsurfViewSpt() // this is the Consurf First View
{
  var v01 = "";

	var bgc = "white";

//	if (consurfMode || pepsurfMode) WE ALREADY KNOW THIS

	if (typeof(pipe_background_color) != "undefined" &&
		pipe_background_color.length != 0)
			bgc = pipe_background_color;

//  for (i=1; i <= top.pipe_spts_total; i++)
//  {
//    if (top.pipe_spt_name[i] == "view01")
//    {

      var s0 = "@spt view01;";
			if (bgc != "white")
			{
				// doToggleButton also sets toggleIsDown[] and refreshes PDB file echo.
				doToggleButton(backgroundIndex);
//				setButtonState("up", backgroundIndex); // also sets toggleIsDown[]
				s0 += "background " + bgc + ";\n";
			}
			v01 = verify_expand_spts(s0) + "\n";

//      break;
//    }
//  }

	v01 = fixSpt(v01);

	v01 = "# BEGIN ConsurfViewSpt;\n" +
		"set refreshing false;\n" +
		 v01 +
		"set refreshing true;\n" +
		"# END ConsurfViewSpt;\n";

	if (showView1Spt)
		showSptInWindow(v01);

	return v01;	
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function fixSpt(v01)
{
//reset;\n"
//spinOnSpt + "background white;\n";

	v01 = "# BEGIN consurfSpt;\n" + v01;

	v01 = deleteLinesContaining("javascript", v01);
	v01 = deleteLinesContaining("zoom ", v01); // remove zoom 115
	v01 = deleteLinesContaining("list * delete", v01);

	// color cartoon none is required for cartoons to obey consurf colors.
	v01 += "select protein;\ncolor cartoon none;\n";
	v01 += "# END consurfSpt;\n";
	return (v01);	
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function verify_expand_spts(s0)
{
	if (!expand_spts(s0)) // expand_spts() also emits more specific error alerts.
	{
		alert("FATAL ERROR IN FIRSTGLANCE:\nexpand_spts() failure.")
		return "";
	}
	return spt_expanded;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// expand_spts() inserts previously defined scripts into a spt block.
// Signals for expansion are "@spt scriptname" or "@for $=m,n"

function expand_spts(sraw)
{
  var sptkey = "@spt ";
  var sptname;
  var i, j; // Index of first block is 1 not 0.
  var ispt, isptname, ispace, inewline, isemi, icut, inew, snew;
  var retval = true;

//alert("sraw " + sraw);
//if (typeof(sraw) == "undefined")
//	alert("scriptsc.js #12: sraw is undefined");

  sraw = expand_for_loops(sraw);
//  if (sraw.length == 0)
//    pipefatal(); A ZERO LENGTH SCRIPT IS NOW OK, as used in
// pepsurf checkboxes for peptides (only change label toggles).

  // while an @spt remains to be replaced with the full script
  while((ispt = sraw.indexOf(sptkey)) != -1)
  {

    // Previous loop of expansion may have inserted @for's.
    // Expand @for loops before expanding @spt's within them.
    sraw = expand_for_loops(sraw);
    if (sraw.length == 0)
      pipefatal();
    // reset ispt for possibly changed sraw
    ispt = sraw.indexOf(sptkey);

//alert("ispt " + ispt);
    // set beginning of sptname
    isptname = ispt + sptkey.length;
//alert("isptname " + isptname);

    // skip any additional spaces before start of sptname
    while(sraw.charAt(isptname) == " ")
      isptname++;
//alert("isptname " + isptname);

    // find end of sptname
    ispace = sraw.indexOf(" ", isptname);
    isemi = sraw.indexOf(";", isptname);
    inewline = sraw.indexOf("\n", isptname); // \r have been stripped out

    // set icut to the first one
    icut = ispace; // can be -1
//alert("icut sp " +icut);
    if (isemi != -1)
    {
      if (ispace != -1 && isemi < ispace)
        icut = isemi;
      else if (icut == -1)
        icut = isemi;
    }
//alert("icut sm " +icut);
    if (inewline != -1)
    {
      if (icut == -1)
        icut = inewline;
      if (icut != -1 && inewline < icut)
        icut = inewline;
    }
//alert("icut nl " +icut);
    if (icut == -1)
      icut = sraw.length;
//alert("icut " +icut);


    // extract the script name
    sptname = sraw.substring(isptname, icut);
//alert("sptname " + escape(sptname));

    // locate the sptname among the PiPE block script segments
    inew = -1;
    for (i = 1; i <= top.pipe_spts_total; i++)
    {
      if (sptname == top.pipe_spt_name[i])
        inew = top.pipe_spt_i[i];
//alert("psn " + top.pipe_spt_name[i]);
    }
    if (inew != -1)
      snew = top.pipe_block[inew];
    else
    {
//      alert("pipe_cp.js #3: sptname=" + escape(sptname));
      var ok = false;
      // does script name begin "color_"?
      if (sptname.substring(0, 6) == "color_")
      {
        // if it matches a defined color name, construct script line
        for (j=1; j <= top.pipe_colors_total; j++)
        {
          if (top.pipe_color_name[j] == sptname)
          {
            ok = true;
            snew = "color [x" + top.pipe_color_value[j] + "] #" + sptname;
          }
        }
      }
      if (!ok)
      {
        alert("PiPE ERROR: there is no !spt whose name\n" +
          "matches \"" + sptkey + sptname + "\". Current script\n" +
          "cannot be executed.");
        retval = false;
        break;
      }
    }

    // REPLACE @spt WITH SCRIPT
    if (debugpipe_cp)
      alert("scriptsc.js #1 @spt:\n" + sraw);
    sraw = sraw.substring(0, ispt) + snew +
      sraw.substring(icut);
    if (debugpipe_cp)
      alert("pipe_cp.js #2 @spt expanded:\n" + sraw); //escape(sraw));
  }

  // Replace @color_names with values
  while((ispt = sraw.indexOf("@color_")) != -1)
  {
    var endc = sraw.indexOf(" ", ispt + 1);
    var endc2 = sraw.indexOf("\n", ispt + 1);
    if (endc == -1 || endc2 < endc)
      endc = endc2;
    if (endc == -1)
    {
      alert("PiPE ERROR: Space is missing after\n" +
        sraw.substring(ispt));
      retval = false;
    }
    else
    {
      var cname = sraw.substring(ispt + 1, endc); // strip off @
//      alert("pipe_cp.js #9: cname = " + cname);

      // find color name index j
      j = -1;
      for (i=1; i <= top.pipe_colors_total; i++)
      {
        if (cname == top.pipe_color_name[i])
        {
          j = i;
          break;
        }
      }
      if (j == -1)
      {
        alert("PiPE ERROR: " + cname + " is not defined.");
        retval = false;
      }
      else
      {
        sraw = sraw.substring(0, ispt) + "[x" + top.pipe_color_value[j] +
          "]" + sraw.substring(endc);
//        alert("pipe_cp.js #8: with @color_name replaced:\n" +
//          sraw);
      }
    }
  }

  if (retval)
    spt_expanded = sraw;
  else
    spt_expanded = "";
  return retval;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// returns script with expanded loops, or "" on error.
// emits its own error messages.
function expand_for_loops(sraw)
{
	var forstart;
	var forkey = "@for $=";
	var forendkey = "@endfor";
	var istart, iend;
	var say_rcvd = true;

	// while there is a "@for $="
	while((forstart = sraw.indexOf(forkey)) != -1)
	{
//		if (say_rcvd)
//		{
//			top.alertlong("pipe_cp.js #10 expand_for_loops() receives:\n" + sraw);
//			say_rcvd = false;
//		}

		// ------ find the "@endfor"
		var forend = sraw.indexOf(forendkey);
		if (forend == -1 || forend < forstart)
		{
			alert("PiPE ERROR: Missing or misplaced \"" + forendkey + "\".");
			return "";
		}

		// ------ get the loop start and end integers
		var comma = sraw.indexOf(",", forstart);
		if (comma == -1)
		{
			alert("PiPE ERROR: No comma after \"@for $=\".");
			return "";
		}
		if (comma > forstart + forkey.length + 2) // 1 works for single digit
		{
			alert("PiPE ERROR: Comma too far beyond \"@for $=\".");
			return "";
		}
		var jj = sraw.substring(forstart + forkey.length, comma);
//		alert("istart string =|" + jj + "|");
		istart = parseInt(jj);
		if (isNaN(istart))
			pipefatal("Can't find first integer after " + forkey);

		var eol = sraw.indexOf("\n", comma); // not top.line_end \r\n!
		jj = sraw.substring(comma + 1, eol);
//		alert("iend string =|" + jj + "|");
		iend = parseInt(jj);
		if (isNaN(iend))
			pipefatal("Can't find second integer after " + forkey);

		if (iend <= istart)
			pipefatal("Invalid integers after " + forkey +
				":\n" + istart + ", " + iend);

		// ------ get the pre-loop, loop body, and post-loop
		var preloop = sraw.substring(0, forstart);
//		top.alertlong("preloop:\n" + preloop);

		var loopbody = sraw.substring(eol, forend);
//		alert("loopbody:\n|" + loopbody + "|");

		var postloop = sraw.substring(forend + forendkey.length);
//		top.alertlong("postloop:\n|" + postloop + "|");

		// ------ expand the loop
		var xbody = "";
		for (var i = istart; i <= iend; i++)
		{
			var ist = "" + i;
			xbody += loopbody.replace(/\$/g, ist);
		}
//		top.alertlong("xbody:\n" + xbody);

		sraw = preloop + xbody + postloop;
//		top.alertlong("pipe_cp.js #11 expand_for_loops produces:\n" + sraw);
	}

	// check for badly formatted @for
	if (sraw.indexOf("@f") != -1)
	{
		alert("PiPE ERROR: \"@f\" in @spt but\n" +
			"not correct syntax \"" + forkey + "\".\n" +
			"(Exactly 1 space is required between @for and $=)");
		return "";
	}

	return sraw;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function pipefatal(msg)
{
  var m2 = "PiPE FATAL ERROR.\n";
  if (typeof(msg) != "undefined")
    m2 += msg + "\n";
  m2 += "OK to close PE window\n(or Cancel for debugging program code)";
  if (confirm(m2))
    top.window.close();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function deleteLinesContaining(mark, tofix)
{
	var im;
	while ((im = tofix.indexOf(mark)) != -1)
	{
		inl = tofix.indexOf("\n", im);
		tofix = tofix.substring(0, im) + tofix.substring(inl + 1);
	}
	return(tofix);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

