/*
 Copyright (C) Andrew Wuensche
 
 This file is part of DDLab (Discrete Dynamics Lab) <www.ddlab.org>
 
 DDLab is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with DDLab.  If not, see <http://www.gnu.org/licenses/>.
 */

/************** include/define 13 May 1993 ********************/

#include "edecfunc.h"

/***************  list of functions in this file *************/
/*
void finish_options_box(char alloptions)
signed int memory_box(float showmem,char *thistext))
void erase_memory_box(float showmem)
void draw_bottom_title(char resize)

void draw_rule_box(signed int rule_box_width, char *thistext,char thisnhood)
signed int draw_prompt_box(char lines)
void get_prompt_box(signed int bufno, char lines)
void uncover_free_prompt_box(signed int bufno)
void erase_prompt_box(char lines)
signed int inset_prompt_box(signed int vfactor, signed int charlen,
                            char* thistext,char this_font),
char draw_hint_box(char pause,char savehintbox,
                   char* thistext,signed int startx)
void erase_free_hint_box(signed int startx)
signed int draw_box(signed int bufno,signed int xtopleft,
      signed int ytopleft,signed int xbotright,
        signed int ybotright,char outline,signed int bcolor)
void erase_box(signed int xtopleft,signed int ytopleft,
		signed int xbotright,signed int ybotright)
void show_rule_bottom(char nhoodz,char printout,
               char* thisrule,unsigned int cellindex)
*/
signed int write_rule(char highbox, char nhoodz,char printout,
        signed int xrulestart,
              signed int yrulestart,signed int rightx,
			char* thisrule,unsigned int cellindex);

/*****************  print save box, Aug 93 **********************/
void finish_options_box(char alloptions){
 signed int temp;

   if (istr_graph==1){
      istr_node_count=0;//for istr_graph
      //fprintf(stderr,"\nfinish_options_box\n");
   }    
   draw_bottom_title(0);
   sprintf(textb[0], /*longest string*/
      "graphics-g ops-o speed(slow)-V ");
   moveto(vgax(6),-vgay(50)); /* y off the screen*/
   outtext(textb[0]);/*to get length of text*/
   temp=getx+CWidth;
   moveto(0,0);

  if (pre_speed==0) sprintf(textb[4],"speed(max)-V");
  else sprintf(textb[4],"speed(slow)-V ");
  
  if (limitcheck==0 && direction=='f') /*forward only*/
                 sprintf(textb[0],"graphics-g %s", textb[4]);
  else{
     /*not while basin interupted*/
     if (basin_not_complete==1) sprintf(textb[0],"%s", textb[4]);
     else{
        if (alloptions==0) /*not while basin interupted*/
        sprintf(textb[0],"");
        else sprintf(textb[0],"graphics-g ops-o %s", textb[4]);
     } 
  }

  if (alloptions==0)
       draw_box(1,2,2,temp,CHeight*2+vgay(8),1,0);     
  else draw_box(1,2,2,temp,CHeight*3+vgay(8),1,0);         

  if (basinfield==0 && ( (limitcheck>0 && direction=='f') ||direction=='b')
            && (basin_not_complete==0)) sprintf(textb[3],"seed-e ");  
  else sprintf(textb[3],"");

  /*not while basin interupted, or if learning etc*/
  if (basin_not_complete==1 || hilight_learn) sprintf(textb[1],"STP-P");
  else{
     if (limitcheck>0 && direction=='f'){  /*if basin or field*/
         if (basinfield) sprintf(textb[1],
	     "tog:field-single-t STP-P");
         else sprintf(textb[1],"tog:single-field-t STP-P");
     }
     else if (direction=='b') sprintf(textb[1],
        "tog:single-field-t STP-P");/*subtree*/
     else sprintf(textb[1],"seed-e");/*forwards only*/
  }

  if (!loc_twod_fonly && alloptions) sprintf(textb[2],
		"%snet-n back-q cont-ret:",textb[3]);

  else sprintf(textb[2],"%s back-q cont-ret:",textb[3]);

  moveto(vgax(6),vgay(3));
  outtext(textb[0]);
  moveto(vgax(6),gety+CHeight);
  if (alloptions){
      outtext(textb[1]);
      moveto(vgax(6),gety+CHeight);
  }
  outtext(textb[2]);
  input_string(1,0);
}

/********** memory box - print bytes remaining in far core ************/
       /***** also some message in the box if showmem==2 ****/
