init()
{
  assign_key("just_para",  10);   /* <CTRL> J */
  assign_key("reform",     11);   /* <CTRL> K */
}

reform()
{
  int len;
  int margin;
  int oldlineno;
  string buf;

  buf = get_tty_str("What is the right margin? ");
  if ((margin = atoi(buf)) <= 0) return;
  oldlineno = currlinenum();

  while (!is_line_blank(currline()))
  {
    if ((len = strlen(currline())) == 0)
      break;
    if (len > margin)
    {
      setcol(margin);
      if (currchar() != ' ')
        prevword();
      insert("\n");
      while (!is_eol() && currchar() == ' ')  delchar();
    }
    else if (len <= margin)
    {
      if (down() && is_line_blank(currline())) break;
      up();
      goeol();
      left();
      while (currchar() == ' ' && currcol() > 1)
      {
        delchar();   left();
      }
      goeol();
      insert(" ");
      delchar();
    }
  }
  goline(oldlineno);
  gobol();
}



just_para()
{
  while (!is_line_blank(currline()))
  {
    expand();
    down();
  }
}


expand()
{
  string text, new;
  int    margin, nextra, nholes, nb;

  margin = 65;

  squash();
  text   = currline();
  nholes = wordcount(text) - 1;
  nextra = margin - strlen(text);

  new = "";
  gobol();

  while (!is_eol() && nholes > 0)
  {
    c = currchar();
    new = strcat(new, chr(c));
    if (c == ' ')
    {
      new = strcat(new, repstr(" ", nb = nextra/nholes));
      nextra = nextra - nb;
      nholes = nholes - 1;
    }
    right();
  }


  while (!is_eol())
  {
    c = currchar();
    new = strcat(new, chr(c));
    right();
  }

  gobol();
  deleol();
  insert(new);
  gobol();
}

squash()
{
  gobol();
  while (!is_eol())
  {
    if (currchar() == ' ')
    {
      right();
      while (!is_eol() && currchar() == ' ')  delchar();
    }
    else
      right();
  }
  gobol();
}


wordcount(str)
  string str;
{
  int count, i, len;

  count = 1;
  len = strlen(str);

  for (i = 1;  i <= len;  i = i + 1)
    if (substr(str, i, 1) == " ")  count = count + 1;
  return count;
}

is_line_blank(str)
  string str;
{
  int i;
  int len;

  len = strlen(str);

  for (i = 1;  i <= len;  i = i + 1)
    if (substr(str, i, 1) != " ")
      return 0;
  return 1;
}