signed int memory_box(float showmem,char *thistext){
 signed int tempx,tempy,leftboxx,rightboxx,boxy;
 unsigned char tempcolor,temp_is0;
# if __UNIX__
     if (showmem==1) return(0); /*xwindows*/
# endif
  temp_is0=is[0];
  tempx=getx;
  tempy=gety;
  tempcolor=getcolor();
  if (showmem<0) leftboxx=trboxw - vgax((int)(40 * -showmem));
  else leftboxx=trboxw-vgax(105);
  rightboxx=trboxw-2;
  boxy=2;
  /*clear box*/
  setviewport(leftboxx,boxy,rightboxx,boxy+CHeight+vgay(6),1);
  clearviewport();
  setviewport(0, 0, Maxx, Maxy, 0);
  setcolor(lightred);
  rectangle(leftboxx,boxy,rightboxx,boxy+CHeight+vgay(6));

  moveto(leftboxx+3,boxy+1);
  if (showmem==2){
     setcolor(white);
     outtext(thistext);     
  }  
  else if (showmem==1){

#    if __WATCOM__
	_heapshrink();
	sprintf(textb[0],"    mem=%lu",(long)_memavl()+get_memory());
#    endif
     setcolor(white);
     outtext(textb[0]);
  }
  moveto(tempx,tempy);
  setcolor(tempcolor);
  while(event_ready()==0){ /* wont print without this ???*/
         break;
  }
  is[0]=temp_is0; 
  return(leftboxx);
}
/********** memory box - print bytes remaining in far core ************/
void erase_memory_box(float showmem){
 signed int tempx,tempy,leftboxx,rightboxx,boxy;

  tempx=getx;
  tempy=gety;
  if (showmem<0) leftboxx=trboxw - vgax((int)(40 * -showmem));
  else leftboxx=trboxw-vgax(105);
  rightboxx=trboxw-2;

  boxy=2;
  /*erase box*/
  setviewport(leftboxx,boxy,rightboxx,boxy+CHeight+vgay(6),1);
  clearviewport();
  setviewport(0, 0, Maxx, Maxy, 0);
  moveto(tempx,tempy);
}

/********************** draw bottom title, Jan 94 **********************/
void draw_bottom_title(char resize){

    /******************** UNIX code ********************/
#   if __UNIX__
    signed int tempx,tempy,temp_pointsize,temp_font;

	tempx=getx;
	tempy=gety;
        temp_font=font_d_m_s; /*keep track of font: d=default, m=medium, s=small*/
        if (temp_font!='d') restore_def_font();
 
        if (resize==1){
           temp_pointsize=pointsize;
           /*free_fonts();*/
           /*setup_fonts(0)*/; /*default size*/
        }
        setviewport(0,Maxy+1,Maxx,WinMaxy,0);
        /*first delete the box*/
        /*clearviewport();*/

	setfillstyle(SOLID_FILL,black); 
	/*fprintf(stderr,"black=%d\n",black);*/     
	bar(0,Maxy+1,Maxx,WinMaxy);
        
	setcolor(lightred);
	rectangle(0,Maxy+1,Maxx,WinMaxy);
	moveto(vgax(3),WinMaxy-vgay(12));
	setcolor(yellow);

	XSetFont(D,Gc,italicfont->fid);
	outtext("DDLab");
	sprintf (textb[0]," %c1993-2026",169);
        outtext(textb[0]);
        /*restor default font*/  
        XSetFont(D,Gc,propfont->fid);

        setcolor(white);
	if (TFO_SEED_FIELD){
           if (TFO_SEED_FIELD==1) outtext("   TFO ");
           else if (TFO_SEED_FIELD==2) outtext("   SEED " );
	   else if (TFO_SEED_FIELD==3) outtext("   FIELD " );
        }
	else outtext("   " );
        setcolor(lightred);
	outtext(" advance-ret back/interrupt-q  ");
        bottom_title_middx=getx; /*to define x where onthefly options start here*/        
        outtext(" screen:print/save/load-@/>/<");

        setcolor(white);
	setviewport(0,0,Maxx,Maxy,1);                
        if (resize==1){
           pointsize=temp_pointsize;
           /*free_fonts();
	     setup_fonts(pointsize);*/ /*current size*/
           XSetFont(D,Gc,propfont->fid);
	}
        if (temp_font=='s') set_small_font();
        else if (temp_font=='m') set_medium_font();
        moveto(tempx,tempy);

        /******************** UNIX code ********************/
#elif __WATCOM__
  signed int hmove,vmove,tempfont,temp_font,
                 CHeight_t,CWidth_t,
                 tempx,tempy;

             temp_font=font_d_m_s; /*keep track of font: d=default, m=medium, s=small*/
             if (temp_font!='d') restore_def_font(); 
             tempx=getx;
	     tempy=gety;
             

	     tempfont=sfont;
	     setviewport(0,0,Maxx,getmaxy(),0);
	     setfillstyle(SOLID_FILL,black);
	     bar3d(0,getmaxy()-vgay(13),Maxx,getmaxy(),0,0);
	     setfillstyle(CLOSE_DOT_FILL,darkgray);
	     bar3d(0,getmaxy()-vgay(13),Maxx,getmaxy(),0,0);
	     setcolor(white);
	     line(0,getmaxy()-vgay(13),Maxx,getmaxy()-vgay(13));
	     moveto(3,getmaxy()-vgay(12));
	     setcolor(yellow);

	     if (hires==2){
		if (sfont>=1) sfont=5;
	     }
	     else if (hires==1){
		if (sfont>=1) sfont=6;
	     }
	      else if (hires==0){
		if (sfont>=1) sfont=2;
	     }
	     if (sfont>=1){  /*if font being used*/
		sprintf(textb[0],"n%d",sfont);
		_setfont(textb[0]);
		_getfontinfo(&info);
		CHeight_t=info.pixheight;
		CWidth_t=info.avgwidth;
	     }
	     else{   /*for line segment font*/
		 _setcharsize(tyd,txd);
		 _gettextsettings(&ts);
		 CWidth_t=ts.width;
		 CHeight_t=ts.height;
	     }
	     if (hires==2 || hires==1){
		hmove=-CWidth_t*.5;
		vmove=CHeight_t*.6;
	     }
	      else if (hires==0){
		hmove=-CWidth_t*.6;
		vmove=CHeight_t*.65;
	     }
	     outtext("DDLab");
             if (hires==0){
	       sprintf(textb[0],"  copyright c");
	        outtext(textb[0]);
	        moverel(hmove,vmove);
	        circle(getx,gety,vgax(4.5));
	        moverel(CWidth_t,-vmove);
	        outtext(" 1993-2026");
             }
             else{
	       sprintf(textb[0]," %c 1993-2026",169); /*copyright symbol*/
	       outtext(textb[0]);
             }           

	     setcolor(white);
	     if (TFO_SEED_FIELD){
                if (TFO_SEED_FIELD==1) outtext("   TFO ");
                else if (TFO_SEED_FIELD==2) outtext("   SEED " );
	        else if (TFO_SEED_FIELD==3) outtext("   FIELD " );
             }
	     else outtext("   " );
             setcolor(lightred);
	     outtext(" advance-ret back/interrupt-q  ");
             bottom_title_middx=getx; /*to define x where onthefly options start here*/        
             outtext(" screen:print/save/load-@/>/<");

	     setcolor(white);
	     setfillstyle(SOLID_FILL,black);
	     setviewport(0,0,Maxx,Maxy,1);

	     if (sfont>=1){  /*if font being used*/
		sfont=tempfont;
		sprintf(textb[0],"n%d",sfont);
		_setfont(textb[0]);
		_getfontinfo(&info);
		/*CHeight_t=info.pixheight;
		CWidth_t=info.avgwidth;*/
	     }
	     else{   /*for line segment font*/
		 _setcharsize(ty1,tx1);
		 _gettextsettings(&ts);
		 /*CWidth_t=ts.width;
		 CHeight_t=ts.height;*/
	     }
        if (temp_font=='s') set_small_font();
        else if (temp_font=='m') set_medium_font();
        moveto(tempx,tempy); 
#       endif
}

/************ draw (bitflip or rnd rule on-the-fly) rule box, June 2007 ******/
void draw_rule_box(signed int rule_box_width,char *thistext,char thisnhood){
  signed int tablemax,xbox;
  char cellsize,sepsize;  
  unsigned char tempcolor;

   tempcolor=getcolor();
   setcolor(white);
   //xbox=Maxx-vgax(170);
   xbox=Maxx-vgax(rule_box_width);
   draw_box(-1,xbox-3,2,Maxx-2,2+CHeight*3+vgay(6),1,0);
   setviewport(xbox-3,2,Maxx-4,CHeight*3+vgay(6),1);
   moveto(getx,gety+2);

   /*reduce size of font*/
   set_medium_font();
   outtext(textb[0]);

   /*reset size of lookup tables*/
       if (tot_only==0){
          if (set_iso_input_histogram==1) tablemax= iso_tablemax;
          else tablemax= (signed int)pow(value_range,(double)thisnhood)-1;
       }
      if (tot_only==1){
         if (totalistic==1) tablemax=thisnhood * (value_range-1) +1;
         else if (totalistic==2) tablemax= v_tablecodemax[thisnhood];
      }
      cellsize=vgax(4);
      sepsize=2;
      if (tablemax>=64){
	    cellsize=vgax(3);
	    sepsize=2;
      }
      if (tablemax>=128){
	    cellsize=vgax(3);
	    sepsize=1;
      }
      if (tablemax>=256){
	    cellsize=vgax(2);
	    sepsize=1;
      }     
      /*show rule as bitstring - don't fold*/
      moveto(xbox,gety+CHeight*1.5);
      
      if (tot_only==1){
	 foldposs=32000;
         if (totalistic==1) print_layered_bitstring(cacode[0],tablemax,cellsize,sepsize,0,1);
         else if (totalistic==2) print_layered_bitstring(v_code[0],tablemax,cellsize,sepsize,0,1);
      }
      else if (tot_only==0){
        if (set_iso_input_histogram==1){
	  //convert revised rule to isotropic, alredy converted ??
	  //isotropic_rule(0,carule[0],nhood,0,tablemax,tablemax,-2); //this shows iso-hex in terminal
	  //fprintf(stderr,"\niso-tabemax=%d",iso_tablemax);
          foldposs=32000; //in this rule box
	  print_layered_bitstring(iso_rule,iso_tablemax,cellsize,sepsize,0,1);//inside rulebox
	}     
	else print_layered_bitstring(carule[0],tablemax,cellsize,sepsize,0,4);
      }	
      moveto(xbox,gety+CHeight*.8);
      if (tot_only==1){
	if (totalistic==1){ 
            if (thisnhood<=5 && value_range==2){ 
               sprintf(textb[0],"dec=%lu ",
                                  dec_equiv(cacode[0],tablemax-1));
               outtext(textb[0]);
            }
            outtext("hex= "); 
            print_current_bitstring_hexbytes(2,2,cacode[0],thisnhood,Maxx-3,white,0);
	}
        else if (totalistic==2){
            outtext("hex= ");
            print_current_bitstring_hexbytes(2,2,v_code[0],thisnhood,Maxx-3,white,0);
        }
      }
      else if (tot_only==0){
         if (thisnhood<=3 && value_range==2 && set_iso_input_histogram==0){
            tablemax= (signed int)pow(2,(double)thisnhood)-1;
            sprintf(textb[0]," dec=%lu",dec_equiv(carule[0],tablemax));
	    outtext(textb[0]);
         }
         outtext("hex="); //in this rule box
	 if (set_iso_input_histogram==1){
	     print_current_bitstring_hexbytes(2,4,iso_rule,thisnhood,Maxx-3,white,0);
	 }   
	 else print_current_bitstring_hexbytes(2,1,carule[0],thisnhood,Maxx-3,white,0);
      }
      setviewport(0, 0, Maxx, Maxy, 0);
      /*restore character size*/    
      restore_def_font();
      tempcolor=getcolor();
}

/********************** draw prompt box, May 93 **********************/
signed int draw_prompt_box(char lines){       /*number of text lines*/
 signed int boxx,boxy,   			/*position of dialogue box*/
              tempfill,tempcolor;
 char temp_font;
					  /*_____________            */
					  /*|     |_____|<--box      */   
                                          /*|		|            */
                                          /*|           |            */
					  /*-------------            */

    sprintf(textb[10], /*longest string in prompt box*/
      "DDLabxxx xxbits Xxxxx20xx res==925X925 pt=10 randseed=2458658004XXX");
    moveto(vgax(0),-vgay(50)); /* y off the screen*/
    outtext(textb[10]);/*to get length of text*/
    boxx=Maxx-getx;
    //fprintf(stderr,"\nboxx=%d Maxx=%d getx=%d",boxx,Maxx,getx);
    if (boxx<Maxx/2)  boxx=Maxx/2;
    trboxw=boxx;
    //fprintf(stderr,"\ntrboxw=%d",trboxw);
  
    boxy=2;

    temp_font=font_d_m_s; /*keep track of font: d=default, m=medium, s=small*/
    if (temp_font!='d') restore_def_font();
    setviewport(0, 0, Maxx, Maxy, 0);
#   if __WATCOM__
       setcolor(lightred);
       /*erase box*/
       setfillstyle(SOLID_FILL,black);
       bar(trboxw,boxy,Maxx-2,boxy+CHeight*lines+vgay(6));
       /*draw box*/
       rectangle(trboxw,boxy,Maxx-2,boxy+CHeight*lines+vgay(6));
       moveto(trboxw+3,boxy+1);
       setcolor(white);

#   elif __UNIX__
       tempcolor=nowcolor;
       tempfill=fillcolor;
       /*erase box*/
       setfillstyle(SOLID_FILL,black);
       bar(trboxw,boxy,Maxx-2,boxy+CHeight*lines+vgay(6));
       /*draw box*/
       setcolor(red);
       rectangle(trboxw,boxy,Maxx-2,boxy+CHeight*lines+vgay(6));
       moveto(trboxw+3,boxy+3);
       setcolor(tempcolor);
       setfillstyle(SOLID_FILL,tempfill);
#   endif
    if (getcolor()==black) setcolor(white);/*make sure text is visible*/
    if (temp_font=='s') set_small_font();
    else if (temp_font=='m') set_medium_font();
    return(trboxw+3);
}

/************** get image covered by prompt_box, Sept 93 *******************/
void get_prompt_box(signed int bufno, char lines){ /*number of text lines*/
 signed int boxy; 		    /*position of dialogue box*/
          
#if __WATCOM__
   unsigned long imsize;
#endif					  /*_____________            */
					  /*|     |_____|<--box      */
                                          /*|		|            */
                                          /*|           |            */
					  /*-------------            */
   boxy=2;

    setviewport(0, 0, Maxx, Maxy, 0);   
   /*get image covered by box, alternative buffers availabe 0-15
     dont do this if buffno=-1*/
   if (bufno>=0 && bufno<kNumBoxPromptImages){
#     if __WATCOM__
         imsize=imagesize(trboxw,boxy,Maxx-2,boxy+CHeight*lines+vgay(6));
	 if ((boximage_prompt[bufno]=malloc(imsize))==NULL){
		    sprintf(textb[0],"boximage_prompt[%d]",bufno);
		    outof_memory(textb[0]);
         }
#     endif
      getimage(trboxw,boxy,Maxx-2,boxy+CHeight*lines+vgay(6),
					boximage_prompt[bufno]);
   }
}

/*************** uncover and free prompt box, July 2010  ******************/
void uncover_free_prompt_box(signed int bufno){
 signed int boxy;   /*position of dialogue box*/
 
   boxy=2;
   sprintf(textb[9],"boximage_prompt[%d]",bufno);
   putimage(trboxw,boxy,boximage_prompt[bufno],COPY_PUT,textb[9]);
   freeimage(boximage_prompt[bufno]);
}


/******************* erase prompt box, May 93 *************************/
void erase_prompt_box(char lines){
 signed int boxy;   /*position of dialogue box*/

#if __UNIX__
   signed int tempfill;
#endif
					  /*_____________            */
					  /*|     |_____|<--box      */
                                          /*|		|            */
                                          /*|           |            */
					  /*-------------            */
      boxy=2;
   
      setviewport(0, 0, Maxx, Maxy, 0);   

#    if __WATCOM__
	/*erase box*/
        setfillstyle(SOLID_FILL,black);
        bar(trboxw,boxy,Maxx-2,boxy+CHeight*lines+vgay(6));
#    elif __UNIX__
        /*erase box*/     
        tempfill=fillcolor;
        setfillstyle(SOLID_FILL,black);
        bar(trboxw,boxy,Maxx-2,boxy+CHeight*lines+vgay(6));       
        setfillstyle(SOLID_FILL,tempfill);
#    endif
}

/******** draw inset box in top right of prompt box  **********************/
signed int inset_prompt_box(signed int vfactor, signed int charlen,
                            char* thistext,char this_font){
  signed int tempx,tempy,boxx,thisCHeight;
 char temp_font;
 unsigned char tempcolor;

  tempx=getx;
  tempy=gety; 
  tempcolor=getcolor();
  temp_font=font_d_m_s;
  if (temp_font!='d') restore_def_font();

  setviewport(0,0,Maxx,Maxy,0);
  thisCHeight=CHeight;
  if (this_font=='m') thisCHeight*=.8;
  else if (this_font=='s') thisCHeight*=.6;
  /*vfactor>0 moves the box down, otherwize its a normal box*/   
  boxx=draw_box(-1,Maxx-2-CWidth*charlen,vgax(2)+vgax(vfactor),
		  Maxx-2,(vgax(4)+thisCHeight)+vgax(vfactor),1,0);
  moveto(Maxx-2-CWidth*charlen+3,vgax(3)+vgax(vfactor));
  /*font is 'd'*/
  if (this_font=='m') set_medium_font();
  else if (this_font=='s') set_small_font();
  
  if (vfactor==0) setcolor(white); /*otherwise set the color locally*/  
  outtext(thistext);
  
  if (temp_font=='d') restore_def_font();
  else if (temp_font=='m') set_medium_font();
  else if (temp_font=='s') set_small_font();  
  setcolor(tempcolor);
  moveto(tempx,tempy);
  return(boxx-vgax(3)); /*x coord of left edge of box*/
}

/********************** draw hint box, June 94 **********************/
char draw_hint_box(char pause,char savehintbox,
                    char *thistext,signed int startx){
 signed int tempx,tempy;
 unsigned char tempcolor;
 char bufno=-1;
  
  setviewport(0,0,Maxx,getmaxy(),0);
  is[0]=0;
  if (savehintbox) bufno=19;
  tempx=getx;
  tempy=gety;
  tempcolor=getcolor();
  setcolor(white);
  
  if (savehintbox)
     draw_box(bufno,startx,Maxy+vgax(2),Maxx-1,getmaxy()-1,1,0);
  else{
     setfillstyle(SOLID_FILL,black);
     bar(startx+1,Maxy+vgax(2),getmaxx()-1,getmaxy()-1);
  }
  moveto(startx+CWidth*2,Maxy+vgax(4));
  outtext(thistext);
  if (pause) input_string(1,0);
  moveto(tempx,tempy);
  setcolor(tempcolor);
  setviewport(0, 0, Maxx, Maxy, 0);

  return(is[0]);  
}

/********************** erase hint box, June 94 **********************/
void erase_free_hint_box(signed int startx){
 signed int tempx,tempy;
   tempx=getx;
   tempy=gety;
   setviewport(0, 0, Maxx,getmaxy(),0);
   sprintf(textb[9],"%s","boximage[19]");
   putimage(startx,Maxy+vgax(2),boximage[19],COPY_PUT,textb[9]);
   freeimage(boximage[19]);
   moveto(tempx,tempy);
   setviewport(0, 0, Maxx, Maxy, 0);
     
}

/********************** draw box, July 93 **********************/
signed int draw_box(signed int bufno,
         signed int xtopleft,signed int ytopleft,
		signed int xbotright,signed int ybotright,
				 char outline,signed int bcolor){
#if __WATCOM__
   unsigned long imsize;
#endif
 signed int boxx,boxy,   /*position of dialogue box*/    
     boxwidth,boxdepth,
     tempcolor,
     vleft,vtop,vright,vbottom;  
                 			  /*_____________            */
                			  /*|           |            */
   boxx=xtopleft;                         /*| ______    |            */
   boxy=ytopleft ;                        /*| |     |<--box          */
   boxwidth=xbotright-xtopleft;	          /*| ------    |            */
   boxdepth=ybotright-ytopleft;	          /*|		|            */
					  /*|		|            */
					  /*-------------            */
   
   vleft=view_x0;
   vtop=view_y0;   
   vright=view_x1; /*note current viewport co-ords*/
   vbottom=view_y1;
  
   /*box could go anywhere in current viewport including bottom title*/   
   tempcolor=getcolor();
   if (view_y1<=Maxy) setviewport(0, 0, Maxx, Maxy, 0);
   /*else fprintf(stderr,"%d %d %d %d\n",vleft,vtop,vright,vbottom);*/
 
   /*get image covered by box, alternative buffers availabe 0-19
     dont do this if buffno=-1*/
   if (bufno>=0 && bufno<=kNumBoxImages){ //30 defined in eglob_ag.h
      
#     if __WATCOM__
         imsize=imagesize(boxx,boxy,xbotright+1,ybotright+1);
         if ((boximage[bufno]=malloc(imsize))==NULL){
	    sprintf(textb[0],"boximage[%d]",bufno);
	    outof_memory(textb[0]);
         } 
#     endif
      /*getimage(boxx,boxy,xbotright+1,ybotright+1,boximage[bufno]);*/
      getimage(boxx,boxy,boxx+boxwidth,boxy+boxdepth+1,boximage[bufno]);
   }
   
   /*erase inside box, or color, unless  bcolor=-1 then dont alter*/
   if (bground=='b' && bcolor==0) bcolor=black;     
   if (bcolor>=0){
	 setfillstyle(SOLID_FILL,bcolor);
	 bar(boxx,boxy,boxx+boxwidth,boxy+boxdepth);
   }
    
   if (outline==1){
	setcolor(lightred);
	/*draw box*/
	rectangle(boxx,boxy,boxx+boxwidth,boxy+boxdepth);
   }
   setcolor(tempcolor);
   moveto(boxx+vgax(3),boxy+1);

   /*restore current viewport*/
   setviewport(vleft,vtop,vright,vbottom,0);
   return(boxx+vgax(3));
}

/******************* erase box, July 93 *************************/
void erase_box(signed int xtopleft,signed int ytopleft,
		signed int xbotright,signed int ybotright){
 signed int boxx,boxy,  /*position of dialogue box*/
              boxwidth,boxdepth,
              tempx,tempy,
              vleft,vtop,vright,vbottom;

	tempx=getx;			  /*_____________            */
	tempy=gety;			  /*|           |            */
	boxx=xtopleft;                    /*| ______    |            */
	boxy=ytopleft;                    /*| |     |<--box          */
	boxwidth=xbotright-xtopleft;	  /*| ------    |            */
	boxdepth=ybotright-ytopleft;	  /*|		|            */
					  /*|		|            */
					  /*-------------            */
        vleft=view_x0;
        vtop=view_y0;   
        vright=view_x1; /*note current viewport co-ords*/
        vbottom=view_y1;

        if (vbottom<=Maxy) setviewport(0, 0, Maxx, Maxy, 0); 

	moveto(boxx,boxy);           /*erase box*/
	setfillstyle(SOLID_FILL,black);
#       if __WATCOM__
	   bar(boxx, boxy, boxx+boxwidth, boxy+boxdepth);
#       elif __UNIX__
	   bar(boxx, boxy, boxx+boxwidth+1, boxy+boxdepth+1);
#       endif
	setcolor(white);
        /*restore current viewport*/
        setviewport(vleft,vtop,vright,vbottom,0);
	moveto(tempx,tempy);
        
}

/********** show rule, lambda,Z eyc at bottom of screen, Aug 93 ***********/
void show_rule_bottom(char nhoodz,char printout,
			 char* thisrule,unsigned int cellindex){
 signed int tempx,tempy,rightx,leftx;
 char textlines,highbox=0,temp_font,tempcolor;
 
   if (exhaustive_testing==2 && screensavedemo) return;
 
   if (tot_only==0){ /*update parameters*/
         if (value_range==2) z_parameter_all(nhoodz,0,thisrule);
         else z_parameter_all_mvalue(nhoodz,0,thisrule);
         post_func(nhoodz,thisrule, 0,0,0,0);
   }

   tempx=getx;
   tempy=gety;
   tempcolor=getcolor();
   setcolor(white);
   temp_font=font_d_m_s; /*keep track of font: d=default, m=medium, s=small*/
   if (temp_font!='d') restore_def_font(); 
   setviewport(0, 0, Maxx, Maxy, 0);
   leftx=vgax(125);

   if ((tot_only==0 && totalistic==0) /*just rcode*/
       || tot_only==1 /*just tcode/kcode*/
       || exhaustive_testing==2) /*for a random map*/
               rightx=vgax(550);
   else rightx=Maxx;

   /*don't show rcode -- show tcode/kcode*/
   if (totalistic || exhaustive_testing==2){ /*for tcode/kcode -- 3 lines*/           
      highbox=1;
      textlines=3;
      rule_box_top=Maxy-(CHeight*textlines)-2;
      draw_box(-1,leftx,rule_box_top,rightx,Maxy,1,0);

      if (exhaustive_testing!=2 && tot_only==0 && neutral_order==0){
	 setviewport(leftx,rule_box_top,rightx,Maxy,1);
         moveto(leftx+2,Maxy-(CHeight*textlines));
         foldposs=-1;
         print_layered_bitstring(thisrule,
            (unsigned int)pow(value_range,(double)nhoodz)-1,vgax(3),2,0,1);         
         restore_viewport;
      }
   }      
        
   else{  /*just rcode -- 2 lines*/
      textlines=2;
      rule_box_top=Maxy-(CHeight*textlines)-2-4;
      draw_box(-1,leftx,rule_box_top,rightx,Maxy,1,0);
      if (tot_only==0 && neutral_order==0){
	 setviewport(leftx,rule_box_top,rightx,Maxy,1);
         moveto(leftx+2,Maxy-(CHeight*textlines)-4);
         foldposs=-1;
         print_layered_bitstring(thisrule,
            (unsigned int)pow(value_range,(double)nhoodz)-1,vgax(3),2,0,1);
         restore_viewport;
      }
   }

   if (tot_only==0) write_rule(highbox,nhoodz,printout,leftx+3,
            Maxy-(CHeight*textlines)-2,rightx,thisrule,cellindex);
   else write_rule(highbox,nhoodz,printout,leftx+3,
         Maxy-(CHeight*textlines)-2,rightx,thisrule,cellindex);
   if (temp_font=='s') set_small_font();
   else if (temp_font=='m') set_medium_font();
   setcolor(tempcolor);
   moveto(tempx,tempy);
}

/***write rule no (dec),hex,size,lambda,lambda ratio,Z-left,Z-right,Z*****/
		  /*********** July 93 *****************/
signed int write_rule(char highbox,char nhoodz,char printout,
        signed int xrulestart,signed int yrulestart,
          signed int rightx,char* thisrule,unsigned int cellindex){
 signed int lineno=0,rightmax,extreme_right;
 signed int tempx,tempy,z,tablemax;
 unsigned long dec_max=0;

   tempx=getx;
   tempy=gety;
   
   moveto(xrulestart,yrulestart);

   if (seq_update && forward_only==0){ /*basins only*/
      unsigned long checkindex;
      unsigned char tempcolor;

       outtext("seq update: ");
       if (lineL<=limitL){   /*int sequences omly*/
          for (z=0; z<=lineL-1; z++){
	     if (lineL<=16) sprintf(textb[0],"%1x",seq_order[z]);
             else sprintf(textb[0],"%d",seq_order[z]);
             if (z%2==0){
	        tempcolor=getcolor();
	        setcolor(lightred);
	        outtext(textb[0]);
	        setcolor(tempcolor);
             }
             else outtext(textb[0]);
          }
          if (lineL<=12){
             checkindex=order_to_index(seq_order,lineL);
             sprintf(textb[0]," dec=%lu hex=%lx",checkindex,checkindex);
             outtext(textb[0]);
          }
          moverel(CWidth,0);
       }
   }
   
   if (neutral_order==1){
          if (basinfield==1) outtext( "all neutral order components");
	  else outtext( "one neutral order component");
   }   
   if (whatwire==5){ /* hypercube wiring */
       unsigned int thislineL;

        
       if (neutral_order==1 && templineL!=0) thislineL=templineL;
       else thislineL=lineL;
       sprintf(textb[0]," %dd-hcube ",thislineL);
       outtext(textb[0]);
      
       if (hyper_prob<100){
	  sprintf(textb[0]," %%wiring prob=%d actual=%.1f ",
	    hyper_prob,100.0-(100.0*(float)wires_cut/(nhood*thislineL)));
	  outtext(textb[0]); 
       }    
   }
   
   if (neutral_order) goto end;
   
   if (exhaustive_testing==2){
         sprintf(textb[0],"Random Map, v%d n=%d ",value_range,lineL);
         tempx=getx;
         moveto(getx,gety+CHeight/2);
         outtext(textb[0]);
         rightmax=getx;
      
         if (Ham_bias>0){
            moveto(tempx,gety+CHeight);
            sprintf(textb[0],"Ham bias=%d",Ham_bias);
            outtext(textb[0]);
         }
         moveto(tempx,tempy);
         return(rightmax);
   }
   if (tot_only==0 && totalistic) moveto(getx,gety+4);
   
   if (tot_only==0) sprintf(textb[0],"v%dk%d rcode",value_range,nhoodz);
   else{ 
      if (totalistic==1) sprintf(textb[0],"v%dk%d tcode (TFO)",
                          value_range,nhoodz);
      else if (totalistic==2) sprintf(textb[0],"v%dk%d kcode (TFO)",
                          value_range,nhoodz);
   }
   outtext(textb[0]);
   if ((pdata || filedata) && printout==1){
      if (pdata){
           print_out("\n");
           print_out(textb[0]);
      }
      if (filedata) save_data(textb[0]);
   }
   if (tot_only==0){
     signed int tablebytes;
      tablemax= (signed int)pow(value_range,(double)nhoodz)-1;
      tablebytes=(signed int)ceil(value_bits * (double)(tablemax+1)/8);
      dec_max=max_dec_rule(tablemax,value_range);
      if (dec_max>0){ 
         sprintf(textb[0],"(dec)%lu ",dec_equiv(thisrule,
              (signed int)pow(value_range,(float)nhoodz)-1));
         outtext(textb[0]);
         if ((pdata || filedata) && printout==1){
	    if (pdata) print_out(textb[0]);
	    if (filedata) save_data(textb[0]);
         }
         moverel(3,0);
      }
      sprintf(textb[0],"(hex)");
      outtext(textb[0]);
      if ((pdata || filedata) && printout==1){
         if (pdata){
            print_out(textb[0]);
            if (tablebytes>16) print_out("\n");
         }
         if (filedata){ 
            save_data(textb[0]);
            if (tablebytes>16) save_data("\n");
         }
      }
      if (highbox==1) moverel(0,vgay(2));
      else moverel(0,1);
      if ((pdata || filedata) && printout==1){
         setviewport(0,0,rightx-2,Maxy-CHeight,0);
         /*restrict size of hex in xterm or file*/
	 lineno=print_current_bitstring_hexbytes(2,1,thisrule,nhoodz,rightx,lightcyan,1);
         setviewport(0,0, Maxx, Maxy,0);
      }
      else{
         setviewport(0,0,rightx-2,Maxy-CHeight,0);
         lineno=print_current_bitstring_hexbytes(2,1,thisrule, nhoodz,rightx,lightcyan,0);
         setviewport(0, 0, Maxx, Maxy, 0);
      }
      if (highbox==1) moverel(0,-vgay(2));
      if ((pdata || filedata)  && printout==1 && nhoodz<7){
         if (pdata) print_out("\n");
         if (filedata) save_data("\n");
      }
   }
   rightmax=getx;
   if (lineno<=0) lineno+=1;
   moveto(xrulestart,Maxy-CHeight);
 
   if (totalistic){
     signed int tablecodemax,tempy2;
     char cellsize,sepsize;
     unsigned long this_dec_code=0;

      if (tot_only==0) moveto(getx,gety+2);
      dec_max=0;
      if (totalistic==1){ 
         tablecodemax=nhoodz*(value_range-1);
         dec_max=max_dec_rule(tablecodemax,value_range);
         sprintf(textb[1],"tcode");
         if (dec_max>0) this_dec_code=dec_equiv(cacode[cellindex],tablecodemax);
      }
      else if (totalistic==2){
         tablecodemax=v_tablecodemax[nhoodz];
         dec_max=max_dec_rule(tablecodemax,value_range);
         sprintf(textb[1],"kcode");
         if (dec_max>0) this_dec_code=dec_equiv(v_code[cellindex],tablecodemax);  
      }
      
      if (highbox==1) moveto(xrulestart,gety-CHeight);
      else moveto(xrulestart,gety);

      setfillstyle(SOLID_FILL,black);
      bar(xrulestart,gety,rightx-1,gety+CHeight-1);

      if (dec_max>0) sprintf(textb[0],"%s(dec)=%lu (hex)=",
	                         textb[1],this_dec_code);
      else sprintf(textb[0],"%s(hex)= ",textb[1]);
      outtext(textb[0]);

      setfillstyle(SOLID_FILL,black);
      bar(getx,gety,rightx-1,Maxy-1);
      if (totalistic==1)
        print_current_bitstring_hexbytes(2,2,cacode[cellindex],nhoodm[cellindex],rightx,white,0);
      else if (totalistic==2)
        print_current_bitstring_hexbytes(2,2,v_code[cellindex],nhoodm[cellindex],rightx,white,0);
      if (highbox==1) moveto(xrulestart,gety+CHeight);
      if ((pdata || filedata) && printout==1){
	 if (pdata) print_out(textb[0]);
	 if (filedata) save_data(textb[0]);
      }
      moveto(getx,gety+CHeight/2);
      if (tot_only==0) moveto(getx,gety-2);
      tempy2=gety;
      
      cellsize=vgax(4);
      sepsize=2;
      if (tablecodemax>=64){
	 cellsize=vgax(3);
	 sepsize=2;
      }
      if (tablecodemax>=128){
	 cellsize=vgax(3);
	 sepsize=1;
      }
      if (tablecodemax>=256){
	 cellsize=vgax(2);
	 sepsize=1;
      }
      
      moveto(getx+cellsize,gety-CHeight/4);
      setfillstyle(SOLID_FILL,black);
      bar(getx,gety-2,rightx-1,Maxy-1);
      if (totalistic){ 
         foldposs=64;
         if (totalistic==1) extreme_right=print_layered_bitstring
            (cacode[cellindex],tablecodemax,cellsize,sepsize,0,1);
         if (totalistic==2) extreme_right=print_layered_bitstring
            (v_code[cellindex],tablecodemax,cellsize,sepsize,0,1);
      }      
      moveto(extreme_right+CWidth,tempy2-CHeight/2);
   }
   if (threed) sprintf(textb[0],"3d size=%dx%dx%d ",i3d,j3d,h3d);
   else if (twod) sprintf(textb[0],"2d size=%dx%d ",i2d,j2d);
   else sprintf(textb[0],"1d size=%d ",lineL);
   outtext(textb[0]);
   if ((pdata || filedata) && printout==1){
      if (pdata) print_out(textb[0]);
      if (filedata) save_data(textb[0]);
   }
   /*show P for value_range=2 only*/
   if (tot_only==0){
      if (value_range==2) sprintf(textb[0],"ld=%.3g ld-r=%.3g P=%.3g ",
		     lambda,lratio,.5+(1.0-lratio)/2);
      else sprintf(textb[0],"ld=%.3g ld-r=%.3g ",lambda,lratio);
      sprintf(textb[1],"zl=%.3g zr=%.3g Z=%g ",
		     zparam[1],zparam[2],zparam[0]);
      outtext(textb[0]);
      outtext(textb[1]);
   
      if (getx > rightmax) rightmax=getx; /*max x text position*/
      if ((pdata || filedata) && printout==1){
         if (pdata){
	    print_out(textb[0]);
	    print_out("\n");
	    print_out(textb[1]);
         }
         if (filedata){
	    save_data(textb[0]);
	    save_data("\n");
	    save_data(textb[1]);
         }
      }
   }
   /*show canalyzing inputs*/
   if (tot_only==0){
      sprintf(textb[0],"C=%x/%x",canaltotal,nhoodz);
      if (canaltotal && nhoodz>1){
         memmove(textb[0]+5," ",1);      
         for (z=nhoodz-1;z>=0;z--){
	    if (get_bit(canal,z)==1){
	       sprintf(textb[1],"%x",z);
	       memmove(textb[0]+6+nhoodz-1-z,textb[1],1);
	    }
	    else memmove(textb[0]+6+nhoodz-1-z,"*",1);
         }
      }
      memmove(textb[0]+6+nhoodz,"\0",1);
      outtext(textb[0]);
      if ((pdata || filedata) && printout==1){
         if (pdata){
	    print_out(textb[0]);
	    print_out("\n");
         }
         if (filedata){
	    save_data(textb[0]);
	    save_data("\n");
         }
      }
   }
   /*show Post function*/
   if (tot_only==0){
      char post=0;
      float temp_CWidth,temp_CHeight;        
        post=post_func(nhoodz,thisrule,0,0,0,0);
        if (post==1){
           temp_CWidth=CWidth;
           temp_CHeight=CHeight;
           set_medium_font();
	   outtext(" Post=");  
           post_func(nhoodz,thisrule,2,1,0,0);
           restore_def_font();
           CWidth=temp_CWidth;
           CHeight=temp_CHeight;
        }       
   }
  end:
   moveto(tempx,tempy);
   return(rightmax);
}
/*---------------------------------------------------------------------*/


