/*
 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/>.
 */

/******** interrupt functions that work with run_forward() ******/
#include "edecfunc.h"
#include <fcntl.h>
#if __WATCOM__
#   include <io.h>
#   include <sys\stat.h>

#elif __UNIX__
#   include <sys/types.h>
#   include <sys/uio.h>
#endif


/***************  list of functions in this file *************/
unsigned char random_block(char keep,signed int blockdiam,
                                         unsigned char color1);
unsigned char singleton_seed(char what,unsigned char color1);
void revise_various_stp_settings(ent_eeg *eg,int_stp *it);
void clear_stp(ent_eeg *eg,int_stp *it);
void clear_lookuphist(ent_eeg *eg);       
/*
void reset_stpwidth(ent_eeg *eg,int_stp *it)
void interrupt_key_index(ent_eeg *eg,int_stp *it)
void interrupt_stp(diff_var *dp, 
                   auto_ent *ae, 
                   ent_eeg *eg, 
                   int_stp *it)*/
void three_block_iso_patterns(char count_up_down,int_stp *it);
void show_three_block_iso_patterns(int_stp *it);
/*char interrupt_stp_box(signed int ypos, char* thisrule,
		   unsigned long ittcount, signed int stpwidth,
                   diff_var *dp, 
                   auto_ent *ae, 
                   ent_eeg *eg, 
                   int_stp *it)*/

/************* random block for interrupt only April 93 ****************/
unsigned char random_block(char keep, signed int blockdiam,
                                          unsigned char color1){

   if (ncolor==0){
      if (color1==white) color1=yellow;
      else if (color1==yellow) color1=white;
   }
   if (oned && (blockx==0 || blockx==lineL)) blockx=seglen;
   else if (twod && ((blockx==0 && blocky==0) ||
                     (blockx==i2d && blocky==j2d))) blockx=blocky=seglen;
   else if (threed && ((blockx==0 && blocky==0 && blockz==0) ||
	   (blockx==i3d && blocky==j3d && blockz==h3d))) blockx=blocky=blockz=seglen;
   set_central_block(keep,state1);

   seed_was_set=1;
   return(color1);
}

/**************** singleton, April 93 *****************************/
unsigned char singleton_seed(char what, unsigned char color1){
  unsigned int z,poss,hh,jj,ii;
  char backg_value,foreg_value;
   
   if (ncolor==0){
      if (color1==white) color1=yellow;
      else if (color1==yellow) color1=white;
   }
   /*if (what==1) memmove(state1,all_0s,bytesL);*/ /*set all bits to 0*/
   if (value_range==2){
      if (what==1) memset(state1, 0, bytesL);
      else if (what==0){
         memset(state1, 255, bytesL);/*set all bits to 1*/ 
         /*set exess bits to 0*/
         for (z=lineL;z<=bytesL*8-1;z++)
	           set_bit0(state1,z); /*set_bit0(all_1s,z);*/
      }
   }
   else{
     signed int excess_bits;
     if (what==0){ /*key 6: any backgound, and diff centre cell*/
         backg_value=myrand()%value_range;
         for (z=0;z<=lineL-1;z++) set_value(state1,z,backg_value);
         /*set exess bits to 0*/
         if ((lineL*value_bits)%sizeof(char)!=0){
	    char *pstate1;
            excess_bits=(bytesL*sizeof(char)) - (lineL*value_bits);
            /*fprintf(stderr,"\n excess_bits=%d",excess_bits);*/
            pstate1=&state1[bytesL-1];
            for (z=7;z>=7-excess_bits;z--) set_bit0(pstate1,z);
         }
      }     
      else{ /*key 5: zero background, and diff centre cell*/
          backg_value=0; /*set background to zero*/
          memset(state1, 0, bytesL);
      }      
   } 


   if (oned){
      if (diff_plot) poss=L/4;
      else poss=lineL/2;
   }
   else if (twod){
      jj=j2d/2;      
      if (diff_plot){
         ii=i2d/4;
         poss=i2d*jj + ii; 
      }
      else{
         ii=i2d/2;
         poss=i2d*jj + ii;
      }
   }
   else if (threed){
      hh=h3d/2;
      jj=j3d/2;
      ii=i3d/2;
      poss=(i3d*j3d*hh) + (i3d*jj) + ii;
   }
   if (value_range==2){
      if (what==1){ 
         set_bit1(state1,poss);
         if (diff_plot){ 
             if (oned) set_bit1(state1,poss+lineL/2);
             else if (twod) set_bit1(state1,poss+i2d/2);
         }
      }
      else if (what==0){
          set_bit0(state1,poss);
          if (diff_plot){ 
             if (oned) set_bit1(state1,poss+lineL/2);
             else if (twod) set_bit0(state1,poss+i2d/2);
          }
      }
   }
   else{
      while(1){
         foreg_value=myrand()%value_range;
         if (foreg_value==backg_value) continue;
         else{ 
            set_value(state1,poss,foreg_value);
            if (diff_plot){ 
               if (oned) set_value(state1,poss+lineL/2,foreg_value);
               else if (twod) set_value(state1,poss+i2d/2,foreg_value);
            }
            break;
         }
      }   
   }
   seed_was_set=1;
   return(color1);
}

/*************draw stp frames, revise scale, revise pixmap***********/ 
void revise_various_stp_settings(ent_eeg *eg,int_stp *it){
 signed int z; 

       if (d_mode==1 /*&& !twod && !threed*/){              
          pixmap_width=eg->stpwidth+1;
	  /*allow for grap*/
          if (eg->showlookupfreq==1 ||
                  eg->showlookupfreq==2 || eg->showeeg==1) 
                    pixmap_width+=(signed int)eg->eegwidth;
          /*restrict width to window*/
          if (pixmap_width>Maxx || pixmap_width<=0 ) pixmap_width=Maxx;
#         if __UNIX__  
             reallocate_pixmap(0,0,pixmap_width,Maxy, 
                                   it->offscreen_pixmap);	
             *current_draw = *it->offscreen_pixmap; 
#         endif    
          if (eg->showeeg)draw_stpframe(eg->stpwidth,eg->eegwidth);
          if (eg->showlookupfreq)
		draw_stpframe(eg->stpwidth,eg->lookupfreqwidth);
#         if __UNIX__  
                  *current_draw = W;
#         endif  
       }
       else if (d_mode==3){ /*2d axonometric*/ 
	  pixmap_width=eg->stpwidth; /*restrict pixmap just to stp*/
         /*restrict width to window*/
         if (pixmap_width>Maxx || pixmap_width<=0 ) pixmap_width=Maxx; 
#        if __UNIX__ 
            reallocate_pixmap(0,0,pixmap_width,
		              Maxy, it->offscreen_pixmap);
#        endif
       }         
        
       else if (d_mode==2){
          pixmap_width=it->fscale*i2d+((double)it->fscale)/2+1;
	  /*allow for division*/
          if (diff_plot) pixmap_width+=(it->fscale*it->diffgap);
          /*restrict width to window*/
          if (pixmap_width>Maxx || pixmap_width<=0 ) pixmap_width=Maxx;
#         if __UNIX__ 
             reallocate_pixmap(0,0,pixmap_width,
	         it->fscale*j2d+1, it->offscreen_pixmap);
             *current_draw = *it->offscreen_pixmap;
#          endif     
	   draw_2d_frame(eg,it);
#          if __UNIX__
            draw_2d_frame(eg,it);
            *current_draw = W;
#         endif  
       }
       else if (d_mode==4){
         pixmap_width=i3d*it->fscale+j3d*it->fscale*sin(PI/4)+1;
         /*allow for division*/
         if (diff_plot) pixmap_width+=(it->fscale*it->diffgap);
         /*restrict width to window*/
         if (pixmap_width>Maxx || pixmap_width<=0 ) pixmap_width=Maxx;
#        if __UNIX__
            reallocate_pixmap(0,0,pixmap_width,
	       j3d*it->fscale*sin(PI/4)+h3d*it->fscale+1,it->offscreen_pixmap);
#         endif  
      }                           
                     
  /*redraw frames*/
  if (d_mode==2) draw_2d_frame(eg,it);
  if (eg->showeeg) draw_stpframe(eg->stpwidth,eg->eegwidth);
  if (eg->showlookupfreq)
	draw_stpframe(eg->stpwidth,eg->lookupfreqwidth);	
  if (eg->showlookupfreq && !(d_mode==2 && scrolling==1)){		  
     eg->startxbox=eg->stpwidth+
	 (signed int)eg->lookupfreqwidth+vgax(10);
     eg->xboxmax=eg->startxbox+(signed int)eg->lookupfreqwidth;
     if (eg->showlookupfreq!=2) //input-histogram frame
       draw_box(-1,eg->startxbox-3,eg->startybox-2,
	      eg->xboxmax+2,eg->yboxmax+1,1,0);
     for (z=it->tablemax;z>=0;z--) eg->oldbar[z]=0;
     eg->thisxbox=eg->startxbox-1;
     eg->thisybox=eg->startybox-1;
  }
  /*it->fsep=2->1 pix div, it->fsep=1-> no div*/
  /*superseeded by show_2d_divs*/
  /*if (it->fscale>vgax(5)) it->fsep=2;
    else it->fsep=1;*/

   if (scrolling==1){
     if (nowscrolling==1){
#       if __WATCOM__
	    freeimage(stpimage);
#       endif
	//moveto(getx,gety+it->fscale+1);
	moveto(0,0);
        nowscrolling=0;
     }                           
   }
   if (d_mode==3){
      it->strip=it->downy=0;
      it->axo_cell_h=sin(PI/4)*it->fscale;
      it->wx=it->fscale*i2d;
      it->aa=it->axo_cell_h*j2d;
      it->polyx=0;
      it->polyy=it->axo_cell_h*j2d;
      moveto(it->polyx,it->polyy);
      draw_axon_plane(it->fscale,gety-1,it->draw_3d_grid);
   } 
   else if (d_mode==4){
      it->axo_cell_h=sin(PI/4)*it->fscale;
      it->wx=it->fscale*i3d;
      it->aa=it->axo_cell_h*j3d;     
      if (it->fscale>vgax(5)) it->fsep=2;
      else it->fsep=1;
      it->strip=0;
      it->downy=1;
   
      it->polyx=0;
      it->polyy=it->aa+it->fscale;
      moveto(it->polyx,it->aa);
      draw_axon_plane(it->fscale,gety,it->draw_3d_grid);
      freeimage(boximage[16]);
      draw_box(16,0,0,i3d*it->fscale+j3d*it->fscale*sin(PI/4),
		     j3d*it->fscale*sin(PI/4)+h3d*it->fscale,0,-1);    
   }                      
}
/********* clear area of space-time pattern (and eeg/entropy plot) ******/
void clear_stp(ent_eeg *eg,int_stp *it){
 signed int xlimit=0,ylimit=0;
                            
     if (d_mode==2){ 
        if (diff_plot) ylimit=it->fscale*(j2d*2+it->diffgap)+1;
        else ylimit=it->fscale*j2d+1;
        if (ylimit>Maxy || stpgraph>0) ylimit=Maxy;
        xlimit=eg->stpwidth;
        if (stpgraph>0) xlimit+=(eg->eegwidth+vgax(12));
     }
     if (d_mode==4){ 
        ylimit=h3d*it->fscale+j3d*it->fscale*sin(PI/4)+vgax(10)+1;
        if (diff_plot) ylimit=2*ylimit+it->diffgap*it->fscale+1;
        if (ylimit>Maxy || stpgraph>0) ylimit=Maxy;
        xlimit=eg->stpwidth;
        if (stpgraph>0) xlimit+=(eg->eegwidth+vgax(12));
	
     } 
     setviewport(0,0,xlimit,ylimit,1);                     
     clearviewport();
     setviewport(0,0,Maxx,Maxy,1);
     setcolor(white);                          
} 
/**** clear area of lookup histogram when resetting space-time pattern ******/
void clear_lookuphist(ent_eeg *eg){
     if (d_mode==2 && scrolling==1) return;                             
     if (stpgraph>0){
        if (!(eg->lookup_entropy /*&& eg->barno>64*/)){
	   if (eg->startxbox-3<Maxx)
	      draw_box(-1,eg->startxbox-3,eg->startybox-2,
				    eg->xboxmax+3,eg->yboxmax+2,0,0);
        }			   
     }
}
/**** reset width of space-time pattern, contract/expand/change mode *******/
void reset_stpwidth(ent_eeg *eg,int_stp *it){
      
     if (d_mode==1){
        eg->stpwidth=lineL*it->fscale+vgax(10);
	if (diff_plot) eg->stpwidth+=
	     it->diffgap*it->fscale+(lineL/2)*it->fscale+vgax(10);
     }
     else if (d_mode==2){
	    if (diff_plot) eg->stpwidth=
                i2d*it->fscale+it->fscale*it->diffgap+vgax(10);
	    else eg->stpwidth=i2d*it->fscale+vgax(10);
     }
     else if (d_mode==3){	 
	   eg->stpwidth=i2d*it->fscale+j2d*it->fscale*
                                             sin(PI/4)+vgax(10);
     }
     else if (d_mode==4){
	   if (diff_plot) eg->stpwidth=
                i3d*it->fscale+2*j3d*it->fscale*sin(PI/4)+
                                 it->fscale*it->diffgap+vgax(10);
	   else eg->stpwidth=i3d*it->fscale+j3d*it->fscale*
                                              sin(PI/4)+vgax(10);
    }
}

/**************** interupt key index, Dec 93 *****************/
/*
£: ---available, not on most keyboards! 
!: for 1d stp, 2d stp, toggle division line color black/white, march 07, appears if divs set (with i)
@  toggle node outline for circles, applies in 2d (+time, diagonal scrolling, and in "graph_layout"
#: toggle scrolling, 1d, 2d+time, 2d diagonal, and netgraph, £ alternative keyboard (DOS)
~: reset last seed, which was set on-the-fly
$: makesound - DOS only
%: toggle lookup freq histogram (lhf) - graph of lfh
^: toggle 0 color background<->grey (not if d_mode>=3)
&: new option Dec 2016 (for new Dell) to increase to number of
   hist bars allowed before a new hist column is required. 
*: toggle pause on screenfull,
    when space time patterns reach bottom of screen
(: restore default: input-entropy histogram)
): amplify the bars: input-entropy histogram
-: (dash) toggle cell color black-yellow for value-range=2,
   at same time,  toggle pattern filtering while histogram filtering scheme remains visible.
   (restore defaut colors for v>=3 : not sure this works)   
_: (underscore) new option Dec 2016 (for new Dell) to reduce bar size for input-histogram
¬:  ------------------------available but does not respond??
+: pause at each itteration (step back, save, interrupt ops, on-the-fly-ops)
   (note: to pause at each x time-steps, interrupt ops 'N' to set x, 
   then 'x' at each puase)
=: toggle diffplot dontkeep/keep damage; if showing diff histogram
 			                  interrupt for options
   alternatively: to anti=filter,  compliment color_filter

{: tog update_probability
}: tog out_prob,temp_out_prob
[: random isotropic+legal
]: deactivate random isotropic+legal for random bit/value flip with '1'
|: toggle between periodic and null boundary conditions, 1d,2d,3d
:: load rule from statistical sample, 
   previous index (if sample loaded) (for next index enter w)

;: density return plot: to show the density at x=t, y=t-1 --june2013 for JM
" (") : tog show details of lu_entropy at each time-step, for pulsing
<: alter stp_speed - slower
>: alter stp_speed - max
,: (coma) toggle to draw history lines in entropy-density and density return map plots
.: toggle dot inside cell (not for 3d or 2d+t)

?: Jan 2020 - for regular wiring 1d, 2d, 3d, select an index to flip. Can be restored with '2'.
            - if iso is active, index from iso-ruletable
   else -- April 2018 - if random wiring is active, randomy rewire at each time-step,
			according to random wiring (inc special) paramiters initially set

   July2021 -- for special case 3x3 iso-patterns set, /=countdown, \=countup

/: set new random block acc to fraction values (block-size was defined when setting seed) sim to 'v',
   or special case enter / for 21 4bit 3x3 iso-patterns in sequence forward.
\: set new random seed acc to fraction values similar to '4'
   or special case enter \ for 21 4bit 3x3 iso-patterns in sequence backward.
   special case is: if (iso_tablemax==101 && twod && value_range==2)

0: toggle between oldlookuphist and newlookuphist
1: random bit flip/value flip
`: flip to 0 (zero) --- left single inverted comma (to make "ideal" glider-gn CA
2: restore bit/value flip
3: toggle nhood color<->cell value
4: set new random seed
5: v=2 set positive singleton seed 000010000 or
   v>=3 set rnd singleton on rnd other background
6: set negative singleton seed 111101111 or
   v>=3 set rnd singleton on zero background
7: toggle local...nonlocal wiring (if nonlocal was set)
8: toggle rulemix-rule[0] - only (if rulemix was set)
9: set complex rule at random from statistical sample?? (if stat sample loaded?)
   or toggle stat_patch, i.e. deactivate/activate 
   -- if active, 'w' ":" restricted to patch, and also automatic blocks.
0: toggle between oldlookuphist and newlookuphist (in groups if long lookuptable)
a: remove all filters from space-time patterns
A: set an Altenberg rule at random
b: set nhood 0 -> 0, for stable zero background (rule,t-code,k-code,tot_only)
B: flip allv->v
c: contract scale
C: set random chain rule, or all chain rules for rule-mix
d: rearange (shuffle) v colors at random (works for v=2 as well as for V>2)
D: max 2 converging series return map: t (x-axis) against t+1 (x-axis) 
e: expand scale
E: create rule sample
f: filter biggest unfiltered bar in histogram
F: find and unfilter smallest filtered bar in histogram
g: load glider rules
G: in showlookupfreq: change analysis (entropy/density) generation size. 
        Select gene if single entropy.
h: toggle 1.normal color
	  2.frozen cells lightred - rest normal
	  3.frozen cells lightred - rest background
	  4.frequency of max-v in x-time step window
H: change generation size, frozen cells
i: show divisions in 1d stp or 2d stp
I: toggle: 3d -- between balls an parallelograms (as before)
               2d -- no effect
               2d+time -- between parallelograms and balls
               diagonal scrolling -- between squares/hexagons and balls
j: toggle justfuz - justentropy - both
J: suppess 2d diagonal scrolling stp, to show graph only (for 1d 'tube')
k: set random k-code/s
K: set rantom t-code/s
l: flip one bit/value in current state at random position
L: new central block, keep rest
m: move 1 or more wires
M: Majority rule
n: decreace CA size by 1 (1d only)
N: increace CA size by 1 (1d only)
o: restore original seed
O: restore original rule/s
p: draw plane in axonometric (2d-time (old) only)
P: skip given no of time-steps
q: quit - get interrupt options - 'q' again to  backtrack to previous promps

Q:  ------------------------available, below is superseded
    quit - interrupt -  but dont show interrupt window.
   'q' to carry on without interrupt window,  'Q' again to revert.
   note bottom right prompt.

r: set random rule/s where all zeros->zero, i.e. zero background is stable.
R: set random rule/s, no bias as above 
s: toggle density (eeg)...showlookupfreq
S: toggle space-time patterns on-off (to speed up other functions)
t: toggle 2d<->2d+time (d_mode=3)
   if d_mode=3 (3d presentation) toggle 3d grid
T: toggle 1d<->2d<->3d<->1d
u: show graph eeg...lookup_entropy
U: toggle between parralel and sequential updating
v: set new random block (block-size was defined when setting seed)
V: load rule from statistical sample, set index
w: load rule from statistical sample, 
   next index (if sample loaded) (for previous index enter : (colon)
W: reset number of wires to move, but dont move
x: toggle: slant-unslant stp (for 1d even k)
                          or 2d square-hex layout
X: toggle remove - restore interrupt key index
y: toggle space matrix on-off 
Y: toggle partial-order, upadate sequential rand
                    subsets of the network
z: flip for lower Z (full lookup only)
Z: flip for higher Z (full lookup only)
----------------------------------------------------------------*/
void interrupt_key_index(ent_eeg *eg,int_stp *it){

   signed int xbox,tempx,tempy;
   float change_vsapce,temp_CWidth,temp_CHeight;

   set_medium_font();

#  if __UNIX__
      if (Maxy<= 700) change_vsapce=.95;
      else change_vsapce=1.0;
      /*change_vsapce=1;*/
#   elif __WATCOM__
       if (hires==0) change_vsapce=.9;
       else if (hires==1) change_vsapce=.85;
       else change_vsapce=.7;
#   endif
   /*taller box for DOS*/
#  define movedown moveto(xbox,gety+CHeight*change_vsapce);
#  define moveup moveto(xbox,gety-CHeight*change_vsapce);
#  if __UNIX__
#     define movedown_plus moveto(xbox,gety+CHeight);
#   elif __WATCOM__
#     define movedown_plus moveto(xbox,gety+CHeight*change_vsapce*1.2);
#   endif
	tempx=getx;
	tempy=gety;
	//xbox=Maxx-vgax(130);
        /*keep the width constant*/
        sprintf(textb[10], /*longest string in on-the-fly box*/
		"7/|..local-nonlocal /  periodic-null XX");
        moveto(vgax(0),-50); /* y off the screen*/
        outtext(textb[10]);/*to get length of text*/
        xbox=Maxx-getx;

#  if __UNIX__
	draw_box(-1,xbox-3,Maxy-vgay(424),Maxx-2,Maxy-2,1,0);
#   elif __WATCOM__
	draw_box(-1,xbox-3,vgay(22),Maxx-2,Maxy-2,1,0);
#  endif
	setcolor(lightred);
	if (tot_only==0) outtext("on-the-fly key index"); 
        else outtext("on-the-fly key index: TFO-mode");
	setcolor(white);
#  if __UNIX__
	line(xbox-1,gety+CHeight+1,Maxx-4,gety+CHeight+1);
#  endif
	movedown_plus;
	/****************** updating ***********************/
	setcolor(lightred);
	outtext("  updating (tog)");
	setcolor(white);
	movedown;
	if (it->temp_seq_update==0) sprintf(textb[0],"U/Y..sync-seq/");
	else  sprintf(textb[0],"U/Y..seq-sync/");
        if (it->partial_order==0)  sprintf(textb[1],"sync-porder");
	else  sprintf(textb[1],"porder-sync");
        sprintf(textb[3],"%s%s",textb[0],textb[1]);
        outtext(textb[3]);
        movedown;
        outtext("{/}..prob:");
        if (temp_update_prob==1) sprintf(textb[0],"update1-%.2f/ ",update_prob);
        else sprintf(textb[0],"update%.2f-1/ ",temp_update_prob);
        outtext(textb[0]);
        if (temp_out_prob==1) sprintf(textb[0]," output1-%.2f",out_prob);
        else sprintf(textb[0]," output%.2f-1",temp_out_prob);
        outtext(textb[0]);
	movedown_plus;
	/****************** rules ***********************/
	setcolor(lightred);
	outtext("  change rule");
	setcolor(white);
	movedown;
        if (tot_only==0) outtext("r,R/K/k..rnd rule/tcode/kcode");
        else{
           if (totalistic==1) outtext("r,R..rnd tcode");
           else if (totalistic==2) outtext("r,R..rnd kcode");
        }
        movedown;
	if (oned || (twod && nhood>=2 && nhood<=10) ||
	              (threed && (nhood==6 || nhood==7))){
           if (tot_only==0 && set_iso_input_histogram==0){
	      if (set_iso_bitflip==0) outtext("[/]..iso/togflip(off)");
              else outtext("[/]..iso/togflip(on)");
	      movedown;
              /* '[' transforns to rule to isotropiuc
                 ']' if on (1) bitflp will flip rand iso-group
		     if off (0) bitflp will flip one rand output in rule*/
           }
	}   
        if (tot_only==0) outtext("O/A/M/C..Orig/Alt/Maj/Chain");
        else if (tot_only==1){
           if (totalistic==1) outtext("O/M..Orig/Maj");
           else if (totalistic==2) outtext("O/A/M..Orig/Alt/Maj");
        }
	movedown;
	outtext("1/2/?..rnd bitflip/restore");
        //else outtext("1..rnd bitflip at index 0");
	movedown;
	if (!rulemix && tot_only==0){
	   outtext("Z/z..force Z higher/lower");
	   movedown;
	}
	outtext("b/B..flip all0s->0/allVs->V");
        movedown;
        
	if (rulemix==1 && nhood_mixed==0){
	   if (it->rule_unmixed==0) outtext("8..rulemix-single");
	   else outtext("8..single-rulemix");
           movedown;
	}
        moveup;
	movedown_plus;
	/****************** rule samples ***********************/
	setcolor(lightred);
	outtext("  rule samples");
	setcolor(white);
        movedown;
	if (glider_rule_order==-1)
	      outtext("g..load glider rule (rnd)");
        else outtext("g..load glider rule (seq)");
	movedown;

	outtext("V..load,jmp,scan");
	movedown;
        if (totstatrules>0){
	   if (xstat1==0 && ystat1==0 && xstat2==0 && ystat2==0){/*patch not defined*/
               outtext("w/:/9..next/prev/rnd");               
           }
           else{ /*patch defined -- activate or not*/
              if (stat_patch==0) outtext("w/:/9..next/prev/tog patch(OFF)");
              else  outtext("w/:/9..next/prev/tog patch(ON)");
           }
           movedown;
        }

        if (eg->lookup_entropy){
	   outtext("E..create sample");
           movedown;
        }
        else{ /*lookup_entropy must be on to create sample*/
           outtext("uE..create sample");
           movedown;
        }	
        moveup;
	movedown_plus;
	/********************* wiring ********************/
	if (!loc_twod_fonly){
	   setcolor(lightred);
	   outtext("  change wiring");
	   setcolor(white);
	   movedown;
	   sprintf(textb[0],"m/W..move %lu wires/revise",wires_to_move);
	   outtext(textb[0]);
	   movedown;
           if (nonlocal==0) sprintf(textb[0],"7/|..local-nonlocal /");
           else if (wiring_madelocal==1) sprintf(textb[0],"7/|..local-nonlocal /");
           else if (wiring_madelocal==0 && nonlocal==1) 
                                  sprintf(textb[0],"7/|..nonlocal-local /");
           if (NULLboundaries==0) sprintf(textb[1],"  periodic-null");
           else sprintf(textb[1],"  null-periodic");
           outtext(textb[0]);
           outtext(textb[1]);
           movedown_plus;
           if (!loc_twod_fonly && wiring_madelocal==0 && nonlocal==1){
	      if (rnd_rewiring_each_timestep==0) sprintf(textb[0],"?..re-rnd(off)");
	      else sprintf(textb[0],"?..re-rnd(on)");
	      outtext(textb[0]);
	      movedown;
	   }
	}

	/******************* seed **********************/
	setcolor(lightred);
	outtext("  change seed/size");
	setcolor(white);
	movedown;	
        if (bias_percent_seed[8]=='p' || bias_percent_seed[8]=='v')
                     outtext("4/v/\\ / /..rnd seed/block/vseed/vblock");
	else outtext("4/v..rnd seed/block");
	movedown;
	outtext("l/L..rnd value/block flip");
	movedown;
        outtext("o/~..original/last");
	movedown;
        if (value_range>2) outtext("5/6..singleton zero/rnd");
        else outtext("5/6..singleton pos/neg");
        if (!rulemix && !twod && !threed && d_mode==1){
	   movedown;
	   outtext("N/n..inc/decrease 1 cell");
	}
	movedown_plus;
	/*******************  presentation **********************/
	setcolor(lightred);
	outtext("  presentation");
	setcolor(white);
	movedown;
        if (direction=='f' && limitcheck==0 && /*nhood%2==0 &&*/ 
	    stp && 
                ((oned && d_mode==1) || (twod && d_mode==2))   
                    && !nhood_mixed){
	   if (oned && d_mode==1){
              if (it->slant_even_k==1) outtext("x..tog slant(on-right)");
              else if (it->slant_even_k==2) outtext("x..tog slant(on-left)");
              else outtext("x..tog slant(off)");
           }
           else if (twod && d_mode==2){ /*toggle between square <--> hex*/
               if (it->slant_even_k==1) outtext("x..tog hex(on)");
               else outtext("x..tog hex(off)");
           }
	   movedown;
        }
        /*if 1d-mode, 2d-mode or 2d-mode diag scrolling is visible*/ 
        if (d_mode==2 || d_mode==1){ /*not if "balls" active*/ 
	   if (it->show_2d_divs==1) outtext("i/!..tog divs(on)/color");
	   else outtext("i/!..tog divs(off)/color");
           movedown;
        }

        /*superseded by @..tog cell outline*/
        /*else if (it->slice_3d==1){//without outline iteration is faster
          if (it->pi_outline==1)  outtext("i..tog balls outline(on)");
          else outtext("i..tog balls outline(off)");
          movedown;
	}*/

        if (graph_layout==1 || it->slice_3d==1){ 
           outtext("@..tog cell outline");
	   movedown;
	}

        if (graph_layout==0 && ((d_mode==2 && scrolling==1) || d_mode==3 || d_mode==4)){
	   if (it->slice_3d==0) outtext("I..tog balls (off)"); 
           else outtext("I..tog balls (on)"); 
           movedown;
	}

        if (d_mode>=3) outtext("3..tog incolor");
        else outtext("3/./^..tog incolor/dot/bground");
        movedown;
        if (value_range==2){
           if (bground=='b') outtext("d/-..colors:swap/white-yellow");
           else if (bground=='w') outtext("d/-..colors:swap/black-blue");
        }
        else outtext("d/-..tog shuffle colors/restore");
	movedown;
	outtext("S..tog space-time display");
	movedown;
        if (it->skip_timesteps==1)
           sprintf(textb[0],"P..tog skip steps=%d (on)", time_skip);
        else sprintf(textb[0],"P..tog skip steps=%d (off)",time_skip);
        outtext(textb[0]);
	movedown; 
        
#       if __WATCOM__ /*not xwindows*/
	   outtext("$..tog sound");
	   movedown
#       endif
	outtext("e/c..exp/contr scale");
        movedown_plus;
	/******************  1d 2d 3d ***********************/
        if (diff_plot==0){
	   setcolor(lightred);
	   outtext("  1d 2d 3d");
	   setcolor(white);
           movedown;
           if (d_mode==3 || d_mode==2){
              if (d_mode==2) outtext("t..tog 2d-2d+time");
              else if (d_mode==3) outtext("t..tog 2d+time-2d");  
              movedown;
	   }
           else if (d_mode==4){
              outtext("t..tog grid3d");
              movedown;
	   }
           if (d_mode!=3){ 
              if (d_mode==1) outtext("T..tog 1d-2d-3d");
              else if (d_mode==2) outtext("T..tog 2d-3d-1d");
              else if (d_mode==4) outtext("T..tog 3d-1d-2d");
              movedown;
           }
	   if (d_mode==3 || (d_mode==2 && scrolling==1)){
              /*tog 2d+time balls/parallelograms, or scrolling squares/hex or balls*/ 
              if (d_mode==2 && scrolling==1) outtext("p/I/J..tog plane/balls/invisible");
              else outtext("p/I..tog plane/balls");
              movedown;
	   }        
           /*else if (threed==3 && d_mode==4){
              //show 3d network in successive horiz slices ??? revise this
	      outtext("I..tog 3d slice");
              movedown;
	   }*/
           else if (d_mode==4){ 
              /*show 3d networkballs in successive horiz slices*/
	      outtext("I..tog balls");
              movedown;
	   }
           moveup;
           movedown_plus;           
	}
	/******************** frozen cells *********************/
	   setcolor(lightred);
	   if (eg->showlookupfreq) outtext("  frozen/filter");
           else outtext("  filter");
	   setcolor(white);
  	   movedown;
	   if (it->frozen_islands==0)      outtext("h..nor-f1-f2-bin");
	   else if (it->frozen_islands==1) outtext("h..f1-f2-bin-nor");
	   else if (it->frozen_islands==2) outtext("h..f2-bin-nor-f1");
           else if (it->frozen_islands==3) outtext("h..bin-nor-f1-f2");
	   movedown;
	   sprintf(textb[0],"H..f-gens(%d)/bins(%d)",frozen_gens,num_bin_bound+1);
	   outtext(textb[0]);
           if (stpgraph){	   
	      movedown;
              outtext("f/F/a/=/-..filter/undo/all/anti/app");
           }
	   movedown_plus;
        
	/********************  analysis *********************/
        setcolor(lightred);
	outtext("  analysis");
	setcolor(white);
	movedown;
	if (stpgraph){
           if (stpgraph>1 && eg->lookup_entropy==0){
              if (eg->showlookupfreq==1 && (it->tablemax+1)>64) 
                                      sprintf(textb[1],"");
              else if (eg->showlookupfreq==1 && (it->tablemax+1)<=64) 
                                      sprintf(textb[1],"/1-time");
              else if (eg->showlookupfreq==2) sprintf(textb[1],"/time-1");             
              if (eg->new_hist==0)
                    sprintf(textb[0],"0/%%..tog lookhist:1-2%s",textb[1]);
              else if (eg->new_hist==1) sprintf(textb[0],"0..tog lookhist:2-1");
	      outtext(textb[0]);
              movedown;
	   }	   
	   if (eg->showlookupfreq){
               /*to amplify the bars: intut-entropy histogram*/
               outtext(")/(..lookhist: amplify/restore,log");
               movedown;
	       /*to amplify the bars: intut-entropy histogram*/
               outtext("_/&..lookhist bars: shrink/inc&col");
               movedown;
	       outtext("s..tog entropy-density");
               movedown;
               if (eg->showlookupfuz==0)
		  outtext("j..tog ent-in-both");
               else if (eg->showlookupfuz==1)
		  outtext("j..tog in-both-ent");
               else if (eg->showlookupfuz==2)
		  outtext("j..tog both-ent-in");
	   }
	   if (stpgraph==1) outtext("s..tog density-entropy");
	   movedown;
           if (stpgraph==1 && eg->showeeg==1){
	          if (it->time_step_density_plot) outtext(";/,..density return map/link");
                  else  outtext(";..density return map");
                  movedown;
	   }
           if (eg->showlookupfreq==1 && eg->new_hist==0){
              if (eg->lookup_entropy==0) outtext("u..entropy-density");
              if (eg->lookup_entropy==1) outtext("u/,/\"..entropy-density/link/wl");
	      movedown;
           }
	   /*if (eg->lookup_entropy){
	      outtext("E..entropy-sdev plot");
	      movedown;
	      }*/	   
	   if (single_entropy==0 && 
                       !(nhood_mixed && eg->showlookupfreq==1))
	       sprintf(textb[0],"G..a-gens (now %d)",gens);
	   else {
               if (oned) sprintf(textb[0],
		      "G..a-gens=%d pos=%d",gens,entropy_poss);
               else if (twod) sprintf(textb[0],
		     "G..a-gens=%d pos=%d,%d",
			  gens,entropy_poss%i2d,entropy_poss/i2d);
               else if (threed) sprintf(textb[0],
		     "G..a-gens=%d pos=%d,%d,%d",
			  gens,
                          entropy_poss%i3d,
                          entropy_poss%(i3d*j3d)/i3d,
                          entropy_poss/(i3d*j3d) );
	   }      
	   outtext(textb[0]);
	   movedown;           
	}
        /*outtext("D..tog Hamming plot-D");*/
        outtext("D..value return map");
        movedown;
        outtext("y..state-space matrix");
        if (diff_plot==1 || diff_plot==2){ /*not diff histogram where = is pause*/
           movedown;
           if (diff_plot==2) sprintf(textb[1],"%s","keep damage");
           else sprintf(textb[1],"%s","dont keep damage");
           sprintf(textb[0],"=..tog diff(%s):",textb[1]);
	   outtext(textb[0]);
        }
        movedown_plus;

	/********************  index, pause *********************/
	setcolor(lightred);
	outtext("  miscellaneous");
	setcolor(white);
	movedown;
	outtext("X..tog this index");
	movedown;
        if (scrolling==0){
	   if (stppause) sprintf(textb[1],"on");
	   else sprintf(textb[1],"off");
	   sprintf(textb[0],"*..tog endpause (%s)",textb[1]);
	   outtext(textb[0]);
	   movedown;
        }
        if (d_mode==1 || d_mode==2 || d_mode==3){
           if (scrolling==1) sprintf(textb[1],"on");
	   else sprintf(textb[1],"off");
	   sprintf(textb[0],"#..tog scrolling (%s)",textb[1]);
	   outtext(textb[0]);
	   movedown;
        }
	sprintf(textb[0],"+..tog time-step pause");
	outtext(textb[0]);
        movedown;
        sprintf(textb[0],"</>..slower/max speed");
	outtext(textb[0]);
	movedown;
#   if __WATCOM__
        sprintf(textb[0],"$..make sound");
	outtext(textb[0]);
	movedown;
#  endif
	/*outtext("q/Q..pause/no-options"); Q superseded*/
        outtext("q..pause");
	moveto(tempx,tempy);
        restore_def_font();
        onthefly_box_erased=0;
}

/************* on the fly interrups for stp  ****************/
void interrupt_stp(diff_var *dp,
                   auto_ent *ae,
                   ent_eeg *eg,
                   int_stp *it){
 
 char *temppoint;
 signed int xbox,tempx,tempy,z,zz,ii,jj,
   tempbytesL;
 unsigned int zu;

      /*reset state space matrix (if showing),*/ 
      /*reset ittcount, unless lookup hist being shown as graph*/
#     define reset_matrix \
	   if (show_ss_matrixF==1) show_statespace_matrix(NULL);\
           if (eg->showlookupfreq<2  && att_hist!=1) it->ittcount=0;

#     define set_entropy_pix_color \
	  if (eg->lookup_entropy || it->Hamming_plot){	\
	      if (eg->ecolor==yellow) eg->ecolor=lightred;\
	      else if (eg->ecolor==lightred) eg->ecolor=lightcyan;\
	      else if (eg->ecolor==lightcyan) eg->ecolor=green;\
	      else if (eg->ecolor==green) eg->ecolor=white;\
	      else if (eg->ecolor==white) eg->ecolor=yellow;\
	  }

#     define  toggle_yellow_white \
          if (ncolor==0 && value_range==2){\
                if (color_v[1]==white) color_v[1]=yellow;\
                else if (color_v[1]==yellow) color_v[1]=white;\
                show_multistate_color_key(0);\
                show_multistate_color_key(1);\
	  }

/*show index to interrupt keys*/
#  define showkey  interrupt_key_index(eg,it);
/*clear the difference plot buffer to retain damaged cells*/
#  define clear_diff_plot {\
      for (zu=0;zu<=bytesL;zu++) tempState[zu]=0;\
}
 /*draw a red line across plot to indicate change*/  
  if (limitcheck==0 && direction=='f'){
     if (
      /*updating*/
      is[0]=='U'||is[0]=='Y'||
      /*rules*/
      is[0]=='r' ||is[0]=='R'||is[0]=='k'||is[0]=='K'||
      is[0]=='['||
      is[0]=='O'||is[0]=='A'||is[0]=='M'||is[0]=='C'||
      is[0]=='1'||is[0]=='2'||is[0]=='Z'||is[0]=='z'||
      is[0]=='b'||is[0]=='B'||
      /*rule samples*/
      is[0]=='g'||is[0]=='V'||is[0]=='w'||is[0]==':'||is[0]=='9'||
      /*rule/s:  toggle single/mixed*/
      is[0]=='8'||       
      /*wiring*/
      is[0]=='7'||is[0]=='m'||is[0]=='W'||is[0]=='|'||
      /*change graph entropy/density*/
      is[0]=='s'||
      /*skip steps*/
      is[0]=='P'||
      /*seed*/
      is[0]=='4'||is[0]=='5'||is[0]=='6'|| 
      is[0]=='o'|| is[0]=='~'|| is[0]=='v'||is[0]=='l'||is[0]=='L'){

        if (eg->showeeg||eg->showlookupfreq){
#          if __UNIX__ /*clear pixmap*/
              *current_draw = *it->offscreen_pixmap;
#          endif	
	   setcolor(red);
	   if (eg->showeeg) line(eg->stpwidth, gety,
		   eg->stpwidth+eg->eegwidth,gety);
	   if (eg->showlookupfreq) line(eg->stpwidth, gety,
			 eg->stpwidth+eg->lookupfreqwidth,gety);
	   setcolor(white);		 
#          if __UNIX__ /*clear pixmap*/
              *current_draw = W;             
#          endif	
        }
        if (is[0]!='V' && ((d_mode==3 && it->screenend==0) || 
                    (d_mode==2 && scrolling && it->invisible==0)) )  
	  draw_axon_plane(it->fscale,it->polyy-1,it->draw_3d_grid);
      }
    start_switch:
      switch(is[0]){
	case 'f': case 'F': case 'a':{          
	    //unsigned long bigbar=0,smallbar=Maxu; 
	    signed int bigbar=0,smallbar=Maxint;
	    signed int biggest,smallest;

            if (eg->showlookupfreq==0) break;

             tempx=getx;
	     tempy=gety;
           
	     /*see also '=' to anti=filter,  compliment color_filter*/
	    if (is[0]=='f'){ /*filter next bigest bar*/
              /*same code for set_iso_input_histogram==1 and old rcode histogram)*/
	           //fprintf(stderr,"hist_order=");
		   for (z=it->tablemax; z>=0; z--){
		      //fprintf(stderr," %lu",hist_order[z]);
                      if (bigbar<hist_order[z] && get_bit(color_filter,z)==0){
                         bigbar=hist_order[z];
                         biggest=z; 
                      }
	           }
                   //fprintf(stderr,"\nfilter biggest=%d",biggest);
                   if (get_bit(color_filter,z)==0) set_bit1(color_filter,biggest);
             }
             /*find and unfilter least frequent filtered bar in histogram*/
	     else if (is[0]=='F'){
	           /*if (set_iso_input_histogram==1) 
                         fprintf(stderr,"\niso-rule-hist=%d",it->tablemax+1);
			 else fprintf(stderr,"\nrcode-hist=%d",it->tablemax);*/ 
                   for (z=it->tablemax; z>=0; z--){
                      if (smallbar>=hist_order[z] && get_bit(color_filter,z)==1){
                         smallbar=hist_order[z];
                         smallest=z;
                      }
	           }
                   //fprintf(stderr,"unfilter smallest=%d",smallest);
                   if (smallest>=0) set_bit0(color_filter,smallest);
             }	    
             else if (is[0]=='a'){ /*remove all filters + block marks*/
	        for (z=it->tablemax; z>=0; z--){ 
                    set_bit0(color_filter,z);
                    //set_bit0(mutation_filter,z); mutations must be undone with '2'
                } 
             }
              /*draw a line in eeg/entropy plot*/ 
             if (eg->showeeg || eg->showlookupfreq){
#               if __UNIX__ /*clear pixmap*/
                   *current_draw = *it->offscreen_pixmap;
#               endif	
	        setcolor(red);
	        if (eg->showeeg) line(eg->stpwidth, gety,
		      eg->stpwidth+eg->eegwidth/6,gety);
	        else if (eg->showlookupfreq) line(eg->stpwidth, gety,
			 eg->stpwidth+eg->lookupfreqwidth/6,gety);
	        setcolor(white);
                	 
#               if __UNIX__ /*clear pixmap*/
                    *current_draw = W;             
#               endif
		/*show the rule-table index*/
            }
            
             break;
	 }

         /*superseded because hide-W in interrupt_stp_box(
                     does the same job, and Q was confusing*/
	 /*case 'Q':
             stppause=2;
             draw_bottom_title(0);              
             if (draw_hint_box(1,0,"ops-Q cont-ret:",vgax(500))=='Q')
                 stppause=1;
             forward_onthefly_bottom_prompts();
             sprintf(textb[0],"scale=%d",it->fscale);
                        draw_hint_box(0,0,textb[0],vgax(500));
			break;*/

	 case 'U':/*toggle between parralel and sequential updating*/
	     if (it->temp_seq_update>0) it->temp_seq_update=0; 
	     else{
                 it->temp_seq_update=seq_update;
                 if (it->temp_seq_update==0) it->temp_seq_update=1;
             }
	     if (it->keyindex==1) showkey;
             toggle_yellow_white;
             reset_matrix;
	     break;
         case '{': /*tog update prob*/
	      if (temp_update_prob<1.0) temp_update_prob=1.0;
              else if (temp_update_prob==1.0) temp_update_prob=update_prob;
              /*fprintf(stderr,"\n temp_update_prob=%.2f update_prob=%.2f",
		temp_update_prob,update_prob);*/ 
              if (it->keyindex==1) showkey;
              toggle_yellow_white;
              reset_matrix;
	      break;
         case '}': /*tog output prob*/
	      if (temp_out_prob<1.0) temp_out_prob=1.0;
              else if (temp_out_prob==1.0) temp_out_prob=out_prob;
              /*fprintf(stderr,"\n temp_out_prob=%.2f out_prob=%.2f",
		            temp_out_prob,out_prob);*/ 
              if (it->keyindex==1) showkey;
              toggle_yellow_white;
              reset_matrix;
	      break;

         case 'Y':/*toggle partial-order, upadate sequential rand
                    subsets of the network*/
             it->partial_order=abs(it->partial_order-1);
             if (it->keyindex==1) showkey;
             toggle_yellow_white;
             reset_matrix;
             break;
         case 'S':/*toggle space-time patterns on-off*/
            stp=abs(stp-1);
	    break;
         case 'P':/*skip given no of time-steps*/
            stp=1;
            it->skip_timesteps=abs(it->skip_timesteps-1);
            if (it->keyindex==1) showkey;	
	    break; 
         case '=':            
	    /*toggle diffplot dont keep/keep damage*/
	    /*if showing diff histogram interrupt for options*/
	    if (diff_plot || att_hist){
	       if (diff_plot==3 || diff_plot==4 || att_hist)
			              dp->pause_dam_hist=1;
	       else{
		  if (diff_plot==1) diff_plot=2;
		  else if (diff_plot==2) diff_plot=1;
		  clear_diff_plot;
		  if (it->keyindex==1) showkey;
	       }
	     }
	     else{ /*to anti=filter,  compliment color_filter*/
	       for (z=it->tablemax; z>=0; z--)
		    set_bit(color_filter,z,abs(get_bit(color_filter,z)-1));
	     }
             break;             

           case '#':/*toggle scrolling, '&' was same for Genaro: superseded*/   
	      /*if (oned || twod){*/ /* +scroll 2d*/
             if (diff_plot && twod) break;
             /*scroll: d_mode: 1=1d, 2=2d diagonal axo, 3=2d+time vertical axo*/ 
             if (d_mode==1 || d_mode==2 || d_mode==3){             
	        if (scrolling==1){
                  char was_scrolling;
		   was_scrolling=1;
                   scrolling=0;
		   /*nowscrolling=0;*/       	                    
                   if (nowscrolling==1){
#                     if __WATCOM__
		         freeimage(stpimage);
#                     endif
                   }
                   nowscrolling=0;			    
                   /*clear area of screen*/
                   if (was_scrolling==1 && d_mode==2){      
                      setviewport(0,0,Maxx,Maxy,1);
                      clearviewport();
                      //reset_stpwidth(eg,it);
		      revise_various_stp_settings(eg,it);
		      moveto(0,0);
		      it->downy=0;
                   }
                   else{
	              if (diff_plot) setviewport(0,0,
                          eg->stpwidth+lineL*it->fscale,Maxy,1);
	              else setviewport(0,0,eg->stpwidth,Maxy,1);  
		      clearviewport();
	              setviewport(0, 0, Maxx, Maxy, 1);
                   }     
                   if (was_scrolling==1 && d_mode==2) draw_2d_frame(eg,it);	
	        }
	        else if (scrolling==0){
                   scrolling=1;
                   //nowscrolling=0;
                   nowscrolling=1;
                   clearviewport();
                   //reset_stpwidth(eg,it);
                   revise_various_stp_settings(eg,it);                 
                   if (d_mode==2) it->downy=0;
	        }
                if (it->keyindex==1) showkey;
             }
             break;     
          case '+':
             /*pause at each itteration*/
             it->itt_step=1;
             break;
          case 'I':
	     if (graph_layout==0 && ((d_mode==2 && scrolling==1) || d_mode==3 || d_mode==4)){
                /*toggle: 3d -- between balls an parallelograms (as before)
                          2d -- no effect (as before)
                          2d+time -- between parallelograms and balls (as before)
                          diagonal scrolling -- between squares/hexagons and balls (added)*/
                it->slice_3d=abs(it->slice_3d-1);
                if (it->keyindex==1) showkey;
                break;
             }    
	  case 'J': /*suppess 2d diagonal scrolling stp, to show graph only*/
	     /*1d circle scrolls as tube - nice*/
	     if (d_mode==2 && scrolling==1){
                it->invisible=abs(it->invisible-1);
             }
             break;                       
	  case'h':
	     /*toggle 1.normal color
                  new:2.green tails on zero bkground to dynamic cells (gliders)
	              3.frozen cells lightred - rest normal
	              4.frozen cells lightred - rest background
	              5.frequency of max-v in x-time step window */ 
	     ncolor=0; /*restore cell color*/
	     it->cell_not_changed=0;
	     if (it->frozen_islands==0) it->frozen_islands=1;
	     else if (it->frozen_islands==1) it->frozen_islands=2;
	     else if (it->frozen_islands==2) it->frozen_islands=3;
             else if (it->frozen_islands==3) it->frozen_islands=4;
	     else if (it->frozen_islands==4){
                it->frozen_islands=0;
		show_multistate_color_key(0);
                show_multistate_color_key(1);
             }
	     if (it->keyindex==1) showkey;
	     tempx=getx;
	     tempy=gety;
             
	     if (it->frozen_islands){
	       signed int xbox,sx,bsize,bint;
                xbox=Maxx-vgax(170);
                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();
		bsize=CHeight;
		bint=bsize*1.5;
    
                if (it->frozen_islands==1){
		   sprintf(textb[0],
			"dynamic trace of %d time-steps on zero bground ",
						 frozen_gens);
		   outtext(textb[0]);
		   moveto(xbox,gety+CHeight);
		   sprintf(textb[0],"color key: trace=  ");
                   outtext(textb[0]);
		   setfillstyle(SOLID_FILL,darkgray);
		      bar3d(getx,gety,getx+bsize,gety+bsize,0,0);
		   moveto(xbox,gety+CHeight);
		   outtext("cells at present time-step according to value");
		}
		if (it->frozen_islands==2){
		   sprintf(textb[0],
			"frozen cells for at least %d time-steps",
						 frozen_gens);
		   outtext(textb[0]);
		   moveto(xbox,gety+CHeight);
		   sprintf(textb[0],"color key: frozen %d-0s=  ",value_range-1);
                   outtext(textb[0]);
		   setfillstyle(SOLID_FILL,magenta);
		      bar3d(getx,gety,getx+bsize,gety+bsize,0,0);
		   moveto(xbox,gety+CHeight);
		   outtext("cells not frozen shown according to value");
		}

		else if (it->frozen_islands==3){
		   sprintf(textb[0],
			 "frozen cells for at least %d time-steps",
						 frozen_gens);
		   outtext(textb[0]);
		   moveto(xbox,gety+CHeight);
                   
                   
                   sprintf(textb[0],"color key: froz %ds=  ",value_range-1);
                   outtext(textb[0]);
		   setfillstyle(SOLID_FILL,lightred);
		      bar3d(getx,gety,getx+bsize,gety+bsize,0,0);
		   moveto(getx+bint,gety);

		   if (value_range==2) sprintf(textb[0]," froz 0s= ");
                   else sprintf(textb[0]," froz %d-0s= ",value_range-2);
                   outtext(textb[0]);
		   setfillstyle(SOLID_FILL,green);
		      bar3d(getx,gety,getx+bsize,gety+bsize,0,0);
		   moveto(getx+bint,gety);

		   outtext(" not=");
		   setfillstyle(SOLID_FILL,black);
		      bar3d(getx,gety,getx+bsize,gety+bsize,0,0);
		   moveto(xbox,gety+CHeight);
		   outtext("% frozen:");

		}
		else if (it->frozen_islands==4){
                  unsigned char tempcolor;
		   sprintf(textb[0],"frequency of %ds in %d time-step window",
						 value_range-1,frozen_gens);
		   outtext(textb[0]);
		   moveto(xbox,gety+CHeight);
		   outtext("color key:  ");
		   sx=getx;
		   moveto(xbox,gety+CHeight+2);
                   sprintf(textb[0],"%d bins:",num_bin_bound+1);
		   outtext(textb[0]);
		   moveto(sx,gety-CHeight-2);
		   for (z=1;z<=num_bin_bound+1;z++){
		      if (z==1) tempcolor=freq_colors[0];
		      else if (z<num_bin_bound+1) /*intermediate colors*/
                                tempcolor=freq_colors[10*z/(num_bin_bound+1) -1];
                      else if (z==num_bin_bound+1) tempcolor=freq_colors[9]; 
                      setfillstyle(SOLID_FILL,tempcolor);
		      /*setfillstyle(SOLID_FILL,freq_colors[z-1]);*/
		      bar3d(getx,gety,getx+bsize,gety+bsize,0,0);
		      moveto(sx,gety+CHeight+2);
		      if (z<=num_bin_bound){
                         sprintf(textb[0],"%d",bin_bound[z]);
		         outtext(textb[0]);
                      }
                      else{
                         sprintf(textb[0],"%d",frozen_gens);
		         outtext(textb[0]);
                      }
		      moveto(sx+bint,gety-CHeight-2);
		      sx+=bint;
		      moveto(sx,gety);
		   }
		}
	     }
	     else{
                xbox=Maxx-vgax(205);
                /*draw_box(-1,xbox-3,2,Maxx-2,2+CHeight*3+vgay(6),0,0);*/
                if (it->keyindex==1) showkey;                
             }            
	     moveto(tempx,tempy);
             /*restore character size*/
             setviewport(0, 0, Maxx, Maxy, 0);    
             restore_def_font();
	     break;

	  case 'H':
	     /*change generation size, frozen cells*/
	     tempx=getx;
	     tempy=gety;
             setcolor(white);
	     sprintf(textb[0],
		"enter new 'frozen' Generation size (now %d):",
						    frozen_gens);
	     xbox=draw_prompt_box(2);
	     outtext(textb[0]);
	     input_string(3,1);
	     /*if (is[0]!=13 && atoi(is)>0){*/
                
	     /*free mem previous generation size*/
	     for (z=frozen_gens-1;z>=0;z--) free(it->last_state1[z]);
	     free(it->last_state1);
	     if (is[0]!=13 && atoi(is)>0) frozen_gens=atoi(is);
	     /*allocale mem new generation size*/
	     sprintf(textb[0],"carule");
	     if ((it->last_state1=
                     (char**)calloc(frozen_gens,sizeof(char*)))
				   ==NULL) outof_memory(textb[0]);
	     for (z=0;z<=frozen_gens-1;z++){
		    sprintf(textb[0],"it->last_state1[%d]",z);
		    if ((it->last_state1[z]=
                         (char *)calloc(bytesL,sizeof(char)))
				==NULL) outof_memory(textb[0]);
	     }
             /* num_bin_bound+1 cant be bigger than frozen_gens */
             if (num_bin_bound+1>frozen_gens){
              float freq_step;
	        num_bin_bound=frozen_gens-1;
                free(bin_bound);
                if ((bin_bound=
	             (signed int *)calloc(num_bin_bound+1,sizeof(signed int)))
			==NULL) outof_memory("(bin_bound");
                /*set the default bin boundaries*/
                freq_step=(float)frozen_gens/(num_bin_bound+1);
                for (z=1;z<=num_bin_bound;z++)
                         bin_bound[z]=(signed int)freq_step*z;
             }
	     moveto(xbox,gety+CHeight);
             sprintf(textb[0],
		"reset bin boundaries, enter new total (max %d, now %d):",
						    frozen_gens,num_bin_bound+1);
	     outtext(textb[0]);
	     input_string(2,1);
             erase_prompt_box(2);
           
             if (is[0]!=13 && atoi(is)>1 && atoi(is)<=frozen_gens){
                 float freq_step;
	           num_bin_bound=atoi(is)-1;
                  start_bin_bound: 
	           free(bin_bound);
                   if ((bin_bound=
	             (signed int *)calloc(num_bin_bound+1,sizeof(signed int)))
			==NULL) outof_memory("(bin_bound");
                   /*set the default bin boundaries*/
                   freq_step=(float)frozen_gens/(num_bin_bound+1);
                   draw_prompt_box(1);
		   outtext("unequal bins-u, equal-def:");
                   input_string(1,0);

                   if (is[0]=='u'){
                      for (z=1;z<=num_bin_bound;z++){
		         sprintf(textb[0],"enter bin boundary %d (def %d):",
			                z,bin_bound[z-1]+(signed int)freq_step);
                         draw_prompt_box(1);
		         outtext(textb[0]);
                         input_string(3,0);
		         if (is[0]!=13 && atoi(is)>0 && atoi(is)<frozen_gens 
                                   && atoi(is)>bin_bound[z-1])
		                               bin_bound[z]=atof(is);
                         else bin_bound[z]=bin_bound[z-1]+(signed int)freq_step;
		      }
                      if (bin_bound[num_bin_bound]>=frozen_gens){
                         draw_prompt_box(1);
                         outtext("invalid bin boundaries, cont-ret:");
                         input_string(1,0);
		         goto start_bin_bound;
                      }
                   }
                   else{ /*equal bins*/
                      for (z=1;z<=num_bin_bound;z++)
                         bin_bound[z]=(signed int)freq_step*z;
                   }
                   erase_prompt_box(2);
                   /*show the color key*/
                   is[0]='h';
                   /*show the bins frozen_islands setting*/
                   it->frozen_islands=2;
                   forward_onthefly_bottom_prompts();
                   goto start_switch;
             }            
 	     moveto(tempx,tempy);
	     if (it->keyindex==1) showkey;
             forward_onthefly_bottom_prompts();             
             /*show the color key*/
             is[0]='h';
             if (it->frozen_islands==1) it->frozen_islands=0;
	     else if (it->frozen_islands==2) it->frozen_islands=1;
	     else if (it->frozen_islands==3) it->frozen_islands=2;
	     else if (it->frozen_islands==0) it->frozen_islands=3;
             forward_onthefly_bottom_prompts();
             goto start_switch;
	     //break;            
	  case 'r': case 'K': case 'k': 
             /*random rule/s, tcode/s, kcode/s
	      'r' rnd rule but stable zero background, nhood 0 -> 0, 
              'R' for any rnd rule (applies also for tot_only==1)*/
	     it->color1=bit_flip(is[0],it->color1);
	     reset_matrix;             
	     set_entropy_pix_color;
	     if (eg->lookup_entropy==1) random_seed(it->color1,100,0);
             if (diff_plot==2) clear_diff_plot;
	     break;

          case 'R':{ /*random rule at [0] with preset proportions of
                           values, either as %s or numbers*/
	    signed int tablemax;
	     if (bias_percent_rule[8]=='p' || bias_percent_rule[8]=='v'){
	        if (tot_only==0){
		    if (set_iso_input_histogram==1) tablemax=iso_tablemax;
                    else tablemax= (signed int)pow(value_range,(double)nhood)-1; 
                }
                else if (tot_only==1){
                    if (totalistic==1) tablemax=nhood*(value_range-1);
                    else if (totalistic==2) tablemax=v_tablecodemax[nhood];
                }    
                if (tot_only==0){ 
                    if (set_iso_input_histogram==1) 
                           implement_fraction_values(1,0,iso_rule,tablemax+1);
                    else implement_fraction_values (1,0,carule[0],tablemax+1);
                }
                else if (tot_only==1){
                     if (set_iso_input_histogram==1) 
                           implement_fraction_values(1,0,iso_rule,tablemax+1);
		     if (totalistic==1) implement_fraction_values(1,0,cacode[0],tablemax+1);
		     if (totalistic==2) implement_fraction_values(1,0,v_code[0],tablemax+1);
                }
                it->color1=bit_flip('V',it->color1); /*just show the rule top-right*/
             }     
             else it->color1=bit_flip('R',it->color1); /*new random rule -no bias*/
             break;
          }
           
          case '[': case ']': /*random isotropic+legal rule/s*/
	     /*if iso-rule active, random isotropic is set with 'r', or 'R' to preserve value-mix*/
             if (tot_only==0 && set_iso_input_histogram==0){
	        if (is[0]=='['){
	           it->color1=bit_flip(is[0],it->color1); /*isotropic*/
	           reset_matrix;             
	           set_entropy_pix_color;
	           if (eg->lookup_entropy==1) random_seed(it->color1,100,0);
                   if (diff_plot==2) clear_diff_plot;
		}
		else if (is[0]==']'){
		   set_iso_bitflip=abs(set_iso_bitflip-1);/*changes rand iso-group*/
                   if (it->keyindex==1) showkey;
                   reset_matrix;          /*else '1' changes just one value*/
		}   
             }
	     break;
                    
          case 'x': /*toggle: slant-unslant stp (for 1d even k)
                          or 2d square-hex layout*/
             if (direction=='f' && limitcheck==0 &&
		 stp &&  ((oned && d_mode==1) || (twod && d_mode==2))){
                 if  (oned && d_mode==1){
		     if (it->slant_even_k==0) it->slant_even_k=1; /*slant right*/
                     else if (it->slant_even_k==1) it->slant_even_k=2; /*slant left*/
                     else if (it->slant_even_k==2) it->slant_even_k=0; /*slant off*/
                 }	         
                 else if (twod && d_mode==2){
                      it->slant_even_k=abs(it->slant_even_k-1);
                      clearviewport();
                      reset_stpwidth(eg,it); 
                      clear_stp(eg,it);
                      revise_various_stp_settings(eg,it);
                      moveto(0,0);                      
                 }
                 if (it->keyindex==1) showkey;
             }
             stagger_even_rows=it->slant_even_k;
             break;
          case 'O':{ /*restore original rule/s*/
            char temp_tot;
	     if (tot_only==1){
	        if (totalistic==1) load_last_rule(cacode[0],nhoodm[0]);
                else if (totalistic==2) load_last_rule(v_code[0],nhoodm[0]);
             }
	     else {
	       signed int thistablemax;
                temp_tot=totalistic;
	        totalistic=0;
	        load_last_rule(carule[0],nhoodm[0]);

                thistablemax= (signed int)pow(value_range,(double)nhood)-1;
                //convert to iso-rule
                isotropic_rule(0,carule[0],nhood,0,thistablemax,thistablemax,-2);
                for (z=it->tablemax; z>=0; z--){
                    set_bit0(mutation_filter,z);
                } 
                totalistic=temp_tot;
             }
             it->color1=bit_flip('O',it->color1);
	     reset_matrix;
	     set_entropy_pix_color;
	     if (eg->lookup_entropy==1) random_seed(it->color1,100,0);
             if (diff_plot==2) clear_diff_plot;
	     break;  
          }        
          case 'A':{ /*random rule from Lee Altenberg random set, 
                      if rule-mix, set all different rules */
             it->color1=bit_flip('A',it->color1);            
             reset_matrix;
	     set_entropy_pix_color;
	     if (eg->lookup_entropy==1) random_seed(it->color1,100,0);
             if (diff_plot==2) clear_diff_plot;
	     break;
          }
          case 'M':{ /*Majority rule*/
             it->color1=bit_flip('M',it->color1);                   
             reset_matrix;
	     set_entropy_pix_color;
	     if (eg->lookup_entropy==1) random_seed(it->color1,100,0);
             if (diff_plot==2) clear_diff_plot;
             
	     break;
          }
          case 'C':{ /*random chain rule, or rules for rule-mix*/
             it->color1=bit_flip('C',it->color1);
             reset_matrix;
	     set_entropy_pix_color;
	     if (eg->lookup_entropy==1) random_seed(it->color1,100,0);
             if (diff_plot==2) clear_diff_plot;
	     break;
          }            
	  case '1':/*random bit/value flip*/
             index_of_flip=-1;
	     it->color1=bit_flip('1',it->color1);
	     reset_matrix;
	     set_entropy_pix_color;
	     break;
	  case '`':/*change to zero*/
             index_of_flip=-1;
	     it->color1=bit_flip('`',it->color1);
	     reset_matrix;
	     set_entropy_pix_color;
	     break;   
	  case '2':/*restore bit/value flip*/
	     /*if (rulemix) break;*/
	     it->color1=bit_flipback(it->color1);
	     reset_matrix;
	     set_entropy_pix_color;
	     break;		  
	  case 'Z':/*flip for higher z*/
	     if (rulemix) break;
	     it->color1=bit_flip('Z',it->color1);
	     reset_matrix;
	     set_entropy_pix_color;
	     break;
	  case 'z':/*flip for lower z*/
	     if (rulemix) break;
	     it->color1=bit_flip('z',it->color1);
	     reset_matrix;
	     set_entropy_pix_color;
	     break;

          case 'b': /*set all0 -> 0, for stable zero background*/
             it->color1=bit_flip('b',it->color1);
	     reset_matrix;
	     set_entropy_pix_color;
	     break;

          case 'B':/*flip allV->V*/
	     it->color1=bit_flip('B',it->color1);
	     reset_matrix;
	     set_entropy_pix_color;
	     break;
          
	  case 'm':/*move 1 or more wires*/
	     if (!loc_twod_fonly) nonlocal=1;
	     it->color1=wire_move('m',it->color1);
             toggle_yellow_white;
	     if (it->keyindex==1 && nonlocal==0) showkey;
	     reset_matrix;
	     set_entropy_pix_color;
	     break;		  
	  case 'W': /*reset number of wires to move, but dont move*/
	     if (!loc_twod_fonly) nonlocal=1;
	     wire_move('W',it->color1);
	     if (it->keyindex==1) showkey;
	     reset_matrix;
	     set_entropy_pix_color;
	     break;
	  case 'g': /*load glider rules*/
	     if (no_glider_rules[value_range][(signed int)nhoodm[0]]>=1){
                toggle_yellow_white;
	        glider_rule(it);      
	        reset_matrix;
	        set_entropy_pix_color;
             }
             else inset_prompt_box(0,20,"glider sample not available",'m');
	     break;		 
	  case 'V':/*load rule from statistical sample, set index*/
	     tempx=getx;
	     tempy=gety;

             if (it->statrule_index==0 || it->statrule_index>totstatrules)
	                                 it->statrule_index=1;
	     it->statrule_index=stat_rule(0,it->statrule_index,it,eg->stpwidth);
             toggle_yellow_white;

	     reset_matrix;
	     set_entropy_pix_color;

             if (oned==1) random_seed(it->color1,100,0);
             else random_block(0,seglen,it->color1); /*changed 7 July 2013*/

	     it->screenend=1;
             forward_onthefly_bottom_prompts();
             interrupt_stp(dp,ae,eg,it);
	     moveto(tempx,tempy);
	     break;		 
          
          case 'w': case ':': {  /*load rule from statistical sample, 
		                next index 'w' or previous ':'*/
              signed int rulebytes,tablemax;
	     
	        tempx=getx;
	        tempy=gety;

                if (stat_patch==1){        
		   if (tot_only==0){ 
		      if (set_iso_input_histogram==1) tablemax=iso_tablemax;
                      else tablemax= (signed int)pow(value_range,(double)nhood)-1;
		   }
                   else if (tot_only==1){
                      if (totalistic==1) tablemax=nhood*(value_range-1);
                      else if (totalistic==2) tablemax=v_tablecodemax[nhood];
                   }
                   rulebytes=(signed int)ceil(value_bits * (double)(tablemax+1)/8);
                }

	        if (is[0]=='w'){
                   if (totstatrules==0) break;
                   if (it->keep_index==1) goto skip_rule_change;
                   if (stat_patch==0) it->statrule_index+=1;
                   else if (stat_patch==1){                    
                      /*fprintf(stderr," %lu",stat_patch_index);*/
                      while(1) {
                         stat_patch_index+=1;
                         if (stat_patch_index>=totstatrules) break;
                         else if (
		          statbuf[(stat_patch_index-1)*(rulebytes+2)+rulebytes] > ystat1 ||
                          statbuf[(stat_patch_index-1)*(rulebytes+2)+rulebytes] < ystat2 ||
                          statbuf[(stat_patch_index-1)*(rulebytes+2)+rulebytes+1] > xstat1 ||
                          statbuf[(stat_patch_index-1)*(rulebytes+2)+rulebytes+1] < xstat2 )
			     continue;
                         else break;
		      }
                      /*fprintf(stderr,"\n(%d %d %lu)",
			 statbuf[(stat_patch_index-1)*(rulebytes+2)+rulebytes],
                         statbuf[(stat_patch_index-1)*(rulebytes+2)+rulebytes+1],
			 stat_patch_index);*/

                      it->statrule_index=stat_patch_index;
	           }
	           if (it->statrule_index>=totstatrules){ 
                      it->statrule_index=1;
                      stat_patch_index=1;
                   }
                //fprintf(stderr,"*");
                }
                else if (is[0]==':'){
                   if (totstatrules==0) break;
                   if (it->statrule_index>1 && stat_patch==0) it->statrule_index-=1;
                   else if (stat_patch_index>1 && stat_patch==1){
		      /*fprintf(stderr," %lu",stat_patch_index);*/                 
                      while(1) {
                         stat_patch_index-=1;
                         //if (stat_patch_index<=1) break;
			 if (stat_patch_index==Maxlu) break;//stat_patch_index is unsigned long
                         else if (
		          statbuf[(stat_patch_index-1)*(rulebytes+2)+rulebytes] > ystat1 ||
                          statbuf[(stat_patch_index-1)*(rulebytes+2)+rulebytes] < ystat2 ||
                          statbuf[(stat_patch_index-1)*(rulebytes+2)+rulebytes+1] > xstat1 ||
                          statbuf[(stat_patch_index-1)*(rulebytes+2)+rulebytes+1] < xstat2 )
			        continue;
                          else break;
		      }
		      /*fprintf(stderr,"\n(%d %d %lu)",
		      statbuf[(stat_patch_index-1)*(rulebytes+2)+rulebytes],
                      statbuf[(stat_patch_index-1)*(rulebytes+2)+rulebytes+1],
		      stat_patch_index);*/

                      it->statrule_index=stat_patch_index;
	           }
                      
		   if (it->statrule_index==Maxlu){ //it->statrule_index is unsigned long
                      it->statrule_index=1;
                      stat_patch_index=1;
                   }                
	        }

	        stat_rule(1,it->statrule_index,it,eg->stpwidth);
                /*toggle_yellow_white;*/
                if (ncolor==0 && value_range==2){/*alternate white-yellow*/
                   if (color_v[1]==white) color_v[1]=yellow;
                   else if (color_v[1]==yellow) color_v[1]=white;
	        }

                skip_rule_change:
	        reset_matrix;
	        set_entropy_pix_color;
                /*new initial state*/
                /*if set in stat_rule(.. , and on-the-fly '4', 'v','5','6', Oct 2014*/
                if (it->seedORblock==0) random_seed(it->color1,100,0); /*the default, all*/
                else if (it->seedORblock=='v') random_block(0,seglen,it->color1); /*block*/
		else if (it->seedORblock=='5'){
                   /*v=2 set positive sinlgeton seed 000010000 or
                     v>2 set rnd singleton on rnd other background*/
		     it->color1=singleton_seed(1,it->color1);
                }
                else if (it->seedORblock=='6'){
                   /*v=2 set negative singleton seed 111101111 or
                     v>2 set rnd singleton on zero background*/
		     it->color1=singleton_seed(0,it->color1);
                }
                moveto(tempx,tempy);
	        break;
             }
	  case '9': /*complex rule at random from statistical sample
                     also: toggle stat_patch ON/OFF if active
                     to deactivate patch -- backtarck*/
	    if (totstatrules==0) break;
	     tempx=getx;
	     tempy=gety;
	     if (xstat1==0 && ystat1==0 && xstat2==0 && ystat2==0){
	        /*random but restricted to first 10% of sample with highest variability
                  otherwise most will be chaotic*/      
	        it->statrule_index=myrand()%(totstatrules/10);
	        stat_rule(1,it->statrule_index,it,eg->stpwidth);//show top-right info
                /*toggle_yellow_white;*/
                if (ncolor==0 && value_range==2){/*alternate white-yellow*/
                   if (color_v[1]==white) color_v[1]=yellow;
                   else if (color_v[1]==yellow) color_v[1]=white;
	        }
	        reset_matrix;
	        set_entropy_pix_color;
	        if (oned==1) random_seed(it->color1,100,0);
                else random_block(0,seglen,it->color1); /*changed 7 July 2013*/
	        /*if (it->a_index_sample==0) it->screenend=1;*/
             }             
             else{
                stat_patch=abs(stat_patch-1);
                stat_rule(1,it->statrule_index,it,eg->stpwidth);//show top-right info
                if (it->keyindex==1) showkey;
             }
             moveto(tempx,tempy);
	     break;
	
	  case '3': /*toggle nhood color<->cell value*/
	     if (att_hist!=2) ncolor=abs(ncolor-1);
	     break;

          case '.': /*toggle dot*/
             if (d_mode>=3) break; /*not for 3d or 2d+t*/
	     it->show_dots=abs(it->show_dots-1);
	     break;

          case '^': /*toggle 0 color background<->grey*/
             if (d_mode>=3) break; /*not for 3d or 2d+t*/
             /*there was a conflict here with shuffle-colors 'd' -fixed*/
             for (z=0;z<=value_range-1;z++){
                if (color_v[z]==black){
                   color_v[z]=darkgray;
                   break;
                }
                else if (color_v[z]==darkgray){
                   color_v[z]=black;
                   break;
                }
             }
             show_multistate_color_key(0);
             show_multistate_color_key(1);    
	     break;

          case '-':
             /*in spite of filtering, to toggle filtering in on/off with '-', June2020*/
	     it->filter_toggle=abs(it->filter_toggle-1);
             /*to restore default colors if altered with 'd' below*/
             if (ncolor==1){
                 tempx=getx;
	         tempy=gety; 
                 set_color_order_nhd(0);/*to restore default nhd colors*/
                 clear_lookuphist(eg);
                 revise_various_stp_settings(eg,it);
                 moveto(tempx,tempy);
             }
             else{/*toggle cell color white-yellow for value-range=2*/
	        if (value_range==2) {toggle_yellow_white}
                else{
                   setup_value_colors(0); /*to restore default*/
                   show_multistate_color_key(0);
                   show_multistate_color_key(1);
                }
             }
	     break;
		  
          case 'd':
	     if (ncolor==1){
               unsigned char tempcolor;
                tempx=getx;
	        tempy=gety;

                set_color_order_nhd(1); /*shuffle nhd colors except white and black*/

                clear_lookuphist(eg);
                revise_various_stp_settings(eg,it);
                moveto(tempx,tempy); 

             }
             else{
	        if (value_range==2){ /*swap forground-background*/ 
                  unsigned char tempcolor;
		    tempcolor=color_v[0];
                    color_v[0]=color_v[1];
                    color_v[1]=tempcolor;    
                }            
	        else rearange_value_colors(); /*rearange (shuffle) colors at random*/            
                show_multistate_color_key(0);
                show_multistate_color_key(1);
	     }       
	     break;

#         if __WATCOM__
		/*toggle sound*/
	  case '$':
		if (!makesound) makesound=1;
		else{
		   nosound();
		   makesound=0;
		}
		break;
#         endif  
	  
	  case 'y':/*toggle space matrix on-off*/
	     if (show_ss_matrixF==1){
		tempx=getx;
		tempy=gety;
		draw_box(-1,Maxx-vgax(136)-vgax(msize)-1,
		Maxy-2-vgay(msize)-1,
		Maxx-vgax(136),Maxy-2,0,0);
		show_ss_matrixF=0;
		moveto(tempx,tempy);
	     }
	     else{
		show_ss_matrixF=1;
		if (show_ss_matrixF==1) show_statespace_matrix(NULL);
	     }
	     break;
	     
          case 'j':
              /*toggle justfuz - justentropy - both*/ 
	      if (eg->showlookupfreq){
                 if (eg->showlookupfuz==0) eg->showlookupfuz=1;
                 else if (eg->showlookupfuz==1) eg->showlookupfuz=2;
                 else if (eg->showlookupfuz==2) eg->showlookupfuz=0;
                  if (it->keyindex==1) showkey;
	      }
	     break;
          case ')': case '(':
             /*to amplify (double) the length of bars: input-entropy histogram*/
             if (stpgraph==0 || ae->show_edata) break;
             if (eg->showlookupfreq==1 || eg->showlookupfreq==2){
                signed int z;
                char waschanged=0;
                 if (is[0]==')'){
                    /*This amplifies by *2 for each press*/
                   if (eg->hist_bar_factor<1) eg->hist_bar_factor=1;
		   else if (eg->hist_bar_factor <= Maxint){ 
                        eg->hist_bar_factor*=2;
                        waschanged=1;
		   }
                   /*fprintf(stderr,"\n %f",eg->hist_bar_factor);*/                 
                 } 
                 else if (is[0]=='(' /*&& eg->hist_bar_factor>1*/){
		    if (eg->hist_bar_factor<=1) eg->hist_bar_factor=0;//to show hist as log2
		    else eg->hist_bar_factor=1;
                    //if (eg->showlookupfreq==1) clearviewport();
		    //if (it->keyindex==1) showkey;
                    waschanged=1;
                 }
                 /*reset oldbar for histogram*/
                 if (eg->showlookupfreq==1 && waschanged==1){              
                    for (z=it->tablemax; z>=0; z--) eg->oldbar[z]=0;
                    /*clear and redraw area of lookup histogram*/
                    tempx=getx;
                    tempy=gety;
                    draw_box(-1,eg->startxbox-3,eg->startybox-2,
				    eg->xboxmax+3,eg->yboxmax+2,1,0);
                    moveto(tempx,tempy);
                 }
	     } 
             break;
	  case 's':/*toggle density (eeg)...showlookupfreq*/         
             if (stpgraph==0 || ae->show_edata) break;
             it->time_step_density_plot=0;
             eg->twodgy=0;/*restart at top*/   
	     if (eg->showeeg==1){
	        tempx=getx;
	        tempy=gety;
	        eg->showlookupfreq=1;
	        eg->showeeg=0;
	        stpgraph=2;
                if (nhood_mixed && single_entropy==1)
	                  eg->ent_nhood=nhoodm[entropy_poss];
	        else eg->ent_nhood=nhood;
	        eg->lookupfreqwidth=vgax(100);
	        it->ittcount=0;
		        
		/*redraw frame to window*/
                draw_stpframe(eg->stpwidth,eg->lookupfreqwidth); 
#               if __UNIX__
                      /*redraw frame to pixmap*/
                      *current_draw = *it->offscreen_pixmap; 
                      draw_stpframe(eg->stpwidth,eg->lookupfreqwidth);
                      *current_draw = W;
#               endif			   
		eg->startxbox=eg->stpwidth+
                          (signed int)eg->lookupfreqwidth+vgax(10);
		eg->xboxmax=eg->startxbox+(signed int)eg->lookupfreqwidth;
                eg->startybox=vgay(57);
		eg->barno=it->tablemax+1;
                /*set the max length of histogram, before next row*/
                if (eg->barno>128) eg->barno=128;
		/*eg->barw=(float)(Maxy-eg->startybox)/eg->barno;*/ /*preserve prev reduced hist size*/
		if (eg->barw>vgay(5)) eg->barw=vgay(5);
		eg->yboxmax=eg->startybox+(signed int)eg->barw*eg->barno;
		eg->barsep=vgay(2);
		if (!(eg->lookup_entropy && eg->ent_nhood>5)){
		   draw_box(-1,eg->startxbox-3,eg->startybox-2,
				       eg->xboxmax+2,eg->yboxmax+1,1,0);
		}
                
		if (eg->ent_nhood<8) 
                    eg->barlength=(signed int)eg->lookupfreqwidth;
		else eg->barlength=
		   (signed int)eg->lookupfreqwidth
                                   /((it->tablemax+1)/eg->barno);
		eg->newbar0=eg->stpwidth;
		eg->thisxbox=eg->startxbox-1;
                eg->thisybox=eg->startybox-1;
		if (it->keyindex==1)  showkey; 
                
		moveto(tempx,tempy);               
		break;
	     }         
	     if (eg->showlookupfreq){
		tempx=getx;
		tempy=gety;
		eg->showeeg=1;
		eg->showlookupfreq=0;
		stpgraph=1;
		eg->eegwidth=vgax(100);

                /*redraw frame to window*/
                draw_stpframe(eg->stpwidth,eg->eegwidth); 
#               if __UNIX__
                   /*redraw frame to pixmap*/
                   *current_draw = *it->offscreen_pixmap; 
                   draw_stpframe(eg->stpwidth,eg->lookupfreqwidth);      
                   *current_draw = W;
#               endif
		  
		 if (it->keyindex==1) showkey;
		 moveto(tempx,tempy);
		 break;
	      }
           case ';': /*show density...x=t, y=t-1*/ 
              if (stpgraph==1 && eg->showeeg==1){
		if (it->time_step_density_plot==2) it->time_step_density_plot=1;
		 it->time_step_density_plot=abs(it->time_step_density_plot-1);
	         tempx=getx;
	         tempy=gety;	      		
		 /*clear space*/
		 if (it->time_step_density_plot==0)
                        draw_entgraph_frame(0,eg->stpwidth,ae->show_edata,0);
                 else if (it->time_step_density_plot==1)
                        draw_entgraph_frame(1,eg->stpwidth,ae->show_edata,0);		
	         moveto(tempx,tempy);
              }
               if (it->keyindex==1) showkey;
	      break;
           case ',': /* (coma) to toggle lines instead of just dots 
                         in  entropy-density or density-return plots*/
              if (eg->lookup_entropy || it->time_step_density_plot){
	           eg->history_lines_in_plots=abs(eg->history_lines_in_plots-1);
	      }
              if (it->keyindex==1) showkey;
              break;
	   case 'u': /*show graph eeg...lookup_entropy*/ 
	      if (eg->showlookupfreq==2 || eg->new_hist==1 ||
                             stpgraph<2 || ae->show_edata) break;
              it->time_step_density_plot=0;              
	      tempx=getx;
	      tempy=gety;
	      
	      if (eg->lookup_entropy==1){
		 eg->lookup_entropy=0;			
		 /*clear space*/
		 draw_entgraph_frame(0,eg->stpwidth,ae->show_edata,0);


		 /*caused seg fault -- not necessary ?? Feb 2017*/
		 /* if (eg->showlookupfreq){
                    for (zz=0;zz<=value_range-1;zz++) 
                                   free(eg->eegcount[zz]);
                    free(eg->eegcount);
                    free(eg->eegratiobefore);
		 }*/
		 
		 if (eg->showeeg){
		    free(eg->oldbar);
		    for (z=0;z<=gens-1;z++) free(eg->lookupcount[z]);
		    free(eg->lookupcount);
		 }
		 //if (it->keyindex==1) showkey;
	      }
	      else if (eg->lookup_entropy==0){
		 eg->lookup_entropy=1;
		 eg->ecolor=yellow;
		 draw_entgraph_frame(1,eg->stpwidth,ae->show_edata,0);
		 if (eg->showlookupfreq==0){
		    it->ittcount=0;
		    it->screenend=1;
		    sprintf(textb[0],"eg->lookupcount");
		    if ((eg->lookupcount=(unsigned int**)
			  calloc(gens,sizeof(unsigned int*)))==
					NULL) outof_memory(textb[0]);
		    /*alloc mem for eg->lookupcount for each nhood*/
		    for (z=0;z<=gens-1;z++){
			sprintf(textb[0],"eg->lookupcount[%d]",z);
			   if ((eg->lookupcount[z]=(unsigned int *)
			      calloc(it->tablemax+1,sizeof(unsigned int)))
				   ==NULL) outof_memory(textb[0]);
		    }
		    /*alloc mem for size of old bar*/
		    sprintf(textb[0],"eg->oldbar");
		    if ((eg->oldbar=(signed int *)calloc
			       (it->tablemax+1,sizeof(signed int)))
				      ==NULL)outof_memory(textb[0]);
		 }
		 
                 /*not necessary ?? Feb 2017*/
		 /*if (eg->showeeg==0) {
                    if ((eg->eegratiobefore=(double *)
                     calloc(value_range,sizeof(double)))
			         ==NULL)  outof_memory("eg.eegratiobefore");
                    if ((eg->eegcount=(unsigned int **)
                     calloc(value_range,sizeof(unsigned int*)))
				   ==NULL)  outof_memory("eg.eegcount");
                    for (zz=0;zz<=value_range-1;zz++){
	               if ((eg->eegcount[zz]=(unsigned int *)
                         calloc(gens,sizeof(unsigned int)))
				   ==NULL)  outof_memory("eg.eegcount[]");
		    }
		 }*/
	      }
              if (it->keyindex==1) showkey;
	      moveto(tempx,tempy);
	      break;
                    
           case 'D': /*return map*/
	         /*if (stpgraph==0 || ae->show_edata) break;*/
                 if (ae->show_edata) break;
		 tempx=getx;
		 tempy=gety;		   			
		 /*clear space*/
                 if (it->Hamming_plot==1){
                    it->Hamming_plot=0;
                    draw_Hamming_plot(0,eg->stpwidth);
		 }                     
                 else{
                    it->Hamming_plot=1;
                    eg->ecolor=yellow;
	            draw_Hamming_plot(1,eg->stpwidth);
		 }
		 if (it->keyindex==1) showkey;
		 moveto(tempx,tempy);
		 break;

	   case 'E': /*create rule sample*/
	         if (stpgraph==0 || eg->lookup_entropy==0) break;
                 tempx=getx;
		 tempy=gety;
		 ae->edataruleno=0;
		 random_seed(it->color1,100,0);
		 it->ittcount=0;
                 slant=-1;
		 it->screenend=1;
               startE:
                 auto_sample_rule_count=0; /*for consecutive dec rules for small rule-space*/
		 xbox=draw_prompt_box(3);
		 setcolor(white);
		 if (ae->show_edata==0) ae->show_edata=1;		 
		 outtext("entropy sample, automatic-a test-(def):");
		 input_string(1,0);
		 if (is[0]=='a') ae->show_edata=2;
                 if (is[0]=='q'){
                    ae->show_edata=0;
                    is[0]=0;
                    erase_prompt_box(3);
		    break;
		 }
		
                 min_max_entropy=1;
                 outtext("  sdev-s min-max-(def):");
		 input_string(1,0);
                 if (is[0]=='q') goto startE;
		 else if (is[0]=='s')  min_max_entropy=0;

		 moveto(xbox,gety+CHeight);
		 sprintf(textb[0],
			"record time-steps, ");
		 outtext(textb[0]);
		 sprintf(textb[0],"start (def %d):",eg->sstep);
		 outtext(textb[0]);
		 input_string(4,0);

		 if (atoi(is)>0 &&
                        is[0]!=13 && is[0]!='q') eg->sstep=atoi(is);
                 else if (is[0]=='q') goto startE;
		 moveto(getx+vgax(10),gety);
		 sprintf(textb[0]," end (def %d):",eg->estep);
		 outtext(textb[0]);
		 input_string(4,0);
		 if (atoi(is)>eg->sstep &&
		      is[0]!=13 && is[0]!='q') eg->estep=atoi(is);
                 else if (is[0]=='q') goto startE; 
		 moveto(xbox,gety+CHeight);
		 sprintf(textb[0],"sample for each rule (def %d):",
		                                 ae->sample_size);
		 outtext(textb[0]);
		 input_string(4,0);
		 if (atoi(is)>0 && 
                       is[0]!=13 && is[0]!='q') ae->sample_size=atoi(is);
		 else if (is[0]=='q') goto startE;

                 ae->bias_rnd_rules=0;
                 ae->bias_isomorphic=0;

                 /*if already set. retain*/
                 /*if (bias_percent_rule[8]!='v' && bias_percent[8]!='p'){
                    for (z=0;z<=8;z++) bias_percent_rule[z]=0;
		 }*/

                 ae->bias_allV2V=0;
                 ae->bias_all020=0;
                 outtext("  bias rnd rules -b:");
		 input_string(1,0);
                 if (is[0]=='q') goto startE;
		 else if (is[0]=='b') ae->bias_rnd_rules=1;

                 if (ae->bias_rnd_rules){
                   signed int tablemax,thisx;
                   char reset_value_bias=0;
		    if (tot_only==0){ 
		        if (set_iso_input_histogram==1) tablemax=iso_tablemax;
		        else tablemax= (signed int)pow(value_range,(double)nhood)-1;
                    }
                    else if (tot_only==1){
                        if (totalistic==1) tablemax=nhood*(value_range-1);
                        else if (totalistic==2) tablemax=v_tablecodemax[nhood];
                    }
		  startB:
                    xbox=draw_prompt_box(3);
                    if (tot_only==0 && set_iso_input_histogram==0){ 
		       if (max_dec_rule(tablemax,value_range)>0 /*rulespace-r: can be dec and automatic only*/
                             && ae->show_edata==2) outtext("iso-i rulespace-r:");
                       else outtext("iso-i: ");
                       input_string(1,0);
                       if (is[0]=='i') ae->bias_isomorphic=1;
                       else if (is[0]=='r' && max_dec_rule(tablemax,value_range)>0)
                                               ae->bias_isomorphic=2; /*consecutive rule-space*/
                       else if (is[0]=='q') goto startE;
                    }
                    /*iso_rule (tot_only==0) &  totalistic==1 and 2 are already isotropic*/
                    else if (max_dec_rule(tablemax,value_range)>0 
                             && ae->show_edata==2){ /*rulespace-r: can be dec and automatic only*/
                       outtext("rulespace-r: ");
                       input_string(1,0);
                       if (is[0]=='r') ae->bias_isomorphic=2; /*consecutive rule-space*/
                       else if (is[0]=='q') goto startE;
		    }
		    outtext("value-bias, ");
                    if (ae->bias_isomorphic==0){
                       if (bias_percent_rule[8]=='v' || bias_percent_rule[8]=='p'){
                          
                          sprintf(textb[0],"(%c)%d--0:", bias_percent_rule[8],value_range-1);
                          for (z=0;z<=value_range-1;z++){
                             sprintf(textb[z+1]," %d ", bias_percent_rule[z]);
                             strcat(textb[0],textb[z+1]);
                          }
                          set_medium_font();
                          outtext(textb[0]);
                          thisx=getx;
                          restore_def_font();
                          moveto(getx,gety);
                          outtext("       cancel-c set-v keep-(def):");
                          input_string(1,0);
                          if (is[0]=='c'){
                             for (z=0;z<=8;z++) bias_percent_rule[z]=0;
                             reset_value_bias=0;
                          }
                          else if (is[0]=='v') reset_value_bias=1;
                          else if (is[0]=='q') goto startE;
                          else reset_value_bias=0;                         
                       }
                       else{
                          outtext("set-v:");
                          input_string(1,0);
                          reset_value_bias=0;
                          if (is[0]=='v') reset_value_bias=1;
                          else if (is[0]=='q') goto startE;                 
                       }
                        
                       if (reset_value_bias==1){
                          moveto(xbox,gety+CHeight);
                          if (tablemax+1<=255) outtext("%/values-p/v: ");
                          else outtext("%values-p: ");
                          input_string(1,0); /*8 is outside range of values 0-7*/
                          if (is[0]=='p') bias_percent_rule[8]='p';
                          else if (is[0]=='v' && tablemax+1<=255) bias_percent_rule[8]='v'; 
                          else if (is[0]=='q') goto startB;
                          if (is[0]=='p' || (is[0]=='v' && tablemax+1<=255))
			                   set_fraction_values(1,tablemax+1);
                          if (is[0]=='q') goto startB;
                       }
		    }

                    moveto(xbox,gety+CHeight);
                    outtext("all0s-0:");
                    input_string(1,0);
                    if (is[0]=='0')  ae->bias_all020=1;
                    else if (is[0]=='q') goto startB;
		    if (value_range>=3){
                       outtext(" allVs-v:");
                       input_string(1,0);
                       if (is[0]=='v' || is[0]=='V')  ae->bias_allV2V=1;
                       else if (is[0]=='q') goto startB;                       
		    }                                    
		 }
   
                 erase_prompt_box(3);

		 if (ae->show_edata==2) ae->file_edata=
				    select_stat_filename(ae);

		 if (ae->show_edata==2) /*clear space*/
			draw_entgraph_frame(0,eg->stpwidth,ae->show_edata,0);
		 free(ae->edata);
		 sprintf(textb[0],"ae->edata");
		 if ((ae->edata=(float *)calloc(eg->estep-eg->sstep+2,
			    sizeof(float)))==NULL) outof_memory(textb[0]);
		 draw_entgraph_frame(1,eg->stpwidth,ae->show_edata,0);
                 scrolling=0; /*dont scroll*/
		 moveto(tempx,tempy);
		 break;


           case '%': /* toggle lookup freq histogram - graph */
	     if (eg->lookup_entropy && stpgraph>1) break; /*stpgraph=2 default show look-up frequency*/
                     /*|| eg->barno>64 -- no longer limited to 64 bars*/ 
		 
	         //fprintf(stderr,"\n%d-%d=%d",eg->yboxmax,eg->startybox,eg->yboxmax-eg->startybox);
                 //fprintf(stderr,"\n<%dx%d=%d",it->tablemax+1,(signed int)eg->barw, (it->tablemax+1) * (signed int)eg->barw);
                 /*for one row histogram only -- Dec 2016,rev Dec 2020*/
		 if (stpgraph>1 && eg->yboxmax-eg->startybox < (it->tablemax+1) * (signed int)eg->barw){
		   //fprintf(stderr,"\nbreak: %d < %d",eg->yboxmax-eg->startybox, (it->tablemax+1) * (signed int)eg->barw);
                        break;
		 }
                 
		 //fprintf(stderr,"\n%d > %d",eg->yboxmax,(signed int)(Maxy*.95));
                 if (eg->yboxmax > (signed int)(Maxy*.95)) break;
                                  
		     tempx=getx;
		     tempy=gety;
		     if (eg->showlookupfreq==1){
			eg->showlookupfreq=2;
			erase_box(eg->startxbox-3,eg->startybox-2,
				       eg->xboxmax+2,eg->yboxmax+1);
		        eg->thisxbox=eg->startxbox-1;
			eg->thisybox=eg->startybox-1;                      
		     }
		     else if (eg->showlookupfreq==2){
			if (it->keyindex) setviewport(eg->startxbox-3,vgay(20),
						 Maxx-vgax(135),Maxy,1);
			else setviewport(eg->startxbox-3,vgay(20),
						 Maxx,Maxy,1);
			clearviewport();
			setviewport(0, 0, Maxx, Maxy, 1);
			eg->showlookupfreq=1;
                        draw_box(-1,eg->startxbox-3,eg->startybox-2,
		                      eg->xboxmax+2,eg->yboxmax+1,1,0);			
		     }
		     for (z=it->tablemax; z>=0; z--) eg->oldbar[z]=0;
		     showkey;
		     moveto(tempx,tempy);

		  break;  
   
            case '0': /* 0 is zero: 
                  toggle between oldlookuphist and 
                                 newlookuphist (in groups if long lookuptable) */
                  if (stpgraph==0 || ae->show_edata || eg->lookup_entropy==1) break;
                  if (eg->showlookupfreq==1){
                     tempx=getx;
		     tempy=gety;
	             eg->new_hist=abs(eg->new_hist-1);
                     for (z=it->tablemax; z>=0; z--) eg->oldbar[z]=0;
		     erase_box(eg->startxbox-3,eg->startybox-2,
				       eg->xboxmax+2,eg->yboxmax+1);    
                     draw_box(-1,eg->startxbox-3,eg->startybox-2,
		          eg->xboxmax+2,eg->yboxmax+1,1,0);
                     showkey;
                     moveto(tempx,tempy);
                  }               
		  break;
            case '_': /*to reduce width of bars in nhood-input-histogram*/ 
	      if (stpgraph==0 || ae->show_edata /*|| eg->lookup_entropy==1*/) break;
                  if (eg->showlookupfreq==1){
		    unsigned char tempcolor;
                     tempx=getx;
	             tempy=gety;

                     tempcolor=fillcolor;
		     setfillstyle(SOLID_FILL,black);
		     bar(eg->stpwidth+eg->eegwidth+1,eg->startybox-2,
			     eg->xboxmax+vgax(2),eg->yboxmax+1);
		     setfillstyle(SOLID_FILL,tempcolor);
		     		     
		     eg->barw-=1;
                     //fprintf(stderr," %f ",eg->barw);
		     //if (eg->barw<vgay(1)){ //restore defaults 
                     if (eg->barw<1){ //one pixel -- restore defaults 
                        eg->barw=(float)(Maxy-eg->startybox)/eg->barno;
		        if (eg->barw>vgay(5)) eg->barw=vgay(5);
		        /*set the max length of histogram, before next row*/
		        if (eg->barno>128) eg->barno=128;
		     }
		     eg->barsep=eg->barw/3;
		     eg->yboxmax=eg->startybox+(signed int)eg->barw*eg->barno;
		     draw_box(-1,eg->startxbox-3,eg->startybox-2,
		     		       eg->xboxmax+2,eg->yboxmax+1,1,0);
		     
                     if (eg->ent_nhood<8) 
                         eg->barlength=(signed int)eg->lookupfreqwidth;
		     else eg->barlength=
		         (signed int)eg->lookupfreqwidth
                                   /((it->tablemax+1)/eg->barno);

		     if (it->keyindex==1)  showkey;

                     clear_lookuphist(eg);
                     revise_various_stp_settings(eg,it);
                     
		     moveto(tempx,tempy);   
		     
		  }
		  break;
            case '&': /*increase the barwidth (if one column), or
                        increase the max length of histogram, so reduce no of cols*/
	      if (stpgraph==0 || ae->show_edata) break;
		  if (eg->showlookupfreq==1){
		    unsigned char tempcolor;
                     tempx=getx;
	             tempy=gety;
		     tempcolor=fillcolor;
		     setfillstyle(SOLID_FILL,black);
		     bar(eg->stpwidth+eg->eegwidth+1,eg->startybox-2,
			 eg->xboxmax+vgax(2),eg->yboxmax+1);
		     setfillstyle(SOLID_FILL,tempcolor);
                     /*increase the barwidth (if one column)*/
		     if (eg->barno==it->tablemax+1){
                          eg->barw+=1;		  
			  if (eg->barw>vgay(10)) eg->barw=vgay(10);
                     }
		     else{ /*increase the max length of histogram, so reduce no of cols*/
		        eg->barno*=1.25;
		        if (eg->barno >= it->tablemax+1)  eg->barno=it->tablemax+1;
		     }
		     eg->barsep=eg->barw/3;		     
		     //fprintf(stderr,"\nbarno=%d t=%d",eg->barno,it->tablemax+1);
		     eg->yboxmax=eg->startybox+(signed int)eg->barw*eg->barno;
		     draw_box(-1,eg->startxbox-3,eg->startybox-2,
		          eg->xboxmax+2,eg->yboxmax+1,1,0);
		     
                
		     if (eg->ent_nhood<8) 
                         eg->barlength=(signed int)eg->lookupfreqwidth;
		     else eg->barlength=
		         (signed int)eg->lookupfreqwidth
                                   /((it->tablemax+1)/eg->barno);

		     if (it->keyindex==1)  showkey;

                     clear_lookuphist(eg);
                     revise_various_stp_settings(eg,it);
                     
		     moveto(tempx,tempy);   
		     
		  }
		  break;
	    /*showlookupfreq: change generation size*/          
	    case 'G':
		  if (stpgraph){
                     get_prompt_box(4,2);                     
                     setcolor(white);                
		     sprintf(textb[0],
			"enter new 'analysis'generation size (now %d):",gens);
		     draw_prompt_box(1);
		     outtext(textb[0]);
		     input_string(5,1);
                    
                     if (is[0]!=13 && atoi(is)>0){
                           for (zz=0;zz<=value_range-1;zz++) 
                                      free(eg->eegcount[zz]);
                           free(eg->eegcount);
                           free(eg->eegratiobefore);
              
                           for (z=0;z<=gens-1;z++) free(eg->lookupcount[z]);
			   free(eg->lookupcount); 

			   gens=atoi(is);

                           /*alloc mem to eg.eegcount
                           for each value
                           for each generation*/
                           if ((eg->eegratiobefore=(double *)
                             calloc(value_range,sizeof(double)))
			         ==NULL)  outof_memory("eg->eegratiobefore");
                           if ((eg->eegcount=(unsigned int **)
                               calloc(value_range,sizeof(unsigned int*)))
				   ==NULL)  outof_memory("eg->eegcount");
                           for (zz=0;zz<=value_range-1;zz++){
	                      if ((eg->eegcount[zz]=(unsigned int *)
                                 calloc(gens,sizeof(unsigned int)))
				   ==NULL)  outof_memory("eg->eegcount[]");
                           }

                           if (eg->showlookupfreq){
			      it->ittcount=0;
			      it->screenend=1;
                           }
			   sprintf(textb[0],"eg->lookupcount");
			   if ((eg->lookupcount=(unsigned int**)
					calloc(gens,sizeof(unsigned int*)))
					    ==NULL) outof_memory(textb[0]);
			   /*alloc mem for eg->lookupcount for each nhood*/
			   for (z=0;z<=gens-1;z++){
			      sprintf(textb[0],"eg->lookupcount[%d]",z);
			      if ((eg->lookupcount[z]=(unsigned int *)
				    calloc(it->tablemax+1,
                                         sizeof(unsigned int)))
					    ==NULL) outof_memory(textb[0]);
			   }
                     }

		     /*set new single gene position*/
                     if (single_entropy==1){		       
                        if (oned){ 
                           sprintf(textb[0],
	                        "single: enter index (max %d def %d):",
			               lineL-1,entropy_poss);
	                   draw_prompt_box(1);
	                   outtext(textb[0]);
	                   input_string(5,0);
	                   if (is[0]!=13 && atoi(is)>=0 && atoi(is)<lineL)
		                   entropy_poss=atoi(is);
	                }
	                else{
                          unsigned int ii=0,jj=0,hh=0,
                                         max_ii,max_jj,max_hh; 
			  if (twod){ 
			     max_ii=i2d-1;
                             max_jj=j2d-1;
                          }
                          else if (threed){
                             max_ii=i3d-1;
                             max_jj=j3d-1;
                             max_hh=h3d-1;
                          }
	                 start_twod_ent1:
	                   xbox=draw_prompt_box(2);
	                   if (twod) sprintf(textb[0],
	                      "single 2d: 2d index(max %d,%d, now %d,%d)",
		                 i2d-1,j2d-1,entropy_poss%i2d,entropy_poss/i2d);
                           else if (threed) sprintf(textb[0],
	                      "single 3d: 3d index(max %d,%d,%d now %d,%d,%d)",
		                 i3d-1,j3d-1,h3d-1,
                                    entropy_poss%i3d,
                                       entropy_poss%(i3d*j3d)/i3d,
                                         entropy_poss/(i3d*j3d));
	                   outtext(textb[0]);
		           moveto(xbox,gety+CHeight);
		           outtext("enter i:");
	                   input_string(3,0);
	                   if (is[0]!=13  && atoi(is)>=0 && atoi(is)<=max_ii)
	                                  ii=atoi(is);
		           outtext(" enter j:");
	                   input_string(3,0);
	                   if (is[0]=='q') goto  start_twod_ent1;
	                   else if (is[0]!=13 && atoi(is)>=0 && atoi(is)<=max_jj)
		                                   jj=atoi(is);
                           if (threed){
                              outtext(" enter h:");
	                      input_string(3,0);
	                      if (is[0]=='q') goto  start_twod_ent1;
	                      else if (is[0]!=13 && atoi(is)>=0 && atoi(is)<=max_hh)
		                                   hh=atoi(is);
                           }   
		           if (twod) entropy_poss=jj*i2d+ii;
                           else if (threed) entropy_poss=(i3d*j3d*hh) + (i3d*jj) + ii;
                           
		        }
                     }
                     uncover_free_prompt_box(4);                    
		     if (it->keyindex==1) showkey;
                  }
		  break;		  
	    case '4':/*set new random seed*/
                  if (diff_plot) it->color1=random_seed(it->color1,100,0);
                  else it->color1=random_seed(it->color1,
				    (signed int)bias_density_seed,0);
		  /*reset_matrix;*/
		  if (diff_plot==2) clear_diff_plot;
                  it->ittcount=0;
                  memmove(this_firstseed,state1,bytesL);
                  slant=-1;
                  if (totstatrules>0) it->seedORblock=0; /*for rnd seed (all) in .sta sample*/
		  break;	  
	    case 'v': /*set new random block, size as existing or default block*/	      
                  it->color1=random_block(0,seglen,it->color1);
		  /*reset_matrix;*/
                  if (diff_plot==2) clear_diff_plot;
                  it->ittcount=0;
                  memmove(this_firstseed,state1,bytesL);
                  slant=-1;
                  if (totstatrules>0) it->seedORblock='v'; /*for a seed-block in .sta sample*/
	          break;

            case '\\': /*(backslash character has to be '\\' not '\',
                        random values state according to  preset proportions of
                           values, either as % or numbers,  or special case 3x3 iso-patterns*/
	          if (iso_tablemax==101 && twod && value_range==2) three_block_iso_patterns(1,it);
		          //3x3 block based on 102 iso-rule patterns -- count down*/
		  
	          else if (bias_percent_seed[8]=='p' || bias_percent_seed[8]=='v'){
                     implement_fraction_values(0,1,state1,lineL);
                  }
                  it->ittcount=0;
                  memmove(this_firstseed,state1,bytesL);
                  slant=-1;
                  break;
            
            case '/': /*random values block according to  preset proportions of
                          values, either as % or numbers, or special case enter 3x3 iso-patterns*/

	      if (iso_tablemax==101 && twod && value_range==2) three_block_iso_patterns(0,it);
		      //3x3 block based on 102 iso-rule patterns -- count up*/		      
	          
	          else if (bias_percent_seed[8]=='p' || bias_percent_seed[8]=='v'){
                     /*set all bits to 0, else new block in existing state*/
                     memmove(state1,all_0s,bytesL);
                     implement_fraction_values(0,0,state1,lineL);
                  }
                  it->ittcount=0;
                  memmove(this_firstseed,state1,bytesL);
                  slant=-1;
                  break;
                  
            case 'o':/*restore original seed*/
                  memmove(state1,bitseed,bytesL);
                  memmove(this_firstseed,state1,bytesL);
		  /*reset_matrix;*/
		  if (diff_plot==2) clear_diff_plot;
                  it->ittcount=0;
                  slant=-1;
		  break;
            case '~':/*restore last seed*/
                  memmove(state1,this_firstseed,bytesL);
		  /*reset_matrix;*/
		  if (diff_plot==2) clear_diff_plot;
                  it->ittcount=0;
                  slant=-1;
		  break;	
	    case 'p':  /*draw plane in axonometric*/
	          if (ae->show_edata==2)
		    ae->auto_sample_pause=abs(ae->auto_sample_pause-1);
		  else if (d_mode==3 || (d_mode==2 && scrolling)) 
		    draw_axon_plane(it->fscale,it->polyy-1,it->draw_3d_grid);
		  break;
	    case 't':  /*toggle 2d<->2d+time (d_mode=3)*/
		  if (diff_plot==0 && d_mode!=4){
                        char native_net;
                        if (oned) native_net=oned;
                        else if (twod) native_net=twod;
                        else if (threed) native_net=threed;
			if (d_mode==2){
                           clear_stp(eg,it);
                           clear_lookuphist(eg);
                           clearviewport();  
			   d_mode=3;
                           sprintf(textb[0],
                             "native %dd->2d+time  ij=%d,%d",
                                             native_net,i2d,j2d);
                           inset_prompt_box(0,23,textb[0],'d'); 
                           reset_stpwidth(eg,it);
                           revise_various_stp_settings(eg,it);
                           it->slice_3d=0; /*show as flat parallelograms - not balls*/
                        }
			else if (d_mode==3){
                           clearviewport(); 
			   d_mode=2;
                           scrolling=nowscrolling=0;
                           sprintf(textb[0],
                             "native %dd->2d ij=%d,%d",native_net,i2d,j2d);
                           inset_prompt_box(0,23,textb[0],'d'); 
                           reset_stpwidth(eg,it);                           
                           revise_various_stp_settings(eg,it); 
			}
			if (it->keyindex==1) showkey;
                        eg->twodgy=-1; /*reset plot for 2d, 2d+time and 3d*/
		  }
                  else if (d_mode==4){/*tog 3d grid for 3d presentation*/
                        it->draw_3d_grid=abs(it->draw_3d_grid-1);
                        clear_stp(eg,it);
                        revise_various_stp_settings(eg,it);
                        //draw_axon_plane(it->fscale,it->polyy-1,it->draw_3d_grid);
                  }         
                  break;

            case 'T':  /*toggle 1d<->2d<->3d<->1d*/
		  if (diff_plot==0){
                        char native_net;
                        it->invisible=0;
                        if (oned) native_net=oned;
                        else if (twod) native_net=twod;
                        else if (threed) native_net=threed;                        
                        if (d_mode==1){
			   /*----------------------------------------------------*/
                           if (scrolling==1){ /*deal with scrolling - turn it off*/
                             char was_scrolling;
		              was_scrolling=1;
                              scrolling=0;     	                    
                              if (nowscrolling==1){
#                                if __WATCOM__
		                    freeimage(stpimage);
#                                endif
                              }
                              nowscrolling=0;			    
                              /*clear area of screen*/
                              if (was_scrolling==1 && d_mode==2){
		                 revise_various_stp_settings(eg,it);
		                 moveto(0,0);
		                 it->downy=0;
                                 setviewport(0,0,Maxy,Maxy,1);
                              }
	                      else if (diff_plot) setviewport(0,0,
                                 eg->stpwidth+lineL*it->fscale,Maxy,1);
	                      else setviewport(0,0,eg->stpwidth,Maxy,1);  
		              clearviewport();
	                      setviewport(0, 0, Maxx, Maxy, 1);
                              if (was_scrolling==1) draw_2d_frame(eg,it);	
	                   }
                           /*----------------------------------------------------*/
                           clear_stp(eg,it);
                           clear_lookuphist(eg);
                           clearviewport();  
			   d_mode=2;
                           it->fscale=vgax(4);			   
                           if (twod==0){
                              i2d=it->i2d_b;
                              j2d=it->j2d_b;
			   }
                           sprintf(textb[0],
                             "native %dd->2d ij=%d,%d",native_net,i2d,j2d); 
                           inset_prompt_box(0,23,textb[0],'d');
                           reset_stpwidth(eg,it);
                           revise_various_stp_settings(eg,it);
                           moveto(0,0);
                           it->slice_3d=0; /*dont't show as balls*/
			}
                        else if (d_mode==2){                          
                           clear_stp(eg,it);
                           clear_lookuphist(eg);
                           clearviewport();  
                           d_mode=4;		          
                           it->fscale=vgax(4);
                           if (threed==0){
                              i3d=it->i3d_b;
                              j3d=it->j3d_b;
                              h3d=it->h3d_b;
			   }
                           sprintf(textb[0],
                             "native %dd->3d ijh=%d,%d,%d",
                                           native_net,i3d,j3d,h3d); 
                           inset_prompt_box(0,23,textb[0],'d');
                           reset_stpwidth(eg,it);
                           revise_various_stp_settings(eg,it);
                           moveto(0,0);
                           it->slice_3d=1; /*show as balls*/
			}
			else if (d_mode==4){
                           clear_stp(eg,it);  
			   d_mode=1;
			   it->fscale=1;
			   it->fsep=1;
                           if (scrolling==0){
                              scrolling=1;
                              nowscrolling=0;
			   }
                           /*scrolling=1;*/
                           clearviewport();
                           reset_stpwidth(eg,it);
                           clear_stp(eg,it);
                           clear_lookuphist(eg);
                           revise_various_stp_settings(eg,it);
                           sprintf(textb[0],
                             "native %dd->1d n=%d",native_net,lineL);
                           inset_prompt_box(0,23,textb[0],'d');
			   moveto(0,0);
                           it->slice_3d=0; /*show as balls*/
			}			
			if (it->keyindex==1) showkey;
                        eg->twodgy=-1; /*reset plot for 2d, 2d+time and 3d*/
                        if (show_ss_matrixF==1) /*state-space matrix*/
                                   show_statespace_matrix(NULL);
                        if (it->Hamming_plot==1) /*graph for return map*/
                                      draw_Hamming_plot(1,eg->stpwidth); 
		  }
		  break;		  
	    case '5': /*v=2 set positivesinlgeton seed 000010000 or
                        v>2 set rnd singleton on rnd other background*/
			it->color1=singleton_seed(1,it->color1);
                        memmove(this_firstseed,state1,bytesL);
                        slant=-1;
                        if (totstatrules>0) it->seedORblock='5'; /*for singleton seed in .sta sample*/
			/*reset_matrix;*/                        
			break;
		  
	    case '6': /*v=2 set negative singleton seed 111101111 or
                        v>2 set rnd singleton on zero background*/
			it->color1=singleton_seed(0,it->color1);
                        memmove(this_firstseed,state1,bytesL);
                        slant=-1;
                        if (totstatrules>0) it->seedORblock='6'; /*for singleton seed in .sta sample*/
			/*reset_matrix;*/
			break;
		  
	    case 'l': /*flip one bit/value in current state at random position*/
			it->color1=random_bitflip_state(it->color1);
                        memmove(this_firstseed,state1,bytesL);
			/*reset_matrix;*/
			break;	
            case 'L': /*new central block, keep rest*/
                     it->color1=random_block(1,seglen,it->color1);
		     /*reset_matrix;*/
                     if (diff_plot==2) clear_diff_plot;
                     it->ittcount=0;
                     memmove(this_firstseed,state1,bytesL);
                     slant=-1;
		     break;	  
	    case '7': /*toggle local...nonlocal wiring*/
		     if (!loc_twod_fonly){
			wiring_madelocal=abs(wiring_madelocal-1);
                        toggle_yellow_white;
			if (it->keyindex==1) showkey;
			reset_matrix;	
		     }
                     break;
            case '?': /*April 2018 - if random wiring is active, randomy rewire at each time-step,
			according to random wiring (inc special) paramiters initially set*/	                                if (!loc_twod_fonly && wiring_madelocal==0 && nonlocal==1){
			rnd_rewiring_each_timestep=abs(rnd_rewiring_each_timestep-1);
			if (it->keyindex==1) showkey;
			reset_matrix;
		     }
		       
		     else{
		       /*Jan 2020 - else for regular wiring 1d, 2d, 3d, 
                             select an index to flip. Can be restored with '2'*/
		       signed int(fliptable); 
		        index_of_flip=-1;
			if (tot_only==0){
			    if (set_iso_input_histogram==1) fliptable=iso_tablemax;
			    else fliptable= (signed int)pow(value_range,(double)nhood)-1;
			}    
                        else if (tot_only==1){
                           if (totalistic==1) fliptable=nhood * (value_range-1);
                           if (totalistic==2) fliptable=v_tablecodemax[nhood];
                        }
			sprintf(textb[1],"%d",fliptable);
			//fprintf(stderr,"\nfliptable=%d, %s, strlen=%d",fliptable,textb[1],strlen(textb[1]));
			get_prompt_box(10,1);
			xbox=draw_prompt_box(1);			
			sprintf(textb[0],"index of flip 0-%d:",fliptable);
			outtext(textb[0]);
			input_string(strlen(textb[1]),1);
			uncover_free_prompt_box(10);
			if (is[0]!=13 && atoi(is)>=0 && atoi(is)<=fliptable){
	                      index_of_flip=atoi(is);
                              it->color1=bit_flip('1',it->color1); /*flips output to different value*/
	                      reset_matrix;
	                      set_entropy_pix_color;
			}
		     }	
                     break;
		      
            case '"': /* April 2018 - pulsing data in terminal,
                         see also interupt prompt 'd' to save*/
		     if (eg->lookup_entropy && ae->show_edata==0){
		       it->ittcount=0; //reset iteration count
		       it->time_step_density_plot=1; /*turn off saving if active*/
		       if (it->track_pulsing==1){ /*turn off data and print averages*/			   
	                   fprintf(stderr,"\nav-wl=%.2f, av-wh=%.3f, sample=%lu",
	                       it->av_wave_length,it->av_wave_height,it->wave_sample);
			   it->track_pulsing=0;
			   
		        }
		        else if (it->track_pulsing==0){ /*turn off data on with new start*/
			   it->track_pulsing=1;
			}   
		     }	                
                     break;
            case '|': /*toggle between periodic and null boundary conditions, 
		      1d, 2d, 3d*/
			NULLboundaries=abs(NULLboundaries-1);
                        toggle_yellow_white;
			if (it->keyindex==1) showkey;
			reset_matrix;
                     break;		  
	    case '8': /*toggle rulemix-rule[0] only*/
	             if (rulemix && nhood_mixed==0){ /*no point for nhood_mixed*/
                        it->rule_unmixed=abs(it->rule_unmixed-1);
                        toggle_yellow_white;
			if (it->keyindex==1) showkey;
			reset_matrix;
		     }
                     break;	  
	    case 'i': if (direction=='f' && limitcheck==0){
                         /*hexagons/rectanges for divisions, March 07 applies to all, 1d, 2d, 3d etc ?*/
	                 if (d_mode==2 || d_mode==1){ /*not if "balls" active*/ 
                            it->show_2d_divs=abs(it->show_2d_divs-1);
                            /*3-way tog black/white/lightblue with '!'*/ 
                            if (twod && d_mode==2){ 
                               clear_stp(eg,it);
                               revise_various_stp_settings(eg,it);
                               clearviewport();
                            } 
                            if (it->keyindex==1) showkey;
			 }
                         /*if balls showing: toggle balls outline (ie above or 3d presentation)*/
                         else if (it->slice_3d==1) it->pi_outline=abs(it->pi_outline-1);
                      }
                      break;
             case '@':
	            if (graph_layout==1) /*tog balls outline for graph*/
                            it->node_outline=abs(it->node_outline-1);
                    else if (it->slice_3d==1) /*tog balls outline for 3d, 2d+time, diagonal scrolling*/
                               it->pi_outline=abs(it->pi_outline-1); //for 3d or 2d scrolling
		    break;    
             case '!': /*tog black/white/gray divisions between cells, 2d hex or square*/
                      if (it->slice_3d==1 || d_mode==2 || d_mode==1){                         
                         if (it->divcolor==black) it->divcolor=white;
                         else if (it->divcolor==white) it->divcolor=lightgray;
                         else if (it->divcolor==lightgray) it->divcolor=black;
                      }
                      break;
             case 'N': /*for 1d increace CA size by 1*/ 
                     if (rulemix==1 || exhaustive_testing==2 || att_hist>0) break;
                     else if (oned && d_mode==1 && 
                             diff_plot==0 && att_hist==0){
			for (z=0;z<=frozen_gens-1;z++) free(it->last_state1[z]);
	                free(it->last_state1); 
			if ((temppoint=(char*)calloc(bytesL,sizeof(char)))
				  ==NULL) outof_memory("temppoint");
			memmove(temppoint,state1,bytesL);
			tempbytesL=bytesL;
			free_mem_CA_states();
                        /*to show stp according to the graph layout and node size*/
                        for (zu=0;zu<=lineL;zu++) free(stp_graph_layout[zu]);
                        free(stp_graph_layout);
                        free(stp_graph_node_size);
                        free(stp_cell_color);
			L++;
			lineL = L+1;
                        bytesL=(signed int)ceil(((double)(value_bits*lineL))/8);
			allocate_mem_CA_states();
                        graph_layout=0; 
                        /*to show stp according to the graph layout and node size*/
                        if ((stp_graph_layout=(signed int**)calloc(lineL+1,
                          sizeof(signed int*)))==NULL) 
                                 outof_memory("stp_graph_layout");
                        for (zu=0;zu<=lineL;zu++){
                           if ((stp_graph_layout[zu]=(signed int *)
                                calloc(2,sizeof(signed int)))
			           ==NULL) outof_memory("stp_graph_layout[]");
                        }
                        if ((stp_graph_node_size=
                            (float *)calloc(lineL+1,sizeof(float)))
			    ==NULL) outof_memory("stp_graph_node_size");
                        if ((stp_cell_color=
                               (unsigned char *)calloc(lineL,sizeof(unsigned char)))
			       ==NULL) outof_memory("stp_cell_color");
                        /*allocale mem prevoius states, 
                                    at timestep t-1,t-2,...etc*/
                        if ((it->last_state1=(char**)
                                  calloc(frozen_gens,sizeof(char*)))
				       ==NULL) outof_memory("it->last_state1");
                        for (z=0;z<=frozen_gens-1;z++){
		           sprintf(textb[0],"it->last_state1[%d]",z);
		           if ((it->last_state1[z]=(char *)
                                        calloc(bytesL,sizeof(char)))
						==NULL) outof_memory(textb[0]);
                        }
			wire_rule_extra_cell((char)1);
			
			memmove(state1,temppoint,tempbytesL);
			memmove(bitseed,temppoint,tempbytesL);
			free(temppoint);
                        setviewport(0,0,Maxx,Maxy,1);
                        clearviewport();
                        
			if (it->keyindex==1) showkey;
                        sprintf(textb[0],
                             "n increased %d->%d",lineL-1,lineL); 
                        inset_prompt_box(0,23,textb[0],'d');
                        if (stpgraph>0) clear_lookuphist(eg);
		    
                        /*revise coords 2d & 3d*/
                        set_2d_3d_coords(it);
                        reset_stpwidth(eg,it);
                        revise_various_stp_settings(eg,it);
			reset_matrix;
                        it->ittcount=0;
                        seed_was_set=1;
                        moveto(0,0);
		     }
		     break;
		  
	    case 'n': /*decreace CA size by 1*/ 
                     if (rulemix==1 || exhaustive_testing==2 || lineL<3) break;
		     if (oned && d_mode==1 && diff_plot==0 && att_hist==0){
                        for (z=frozen_gens-1;z>=0;z--) free(it->last_state1[z]);
	                free(it->last_state1);	        
		        if ((temppoint=(char*)calloc(bytesL,sizeof(char)))
			       ==NULL) outof_memory("temppoint");
			memmove(temppoint,state1,bytesL);
			set_bit0(temppoint,L);
                        /*to show stp according to the graph layout and node size*/
                        for (zu=0;zu<=lineL;zu++) free(stp_graph_layout[zu]);
                        free(stp_graph_layout);
                        free(stp_graph_node_size);
                        free(stp_cell_color);
			L-=1;
			lineL=L+1;
                        bytesL=(signed int)ceil(((double)(value_bits*lineL))/8);
			sprintf(textb[0],"temppoint");
			if( (temppoint = (char*) realloc(temppoint,
				  sizeof(char)*bytesL))
				      ==NULL) outof_memory(textb[0]);
			free_mem_CA_states();
			allocate_mem_CA_states();
                        graph_layout=0; 
                        /*to show stp according to the graph layout and node size*/
                        if ((stp_graph_layout=(signed int**)calloc(lineL+1,
                          sizeof(signed int*)))==NULL) 
                             outof_memory("stp_graph_layout");
                        for (zu=0;zu<=lineL;zu++){
                           if ((stp_graph_layout[zu]=(signed int *)
                                calloc(2,sizeof(signed int)))
			           ==NULL) outof_memory("stp_graph_layout[]");
                        }
                        if ((stp_graph_node_size=
                            (float *)calloc(lineL+1,sizeof(float)))
			    ==NULL) outof_memory("stp_graph_node_size");
                        if ((stp_cell_color=
                               (unsigned char *)calloc(lineL,sizeof(unsigned char)))
			       ==NULL) outof_memory("stp_cell_color");
                        /*allocale mem prevoius states, 
                                    at timestep t-1,t-2,...etc*/
                        if ((it->last_state1=(char**)
                                   calloc(frozen_gens,sizeof(char*)))
				       ==NULL) outof_memory("it->last_state1");
                        for (z=0;z<=frozen_gens-1;z++){
		           sprintf(textb[0],"it->last_state1[%d]",z);
		           if ((it->last_state1[z]=(char *)
                                 calloc(bytesL,sizeof(char)))
				     ==NULL) outof_memory(textb[0]);
                        }                        
			wire_rule_extra_cell((char)-1);
			
			memmove(state1,temppoint,bytesL);
			memmove(bitseed,temppoint,bytesL);
			free(temppoint);
			
			setviewport((L+1)*it->fscale,0,Maxx,Maxy,1);
			clearviewport();
			setviewport(0,0,Maxx,Maxy,1);
			if (it->keyindex==1) showkey;
                        sprintf(textb[0],
                             "n decreased  %d->%d",lineL+1,lineL); 
                        inset_prompt_box(0,23,textb[0],'d');
                        set_2d_3d_coords(it);
                        reset_stpwidth(eg,it);
                        revise_various_stp_settings(eg,it);
			reset_matrix;
                        it->ittcount=0;
                        seed_was_set=1;
                        moveto(0,0);
		     }
		     break;
		  
	    case 'e':  /*expand scale*/                   
		     if (limitcheck==0 && it->fscale<=126){
                        if (d_mode>=2){
			    if (d_mode==2 && scrolling==1) it->downy=0;
			} 
                        else if (stpgraph>0) clear_lookuphist(eg);
                        clearviewport();
                        if (it->keyindex==1) showkey;
                        it->fscale++;
                        /*reset width of pattern including gaps*/
                        reset_stpwidth(eg,it);
                        clear_stp(eg,it);
                        clear_lookuphist(eg);
                        revise_various_stp_settings(eg,it);
                        if (show_ss_matrixF==1) /*state-space matrix*/ 
                              show_statespace_matrix(NULL);
                        if (it->Hamming_plot==1) /*graph for return map*/
                                  draw_Hamming_plot(1,eg->stpwidth);             
                        moveto(0,0);
                        /*reset plot for 2d, 2d+time and 3d*/
                        if (d_mode>1) eg->twodgy=-1;
                        
                        if (it->keyindex==1) showkey;
                        /*show the scale bottom right*/
                        sprintf(textb[0],"scale=%d",it->fscale);
                        draw_hint_box(0,0,textb[0],vgax(500));
		     }                                   
		     break;

	    case 'c': /*contract scale*/                  
		     if (limitcheck==0){
			it->fscale--;
			if (it->fscale<=0){
			   it->fscale=1;
			   goto show_scale;
			}
                        it->fscale++;
                                               
			if (d_mode>=2){ 
                           clear_lookuphist(eg);
                           if (d_mode==2 && scrolling==1) it->downy=0;
                        }                       
			clearviewport();
			if (it->keyindex==1) showkey;
                        it->fscale--;
			reset_stpwidth(eg,it);
                        clear_stp(eg,it);		
                        revise_various_stp_settings(eg,it);
                        if (show_ss_matrixF==1) /*state-space matrix*/ 
                              show_statespace_matrix(NULL);
                        if (it->Hamming_plot==1) /*graph for return map*/
                             draw_Hamming_plot(1,eg->stpwidth);   
                        moveto(0,0);
                        /*reset plot for 2d, 2d+time and 3d*/
                        if (d_mode>1) eg->twodgy=-1;
                        if (it->keyindex==1) showkey;
		       show_scale:
                        /*show the scale bottom right*/ 
                        sprintf(textb[0],"scale=%d",it->fscale);
                        draw_hint_box(0,0,textb[0],vgax(500));

		     }
		     break;

		  /*toggle pause on screenfull*/
		  case '*':
		     stppause=abs(stppause-1);
                     if (stppause==0) erase_prompt_box(1);
		     if (it->keyindex==1)  showkey;
		     break;
	          case '<': /*alter stp_speed slower*/
                     if (it->stp_speed==0) it->stp_speed+=500;
                     else it->stp_speed*=2;
                     break;
	          case '>': /*alter stp_speed max*/
                    it->stp_speed=0;
                    break;
		  /*toggle remove - restore interrupt key index*/
		  case 'X':
		     if (it->keyindex){
			tempx=getx;
			tempy=gety;
			/*taller box for DOS*/
#                       if __UNIX__
			    erase_box(Maxx-vgax(130)-3,Maxy-vgay(424),
							  Maxx,Maxy);
#                       elif __WATCOM__
			    erase_box(Maxx-vgax(165),vgax(22),Maxx,Maxy);
#                       endif
			it->keyindex=0;
			moveto(tempx,tempy);
		     }
		     else {
			showkey;
			it->keyindex=1;
		     }
		     break;

	       }/*end switch*/
	   }/*if space-time pattern only*/

           /*to make shure the interrupt finishes before next iteration*/
           while(event_ready()==0){
                   break;
           }
}

/*********************for 3x3 block based on 102 iso-rule patterns 26July2021**************/
void three_block_iso_patterns(char count_up_down,int_stp *it){
       unsigned int mostx,mosty;
       signed int z,iso_index,poss,tempL,tempi2d,tempj2d,xbox,ii,jj,bit_one_total;

                     /*locate centrally*/
                     mostx=(unsigned int)(ceil((double)i2d/2))-1;
                     mosty=(unsigned int)(ceil((double)j2d/2))-1;
		     
		     //iso_index=myrand()%iso_tablemax+1; //pick iso-index at random from 1-101 iso-list
		     //iso_prototype_count is global
                     if (count_up_down==0 && iso_prototype_count==0) iso_prototype_count=2; //skip 0,1,2
		     if (count_up_down==1 && iso_prototype_count<=2) iso_prototype_count=101;
                   skipcount: //count_up_down: 0=up, 1=down
		     if (count_up_down==0) iso_prototype_count+=1;
		     else if (count_up_down==1) iso_prototype_count-=1;
		     
		     if (iso_prototype_count==12 || iso_prototype_count==13 || iso_prototype_count==14
			 || iso_prototype_count==15 || iso_prototype_count==18 || iso_prototype_count==20
                         || iso_prototype_count==24 || iso_prototype_count==25 || iso_prototype_count==26
                         || iso_prototype_count==27 || iso_prototype_count==30 || iso_prototype_count==31
			 || iso_prototype_count==32 || iso_prototype_count==33 || iso_prototype_count==34) goto skipcount;
		     //102-16 = 86 remaining with 2 to 9 1s
		     
		     if (count_up_down==0 && iso_prototype_count>101) iso_prototype_count=3;
		     if (count_up_down==1 && iso_prototype_count<3) iso_prototype_count=101;
		     iso_index=iso_prototype_count;
		      
                     
	             //fprintf(stderr,"\n %d %d",iso_index,glbl_iso_list[iso_index][1]);//iso-index,prototype value		     
		     dec_to_value_line(iso_group_image,glbl_iso_list[iso_index][1],9);//convert prototype value to bitstring
		     
		     bit_one_total=0;//count number of bits in 3x3 block
		     memmove(state1,all_0s,bytesL);//clear state1 to not overwrite! 
		     for (jj=0; jj<=2;jj++){
                        for (ii=0;ii<=2;ii++){
                           poss=i2d*(jj+mosty)+(ii+mostx);
			   if (get_bit(iso_group_image,3*jj+ii)==1){
			       set_bit1(state1,poss);
			       bit_one_total+=1;
			   }    
			}			     
		     }
                     
	             if (it->req_iso_ptrns[bit_one_total]==bit_one_total); //do nout
		     else goto skipcount;
		     
		     //if (bit_one_total!=4) goto skipcount;		     
		     //if (bit_one_total!=5) goto skipcount;
		     //if (bit_one_total!=5 && bit_one_total!=4) goto skipcount;
		    
		     memmove(this_firstseed,state1,bytesL);
		     
                     xbox=draw_box(-1,Maxx-vgax(86),2,Maxx-2,2+CHeight*3+vgay(6),1,0);
		     moveto(xbox,gety+vgax(3));
		     outtext("now(");
                     for (z=3;z<=6;z++){
		        if (it->req_iso_ptrns[z]==z){
		           if (z<6) sprintf(textb[0],"%d,",it->req_iso_ptrns[z]);
		           else sprintf(textb[0],"%d)",it->req_iso_ptrns[z]);
		        }
	                 else{
		           if (z<6) sprintf(textb[0],"_,");
		           else sprintf(textb[0],"_)");
		         }
		         outtext(textb[0]);
                     }

		     moveto(xbox,gety+1.5*CHeight);
		     sprintf(textb[0],"i=%d v=%d  ",iso_index,glbl_iso_list[iso_index][1]);//iso-index,prototype value
		     outtext(textb[0]);
		     tempL=L;
		     L=8;
		     tempi2d=i2d;
		     tempj2d=j2d;
		     i2d=j2d=3;
		     print_current_state_twod(iso_group_image,yellow,0);
		     L=tempL;
		     i2d=tempi2d;
		     j2d=tempj2d;
		    
		     //input_string(1,0);
}
 
/*********************show selected 3x3 block patterns based on 102 iso-rule patterns 19Sept2021**************/
 void show_three_block_iso_patterns(int_stp *it){

       unsigned int mostx,mosty;
       signed int z,zz,zx,tempxx,tempyy,
	 iso_index,poss,tempL,tempi2d,tempj2d,ii,jj,bit_one_total,xbox,ynow,pattern_count;
       char tempscale,temp_basin_postScript,temp_isotropic_set,temp_divcolor,incomplete,end_of_line;
      
                  tempL=L;
		  L=8;
		  tempi2d=i2d;
		  tempj2d=j2d;
		  i2d=j2d=3;
		  temp_basin_postScript=basin_postScript;
		  basin_postScript=0;
		  temp_isotropic_set=isotropic_set;
		  isotropic_set=1;
		  temp_divcolor=it->divcolor;
		  
		  tempscale=it->fscale;
	          if (tempscale<4) tempscale=4;
		  
                  get_prompt_box(8,20);//complete right side of screen

		 redo_postScript:
		  
		  xbox=draw_prompt_box(20);//complete right side of screen
		  		  
		  //tempscale=it->fscale;
		  ynow=gety+tempscale;               
	          moveto(xbox+tempscale,ynow);

		  
		  pattern_count=0;		  
		  for (iso_index=101;iso_index>=3;iso_index--){
		     
		     if (iso_index==12 || iso_index==13 || iso_index==14
			 || iso_index==15 || iso_index==18 || iso_index==20
                         || iso_index==24 || iso_index==25 || iso_index==26
                         || iso_index==27 || iso_index==30 || iso_index==31
			 || iso_index==32 || iso_index==33 || iso_index==34 ) continue;
		     //102-16 = 86 remaining with 2 to 9 1s
		                          
	             //fprintf(stderr,"\n %d %d",iso_index,glbl_iso_list[iso_index][1]);//iso-index,prototype value
		     dec_to_value_line(iso_group_image,glbl_iso_list[iso_index][1],9);//convert prototype value to bitstring
		     
		     bit_one_total=0;//count number of bits in 3x3 block
		     for (jj=0; jj<=2;jj++){
                        for (ii=0;ii<=2;ii++){
                           poss=i2d*(jj+mosty)+(ii+mostx);
			   if (get_bit(iso_group_image,3*jj+ii)==1){
			       set_bit1(state1,poss);
			       bit_one_total+=1;
			   }    
			}			     
		     }
                     		     
	             if (it->req_iso_ptrns[bit_one_total]==bit_one_total); //do nout
		     else continue;

		     
		     pattern_count+=1;
		     //print 3x3 using print_current_state_twod function
		     //if (basin_postScript==0) print_current_state_twod(iso_group_image,yellow,0);
		       
                     tempxx=getx;
                     tempyy=gety;
		     zx=0;
                     for (zz=8;zz>=0;zz--){ //draw the 3x3 pattern
                           zx+=1;

			   if (get_bit(iso_group_image,zz)==1) setfillstyle(SOLID_FILL,yellow);
			   else setfillstyle(SOLID_FILL,black);

			   if (basin_postScript){
			      color_ps(basin_postScript-1,fillcolor);
                              rect_fill_ps(getx,gety,tempscale,tempscale);
			      color_ps(wiring_postscript-1,it->divcolor);/*color or gray*/
			      rect_outline_ps(getx,gety,tempscale,tempscale);
			   }
			   bar(getx,gety,getx+tempscale,gety+tempscale);
			   setcolor(it->divcolor);
			   rectangle(getx,gety,getx+tempscale,gety+tempscale);
			   setcolor(white);
			
                           moverel(tempscale,0);
			   if (zx%3==0) moveto(tempxx,gety+tempscale);
                     }
		     moveto(getx+tempscale*4,ynow);
		     
                     incomplete=0;
		     if (gety>=20*CHeight-tempscale*4*2){ //2 rows of patterns
		        //fprintf(stderr,"\n2:gety=%d height=%d",gety,20*CHeight-tempscale*4*2);
		        incomplete=1;
		        break;
		     }
		     end_of_line=0;
		     if (getx>Maxx-tempscale*4){
		         end_of_line=1;
		         ynow+=tempscale*4;
		         moveto(xbox+tempscale,ynow);
		     }
		     
		  }//for (iso_index=101;iso_index>=3;iso_index--){	  
                		  
		  if (basin_postScript){
		     moveto(xbox+tempscale,ynow+tempscale*4+CHeight);
		     if (incomplete==1) sprintf(textb[1],"incomplete 3x3 patterns \\\(");
		     else sprintf(textb[1],"%d 3x3 patterns \\\(",pattern_count);
		     color_ps(basin_postScript-1,white);
                     nodetext_ps(3,bground,textb[1],getx,gety);
		     moverel((strlen(textb[1])-1)*CWidth-vgax(2),0);
                  
		     for (z=3;z<=6;z++){
		        if (it->req_iso_ptrns[z]==z){
		           if (z<6) sprintf(textb[1],"%d,",it->req_iso_ptrns[z]);
		           else sprintf(textb[1],"%d\\\)",it->req_iso_ptrns[z]);
		        }
	                else{
		            if (z<6) sprintf(textb[1],"_,");
		            else sprintf(textb[1],"_\\\)");
		        }
		        if (z>3) moverel(CWidth+vgax(3),0);
                        color_ps(basin_postScript-1,white);
			nodetext_ps(3,bground,textb[1],getx,gety);
		     }		     
                  }
		  
                  if (end_of_line==0 || getx<Maxx-tempscale*4) moveto(xbox+tempscale,ynow+tempscale*3+CHeight);
		  if (incomplete==1) sprintf(textb[1],"%d incomplete 3x3 patterns (",pattern_count);
		  else sprintf(textb[1],"%d 3x3 patterns (",pattern_count);
		  outtext(textb[1]);
		  
		  for (z=3;z<=6;z++){
		        if (it->req_iso_ptrns[z]==z){
		           if (z<6) sprintf(textb[1],"%d,",it->req_iso_ptrns[z]);
		           else sprintf(textb[1],"%d)",it->req_iso_ptrns[z]);
		        }
	                else{
		            if (z<6) sprintf(textb[1],"_,");
		            else sprintf(textb[1],"_)");
		        }
		        outtext(textb[1]);
		  }		     
                   
		 
		  /*if (basin_postScript==1){
		    input_string(1,0);
		    goto skipPS;
		  }*/
		  
		  basin_postScript=0;
                  sprintf(textb[0]," scale(%d)-e/c PScript-p, cont-ret:", tempscale);
		  outtext(textb[0]);
		  input_string(1,0);
		  
		  if (is[0]=='e' || is[0]=='c'){
		     if (is[0]=='e'){
		        tempscale+=1;
			if (tempscale>=30) tempscale=30; //max scale
	             }		
		     else if (is[0]=='c'){
		        tempscale-=1;
			if (tempscale<3) tempscale=3; //min scale
	             } 
		     goto redo_postScript;
		  } 
		  else if (is[0]=='P' || is[0]=='p'){
		     char filename_3p_PS[13],file_ret;
		 
                     /*to redraw the whole thing exactly as is 
                             and save vector PostScript*/
		            if (is[0]=='p') basin_postScript=1;//color
		            else if (is[0]=='P') basin_postScript=2;//greyscale
		     
                            file_ret=select_filename("SAVE","PostScript file","*.ps","my_3pPS");
                            if (file_ret=='q'){
			       basin_postScript=0;
                               goto skipPS;
                            }
	                    memmove(filename_3p_PS,filename,13);
			    
                            //delete previous*/
                            fid_PS=myopen(filename_3p_PS,1,0);
                            vret=write(fid_PS,"",0);
                            close(fid_PS);

                            /*start new*/
                            fid_PS=myopen(filename_3p_PS,1,1);
                            if (fid_PS==-1){ 
                                  file_error(filename_3p_PS);
                                  close(fid_PS); 
                                  basin_postScript=0;
                                  goto skipPS;
			    }
			    
                            psize_ps=pointsize;
			    basin_postScript=1;
                            prepare_basinPS(2,2); /*write/define postScipt for wiring*/
			    
			    goto redo_postScript;
	          }		    
                skipPS:
		  if (basin_postScript==1){
		    close(fid_PS);
		    input_string(1,0);
		  }  
		  uncover_free_prompt_box(8);
		  
		  L=tempL;
		  i2d=tempi2d;
		  j2d=tempj2d;

		  basin_postScript=temp_basin_postScript;
		  isotropic_set=temp_isotropic_set;
                  it->divcolor=temp_divcolor;
		  
}



/********** stp interupt options and show rule, 93, 98 ************/
char interrupt_stp_box(signed int ypos, char* thisrule,
               unsigned long this_ittcount, 
               char* current_state,signed int stpwidth,
                   diff_var *dp, 
                   auto_ent *ae, 
                   ent_eeg *eg, 
                   int_stp *it){
 signed int xbox,xtopleft,ytopleft,xbotright,xxtext,
     ybotright,
     tablemax,tablebytes,
     z,prytopleft,prybotright;
 unsigned long ruledec,rule_dec_max;

 unsigned int cellindex;
 char reset=0; /*=1 start at top and reset ittcount, =2 reset ittcount*/
 /*NOTE:"forward_only" =1 for space-time patterns is a global variable set in drpara. 
 interrupt_stp_box() is also called from the top left basin complete option,
 (where forward_only=0) with just a few prompts for the rule and net*/ 
  
#   define put_free_9_4 {\
              sprintf(textb[9],"%s","boximage[4]");\
	      putimage(xtopleft,prytopleft,boximage[4],COPY_PUT,textb[9]);\
	      freeimage(boximage[4]);\
	      if (/*!rulemix && */forward_only){\
                 sprintf(textb[9],"%s","boximage[9]");\
		 putimage(xtopleft,ytopleft,boximage[9],COPY_PUT,textb[9]);\
		 freeimage(boximage[9]);\
	      }\
	      if (/*!rulemix && */!forward_only)\
	      show_rule_bottom(nhoodm[0],1,carule[0],0);\
    }

    
#   define rulemix_choose_cellindex {\
             draw_box(3,xtopleft,prybotright+vgay(3),\
		      xbotright,prybotright+vgay(16),1,0);\
	     moveto(xtopleft+3,prybotright+vgay(5));\
	     sprintf(textb[0],"enter cell index, %d-0:",lineL-1);\
	     outtext(textb[0]);\
	     sprintf(textb[0],"%d",lineL-1);\
	     input_string(strlen(textb[0]),0);\
	     if (atoi(is) >=0 && atoi(is)<lineL) cellindex=atoi(is);\
    }

#   define restore_cellindex_box {\
             sprintf(textb[9],"%s","boximage[3]");\
	     putimage (xtopleft,prybotright+vgay(3),boximage[3],COPY_PUT,textb[9]);\
	     freeimage(boximage[3]);\
    }
    
    xtopleft=ytopleft=xbotright=ybotright=prytopleft=prybotright=0;

    if (tot_only==0){
       if (set_iso_input_histogram==1) tablemax=iso_tablemax;
       else tablemax= (signed int)pow(value_range,(double)nhood)-1;
    }   
    else if (tot_only==1){
       if (totalistic==1) tablemax=nhood*(value_range-1);
       else if (totalistic==2) tablemax=v_tablecodemax[nhood];
    }
    tablebytes=(signed int)ceil(value_bits * (double)(tablemax+1)/8);
    
    if (forward_only==1) /*to note if the rule or wiring has changed*/
            was_changed=0; 
   start:
       setcolor(white);
       xtopleft=trboxw; /*same as prompt box*/
       ytopleft=ypos;
       xbotright=Maxx-2;
       xxtext=xtopleft+vgax(3);
     if (forward_only){
      char ruletype;
       ybotright=ypos+CHeight*5;
       draw_box(9,xtopleft,ytopleft,xbotright,ybotright,1,0);
       
       moveto(xxtext,ytopleft+vgay(4));
       setviewport(trboxw, gety, Maxx-vgax(4), gety+CHeight/2,0);      
       if (nhood_mixed==0){
	   foldposs=-1; /*very long*/
	   if (set_iso_input_histogram==1)
	     print_layered_bitstring(iso_rule,tablemax,vgax(2),1,0,1);
	   else print_layered_bitstring(thisrule,tablemax,4,1,0,1);
       }
       setviewport(0, 0, Maxx, Maxy, 0);
       rule_dec_max=max_dec_rule(tablemax,value_range);
       if (nhood_mixed==0 && rule_dec_max>0){ 
          ruledec=dec_equiv(thisrule,tablemax);    
	  moverel(CWidth,-vgay(3));
	  if (tot_only==0) sprintf(textb[1],"rcode");
          else if (tot_only==1){
             if (totalistic==1) sprintf(textb[1],"tcode");
             if (totalistic==2) sprintf(textb[1],"kcode");
          }
          sprintf(textb[0],"%s(dec)=%lu  ",textb[1],ruledec);
	  outtext(textb[0]);
       }
       /*show the rule in hex*/
       moveto(xxtext,gety+CHeight/2);
       setviewport(trboxw, gety, Maxx-3, 
                gety+ (signed int)((float)CHeight*1.6), 0);
       
       if (tot_only==1){
	  if (totalistic==1) ruletype=2;
          else if (totalistic==2) ruletype=3;
       }
       else{
	 if (set_iso_input_histogram==1) ruletype=4;
	 else ruletype=1;
       }	 
       moveto(xxtext,gety+vgay(2));
       if (nhood_mixed==0) 
          print_current_bitstring_hexbytes(2,ruletype,thisrule,nhood,xbotright,white,4);
       setviewport(0, 0, Maxx, Maxy, 0);

       moveto(xxtext,gety+
                  (signed int) ((float)CHeight*1.5)+vgay(3));

       if (tot_only==1){ 
          if (totalistic==1) sprintf(textb[1],"tcode");
          else if (totalistic==2) sprintf(textb[1],"kcode");
       }
       else{
	 if (set_iso_input_histogram==1) sprintf(textb[1],"iso-rcode (%d)",tablemax+1);
	  else sprintf(textb[1],"rcode");
       }	 
       if (nhood_mixed==0) sprintf(textb[ 0],"%s v%dk%d ",textb[1],value_range,nhood);
       else sprintf(textb[0],"%s v%dk(%d-%d) ",textb[1],value_range,nhood_lb,nhood_ub);
       outtext(textb[0]);
       if (nhood_mixed==0 && tot_only==0 && set_iso_input_histogram==0){

          /*update parameters*/
          if (value_range==2) z_parameter_all(nhood,0,thisrule);
          else z_parameter_all_mvalue(nhood,0,thisrule);
          post_func(nhood,thisrule, 0,0,0,0);

          sprintf(textb[0],"ld=%.3g ld-r=%.3g zl=%.3g zr=%.3g Z=%g",
			     lambda,lratio,zparam[1],zparam[2],zparam[0]);
          outtext(textb[0]);
          moveto(xxtext,gety+CHeight);
          /*show canalyzing inputs*/
          
          sprintf(textb[0],"C=%d/%d",canaltotal,nhood);
          if (canaltotal && nhood>1){
	        memmove(textb[0]+5," ",1);
	           for (z=nhood-1;z>=0;z--){
		      if (get_bit(canal,z)==1){
		         sprintf(textb[1],"%d",z);
		         memmove(textb[0]+6+nhood-1-z,textb[1],1);
	              }
	              else memmove(textb[0]+6+nhood-1-z,"*",1);
	          }
	  }
                 
          memmove(textb[0]+6+nhood,"\0",1);
          outtext(textb[0]);
       }
       if (oned) sprintf(textb[0],"  1d=%d",lineL);
       else if (twod) sprintf(textb[0],"  2d ij=%dx%d",i2d,j2d);
       else if (threed) sprintf(textb[0],"  3d ijh=%dx%dx%d",i3d,j3d,h3d);
       outtext(textb[0]);
       sprintf(textb[0]," time-step=%lu",this_ittcount);
       outtext(textb[0]);
       /*reset selected rule from entropy scatter plot*/
       if (totstatrules>0 && current_sample_index>0 && current_sample_index<=totstatrules){
         unsigned long ruleindex;
	 signed int rulebytes;
	  sprintf(textb[0]," sample_index=%lu",current_sample_index);
	  outtext(textb[0]);
          ruleindex=current_sample_index;/*to keep track of sample_index*/
          rulebytes=tablebytes;
          it->statrule_index=current_sample_index;
          //fprintf(stderr,"\n%lu",it->statrule_index);
              if (tot_only==0){
                 if (set_iso_input_histogram==1)
                    memmove(iso_rule,statbuf+(ruleindex-1)*(rulebytes+2),rulebytes);
                 else memmove(carule[0],statbuf+(ruleindex-1)*(rulebytes+2),rulebytes);
              }
              else if (tot_only==1){
                 if (totalistic==1) memmove(cacode[0],
                       statbuf+(ruleindex-1)*(rulebytes+2),rulebytes);
                 else if (totalistic==2) memmove(v_code[0],
                       statbuf+(ruleindex-1)*(rulebytes+2),rulebytes);
              }
       }
    }

    /*------------------ start interrupt prompts--------------------*/ 
    prytopleft=ybotright;
    /*space-time patterns only*/
    if (forward_only) prybotright=prytopleft+6*CHeight;
    else if (!basinfield) prybotright=prytopleft+5*CHeight;
    else prybotright=prytopleft+4*CHeight;

    draw_box(4,xtopleft,prytopleft,xbotright,prybotright,1,0);
    moveto(xxtext,prytopleft+vgay(4));
    if (tot_only==0) sprintf(textb[0],
         "rule:save/load/revise/rnd/trans-s/l/v/r/t net-n");
    else sprintf(textb[0],"rule:save/load/revise/rnd-s/l/v/r net-n");
    if (forward_only) sprintf(textb[1]," sample:load/keep-E/K");
    else sprintf(textb[1],"");
    sprintf(textb[3],"%s%s",textb[0],textb[1]);
    outtext(textb[3]);
    moveto(xxtext,gety+CHeight);
    for (z=0;z<=4;z++) sprintf(textb[z],""); /*clear buffs*/

    if (iso_tablemax==101 && twod && value_range==2) sprintf(textb[2],"iso-patterns-i ");
    else if (loc_twod_fonly==0 && tot_only==0) sprintf(textb[2],"canal-C ");
    else sprintf(textb[2],"");
    
    if (forward_only){
       if (d_mode==1 || d_mode==2) sprintf(textb[3],"PScript-P ");
       if (glider_rule_order==-1) sprintf(textb[1],"(rnd/seq)-G");
       else sprintf(textb[1],"(seq/rnd)-G");
       if (no_glider_rules[value_range][(signed int)nhoodm[0]]>=1)
	                                   sprintf(textb[4],"g-rules");
       else{
          sprintf(textb[4],"");
          sprintf(textb[1],"");
       }               
       if (tot_only==0){
          if (rulemix) sprintf(textb[0],
           "%s%s %s%s",textb[3],textb[2],textb[4],textb[1]);
          else sprintf(textb[0], 
           "%sZ:high/low-Z/z %s%s%s",textb[3],textb[2],textb[4],textb[1]);
       }
       else sprintf(textb[0],"%s%s%s",textb[3],textb[4],textb[1]);
      
    }
    else{
       if (rulemix==0) sprintf(textb[0],
	  "valueflip-1 allv-b Z:higher/lower-Z/z %s",textb[2]);
       else sprintf(textb[0],
	  "valueflip-1 allv-b %s",textb[2]);
    }
    outtext(textb[0]);
    moveto(xxtext,gety+CHeight);
    if (forward_only){
       sprintf(textb[0],
	"state:rev-e rnd/Ham/blk/orig/last-R/H/k/o/~ sng:pos/neg-5/6 save/load-S/L");
       if (eg->showlookupfreq) sprintf(textb[5]," filter-f ");
       else sprintf(textb[5]," ");
       if (it->stp_speed>0) sprintf(textb[6],"slow");
       else sprintf(textb[6],"max"); 
       if (graph_layout==1)  sprintf(textb[1],
	   "graph-g/p border-B%sskip-X pause-N step-x/+ speed(%s)-V",textb[5],textb[6]);
       else sprintf(textb[1],
		    "graph-g border-B%sskip-X pause-N step-x/+ speed(%s)-V",textb[5],textb[6]);
       outtext(textb[0]);
       moveto(xxtext,gety+CHeight);
       outtext(textb[1]);
       if (forward_only==1){
         //fprintf(stderr,"\neg->showeeg=%d it->time_step_density_plot=%d",eg->showeeg,it->time_step_density_plot);
         //fprintf(stderr,"\neg->lookup_entropy=%d  ae->show_edata=%d",eg->lookup_entropy,ae->show_edata);
	 if (eg->showeeg==1 && it->time_step_density_plot){
             outtext(" dnsty-d");
         }
         else if (eg->lookup_entropy && ae->show_edata==0){
             outtext(" entropy-d");
             if (it->track_pulsing==1){
	        fprintf(stderr,"\nav-wl=%.2f, av-wh=%.3f, sample=%lu",
	                       it->av_wave_length,it->av_wave_height,it->wave_sample);
                if (it->time_step_density_plot==2){
                    sprintf(textb[0],"\naverage: wl=%.2f, wh=%.3f, sample=%lu",
                               it->av_wave_length,it->av_wave_height,it->wave_sample);
                    save_data(textb[0]);
		}
             }
         }
       }
       moveto(xxtext,gety+CHeight);
       if (it!=NULL) sprintf(textb[0],"top-T on-the-fly-y hide-W back-q cont-ret:");
       else sprintf(textb[0],"top-T hide-W back-q cont-ret:");
       outtext(textb[0]);     

    }
    else if (!basinfield){ /*single basin*/
       sprintf(textb[0],
	"seed:rev-e rnd/blk-R/k sng:pos/neg-5/6 save/load-S/L");
       sprintf(textb[1],"back-q cont-ret:");
       outtext(textb[0]);
       moveto(xxtext,gety+CHeight);
       outtext(textb[1]);
    }
    else{
       sprintf(textb[1],"back-q cont-ret:");
       outtext(textb[1]);
    }


    input_string(1,0);
    /*------------------ end interrupt prompts--------------------*/ 

    if (is[0]!=13) reset=0;
    switch(is[0]){
       case 'q':
          if (1){ /*to remove all mutation blocks, set/removed on-the-fly 1/2, Oct2020*/
	    signed int filter_bytes; 
             filter_bytes=(unsigned int)ceil((double)(tablemax+1)/8);
             free(mutation_filter);
             if ((mutation_filter=(char *)calloc(filter_bytes,sizeof(char)))
				==NULL) outof_memory("mutation_filter");
             for (z=tablemax; z>=0; z--){  /*remove all filters + block marks*/
                    set_bit0(color_filter,z);
             } 
          }
	  graph_layout=0;
	  ittpause=0;
          stppause=0;
          /*scrolling=0;*/
          reset=1;
          break;
       case 'd': /*save density data -- from density return map if active, 
                   or from entropy/density plot*/
         if (forward_only==1){
	   if (eg->showeeg==1 && it->time_step_density_plot){
             char file_ret;
             xbox=draw_prompt_box(1);
             if (it->time_step_density_plot==2){ /*if already saving*/
	        outtext("now saving dnsty: stop-s, start new file-n, cont-ret:");
                input_string(1,0);
                if (is[0]=='s'){
                   it->time_step_density_plot=1;
                   goto skip_data;
                }
                else if (is[0]=='n') close(fid_data);                     
                else goto skip_data;
             }  
	     else it->time_step_density_plot=2;/*to save each density*/

             file_ret=select_filename("SAVE","DATA","*.dat","my_dnsty");
             if (file_ret=='q') goto skip_data;
	     memmove(filename_data,filename,13);
             fid_data=myopen(filename_data,1,0);
             if (fid_data==-1) file_error(filename_data);
             else{
                vret=write(fid_data,"",0);
                close(fid_data);
                sprintf(textb[0],
                   "density return map: start time-step=%lu\n",it->ittcount);                
                save_data(textb[0]);
             }
           }
           else if (eg->lookup_entropy && ae->show_edata==0){
             char file_ret;
	     reset=0;
             xbox=draw_prompt_box(1);
             if (it->time_step_density_plot==2){ /*if already saving*/
	        outtext("now saving entropy: stop-s, start new file-n, cont-ret:");
                input_string(1,0);
                if (is[0]=='s'){
		   it->track_pulsing=0;                   
                   it->time_step_density_plot=1;
                   goto skip_data;
                }
                else if (is[0]=='n') close(fid_data);                     
                else goto skip_data;
             } 

	     // else it->time_step_density_plot=2;/*to save data*/

             xbox=draw_prompt_box(1);
	     outtext("start new entropy data file-n:");
             input_string(1,0);
             if (is[0]=='n'){
               it->time_step_density_plot=2;/*to save data*/
	       close(fid_data);
	     }  
	     else{
                  it->time_step_density_plot=1;
                  goto skip_data;
             }
             file_ret=select_filename("SAVE","DATA","*.dat","my_entr");
             if (file_ret=='q') goto skip_data;
	     memmove(filename_data,filename,13);
             fid_data=myopen(filename_data,1,0);
             if (fid_data==-1) file_error(filename_data);
             else{
	        it->ittcount=0;
                it->track_pulsing=1;
                vret=write(fid_data,"",0);
                close(fid_data);
             }
           }
         }
       skip_data:
         put_free_9_4;
	 return(reset);

       case 'P': /*create .ps vector postcript file for Latex*/
         if (forward_only==1 && d_mode<3){
	    /*fprintf(stderr,"\nP:it->show_2d_divs=%d it->divcolor=%d",it->show_2d_divs,it->divcolor);*/
	    if (d_mode==2) save_to_PostScript(current_state,i2d,j2d,-2,
                            0,scale,it->show_2d_divs,it->divcolor,'d',stagger_even_rows,0);
            else if (d_mode==1) save_to_PostScript(current_state,lineL,Maxx/scale,-1,
                            0,scale,it->show_2d_divs,it->divcolor,'d',stagger_even_rows,0);
         }
         put_free_9_4;
         goto start;
       case 'G': /*for glider rules, toggle rand/seq order*/
          if (forward_only==1 &&
                no_glider_rules[value_range][(signed int)nhoodm[0]]>=1){
	    signed int g_no;
            glider_rule_order=-1;/*default random*/
	    g_no=no_glider_rules[value_range][(signed int)nhoodm[0]]-1;
            xbox=draw_prompt_box(2);
	    sprintf(textb[0],
	      "%d v%dk%d complex rules (select on-the-fly with \"g\")",
                                             g_no,value_range,nhoodm[0]);
            outtext(textb[0]);
            moveto(xbox,gety+CHeight);    
            sprintf(textb[1],"consecutive enter start 1-%d, rnd-r:",g_no);
            outtext(textb[1]);
            input_string(2,0);
	    if (atoi(is)>=1 && atoi(is)<=g_no)  
                                  glider_rule_order=atoi(is)-1;
	  }
          put_free_9_4;
          goto start;
       case 'B': /*set a fixed border 1,2,3d to try to absord gliders etc*/
         if (forward_only==1){
           signed int smallaxis;
           char max_b; /*border, b_value - char global variables*/
            /*find smallest axis*/
	    if (oned) smallaxis=lineL;
            else if (twod){ 
	       smallaxis=j2d;
               if (i2d<j2d) smallaxis=i2d;
            }
            else if (threed){             
               smallaxis=j3d;
               if (i3d<j3d) smallaxis=i3d;
               if (h3d<smallaxis) smallaxis=h3d;
            } 
            if (smallaxis>127) smallaxis=127;
            max_b=smallaxis/5;
            if (max_b>9) max_b=9;
	    else if (max_b<=0) max_b=1;
	    start_border:
            xbox=draw_prompt_box(2);
            sprintf(textb[0],"fixed border: width (0-%d, now %d): ",
                                      max_b,border);
	    outtext(textb[0]);
            input_string(1,0);
            if (is[0]=='q') goto skip_border;
	    if (is[0]!=13 && atoi(is)>=0 && atoi(is)<=max_b)  
                                   border=atoi(is);
            moveto(xbox,gety+CHeight);
            sprintf(textb[0],"border value: (0-%d, now %d): ",
                                      value_range-1,b_value);
            outtext(textb[0]);
            input_string(1,0);
            if (is[0]=='q') goto start_border;
	    if (is[0]!=13 && atoi(is)>=0 && atoi(is)<=value_range-1) 
                                   b_value=atoi(is);
	    skip_border:;    
         } 
         put_free_9_4;
         goto start;
       /*show rule statistics*/
       case 'E':
          if (forward_only){/*space-time patterns only*/
             /*cancel a patch (if set) in entropy scatter plot*/
             xstat1=ystat1=xstat2=ystat2=0;

             min_max_entropy=1;
             draw_prompt_box(1);
             sprintf(textb[0],
               "load sample: entropy variability, sdev-s,  min-max -(def):");
             outtext(textb[0]);
             input_string(1,0);
             if (is[0]=='s') min_max_entropy=0;
             sprintf(textb[9],"%s","boximage[4]");
             putimage(xtopleft,prytopleft,boximage[4],COPY_PUT,textb[9]);
             sprintf(textb[9],"%s","boximage[9]");	      
	     putimage(xtopleft,ytopleft,boximage[9],COPY_PUT,textb[9]);
             if (is[0]!='q') load_rule_stats(0,stpwidth);/*load new sample*/
	     /*load_rule_stats(0,stpwidth);*//*load new sample*/	    
          }
          put_free_9_4;
	  goto start;
       case 'K':
          if (forward_only && totstatrules>1){/*space-time patterns only*/
             /*cancel a patch (if set) in entropy scatter plot*/
             xstat1=ystat1=xstat2=ystat2=0;

             sprintf(textb[9],"%s","boximage[4]");
             putimage(xtopleft,prytopleft,boximage[4],COPY_PUT,textb[9]);
             sprintf(textb[9],"%s","boximage[9]");	      
	     putimage(xtopleft,ytopleft,boximage[9],COPY_PUT,textb[9]);
	     load_rule_stats(1,stpwidth);/*keep existing sample*/
             stat_rule(1,it->statrule_index,it,eg->stpwidth);//show top-right info
          }
          put_free_9_4;
	  goto start;
       /*revise rule*/
       case 'v':
	  cellindex=0;
	  if (rulemix) rulemix_choose_cellindex;	  
          /*restore below top right prompts -- not to confuse with new prompts*/
          sprintf(textb[9],"%s","boximage[4]");
          putimage(xtopleft,prytopleft,boximage[4],COPY_PUT,textb[9]);	      
	  if (forward_only){
               sprintf(textb[9],"%s","boximage[9]");
               putimage(xtopleft,ytopleft,boximage[9],COPY_PUT,textb[9]);
          }         
	  revise_rule_or_code(cellindex);
	  if (rulemix) restore_cellindex_box;
	  was_changed=1;
	  reset=2;
	  put_free_9_4;
	  goto start;
      case 'r': /*random rule/s*/
	     bit_flip('r',white);
	     was_changed=1;
	     reset=2;
	     put_free_9_4;
	     goto start;
      case 't':
	  if (tot_only==0){
             cellindex=0;
	     if (rulemix) rulemix_choose_cellindex;   
	     transform_rule(cellindex);
             tablemax= (signed int)pow(value_range,(double)nhood)-1;
             tablebytes=(signed int)ceil(value_bits * 
                                             (double)(tablemax+1)/8);
             if (rulemix) restore_cellindex_box;
	     was_changed=1;
	     reset=2;
	     put_free_9_4;
          }
	  goto start;
      case 'n':
	 if (loc_twod_fonly==0 && loc_twod_fonly==0){
	     show_w_r_scheme();
	     was_changed=1;
	     reset=2;	     
	 }
         put_free_9_4;
	 goto start;
       case 'C': /*canalizing needs full lookup-table*/
	 if (tot_only==0 && loc_twod_fonly==0){
             if (rulemix) set_canalyzing_net(0);
             else set_canalyzing_rule(0);
             was_changed=1;
	     reset=2;             
         }
         break;
         case 'i':/*define and show range of 3x3 iso-rule seeds*/
	   
	   if (iso_tablemax==101 && twod && value_range==2){
	     char active_d=0;
	      
	    start_i:  
              xbox=draw_prompt_box(2);
              outtext("numbers of 1s in 3x3 pattern: (3,4,5,6)");
	      outtext(" now(");
	      for (z=3;z<=6;z++){
		 if (it->req_iso_ptrns[z]==z){
		    if (z<6) sprintf(textb[0],"%d,",it->req_iso_ptrns[z]);
		    else sprintf(textb[0],"%d",it->req_iso_ptrns[z]);
		 }
	         else{
		     if (z<6) sprintf(textb[0],"_,");
		     else sprintf(textb[0],"_)");
		 }
		 outtext(textb[0]);
              }
	      outtext(" accept-a, reset-ret:");
	      input_string(1,0);
	      if (is[0]=='a' || is[0]=='q') break;
	      
              moveto(xbox,gety+CHeight);
	      active_d=0;
	      outtext("enter y to include: ");
	      for (z=3;z<=6;z++){
		 sprintf(textb[0]," %d:",z);
		 outtext(textb[0]);
		 input_string(1,0);
		 if (is[0]=='y'){
		    it->req_iso_ptrns[z]=z;
		    active_d+=1;
		    outtext("  ");
		 }		 
		 else{
		   it->req_iso_ptrns[z]=0;
		   outtext("_ ");
		 }		 
	      }
	      if (active_d==0) it->req_iso_ptrns[4]=4;//restore default 4/9 if none set
	      outtext("  result(");
	      for (z=3;z<=6;z++){
		 if (it->req_iso_ptrns[z]==z){
		    if (z<6) sprintf(textb[0],"%d,",it->req_iso_ptrns[z]);
		    else sprintf(textb[0],"%d)",it->req_iso_ptrns[z]);
		 }
	         else{
		    if (z<6) sprintf(textb[0],"_,");
		    else sprintf(textb[0],"_)");
		  }
		  outtext(textb[0]);
              }
	      
	      
	      outtext(" reset-r show-s:");
	      input_string(1,0);
	      if (is[0]=='r') goto start_i;
	      else if (is[0]=='s'){
		 show_three_block_iso_patterns(it);
	         goto start_i;
	      }
	      else break;	            
	   }
	   break;
	 
       case 'e':
	  if (!basinfield){             
             if (forward_only){
                xbox=draw_prompt_box(1);
	        outtext(
                   "revise/reset seed: original-o last-l current-c:");
	        input_string(1,0);   
	        moveto(vgax(200),vgay(315));
	        if (is[0]=='c'){
		   if (d_mode==4) memmove (bitseed,it->last_state1[1],bytesL);
                   else memmove(bitseed,current_state,bytesL); 
                   select_seed(0,bitseed,"SEED",1);
                   memmove(state1,bitseed,bytesL);
                }
                else if (is[0]=='l'){
                   memmove(bitseed,this_firstseed,bytesL);
                   select_seed(0,bitseed,"SEED",1);
                   memmove(state1,bitseed,bytesL);
                   slant=-1;
		}
                else if (is[0]=='o'){ 
                    select_seed(0,bitseed,"SEED",1);
	            memmove(state1,bitseed,bytesL);
                    slant=-1;
                }
             }
             else{ 
	        moveto(vgax(200),vgay(315));
                select_seed(0,bitseed,"SEED",1);
	     }
	     put_free_9_4;
	     goto start;
	  }
          break;
       case 'R':
	  if (!basinfield){
	     random_seed(white,100,0);
	     memmove(bitseed,state1,bytesL);
 	     put_free_9_4;
             slant=-1;
	     goto start;
	  }
	  break;
	case 'H':
	  if (!basinfield){
            signed int rand_seed_percent=100;
	     draw_box(3,xtopleft,prybotright+vgay(3),
		      xbotright,prybotright+vgay(16),1,0);
	     moveto(xtopleft+3,prybotright+vgay(5));
	     sprintf(textb[0],"enter %% random Hamming change to current state:");
             outtext(textb[0]);
	     input_string(3,0);
             if (is[0]=='q' || is[0]==13); /*do nothing*/
             else{
	        if (atoi(is) >=0 && atoi(is)<=100) rand_seed_percent=atoi(is);
                if (rand_seed_percent>0)
	             random_seed(white,rand_seed_percent,0);
             }
             sprintf(textb[9],"%s","boximage[3]");
	     putimage (xtopleft,prybotright+vgay(3),boximage[3],COPY_PUT,textb[9]);
	     freeimage(boximage[3]);
	     put_free_9_4;
             slant=-1;
	     goto start;
	  }
	  break;

       case 'k': /*set random block*/
	  if (!basinfield){
	     start_set_block:
             draw_prompt_box(1);
	     sprintf(textb[0],
               "rnd block: change size (now %d), rest: keep-k, all 0s-(def):",seglen);
             outtext(textb[0]);
             input_string(3,0);
             if (is[0]=='k') random_block(1,seglen,white); /*keep rest*/
             else if (is[0]==13 || is[0]=='0') random_block(0,seglen,white); /*new*/
             else if (atoi(is)>0){
                 if (oned && atoi(is)<=lineL) seglen=atoi(is);
                 else if (twod && atoi(is)<=i2d && atoi(is)<=j2d) 
                                                         seglen=atoi(is);
                 else if (threed && atoi(is)<=i3d && 
                         atoi(is)<=j3d && atoi(is)<=h3d) seglen=atoi(is);
                 goto start_set_block;
             }
	     memmove(bitseed,state1,bytesL);
	     put_free_9_4;
             seed_was_set=1;
             slant=-1;
	     goto start;
	  }
	  break;
       case 'o':/*set original seed*/
             if (!basinfield){
                  memmove(state1,bitseed,bytesL);
		  put_free_9_4;
                  seed_was_set=1;
                  slant=-1;
	          goto start;
	     }
       case '~':/*reset last seed, which was set on-the-fly*/
             if (!basinfield){
                  memmove(state1,this_firstseed,bytesL);
		  put_free_9_4;
                  seed_was_set=1;
                  slant=-1;
	          goto start;
	     }
       case '5':
	  if (!basinfield){
	     singleton_seed(1,white);
	     if (!forward_only) memmove(bitseed,state1,bytesL);
	     put_free_9_4;
             seed_was_set=1;
             slant=-1;
	     goto start;
	  }
	  break;
       case '6':
	  if (!basinfield){
	     singleton_seed(0,white);
	     if (!forward_only) memmove(bitseed,state1,bytesL);
	     put_free_9_4;
             seed_was_set=1;
             slant=-1;
	     goto start;
	  }
	  break;	
	case 'S': /*save original seed, current state, or transient*/
	  if (!basinfield){
	     draw_prompt_box(1);
	     if (direction=='f' && limitcheck==0)
                  outtext("save seed: original-o last-l  current-c:");
             else outtext("save seed: original-o current-c:");
             /* save the transient, not implimented */
	     /*if (frozen_gens<=this_ittcount+1){
		moveto(xbox,gety+CHeight);
		sprintf(textb[0],
		   "save trans last %d (f-gens) time-steps -t:",frozen_gens);
		outtext(textb[0]);
	     }*/
	     input_string(1,0);
	     if (is[0]=='c'){
                if (direction=='f' && limitcheck==0)
                   load_save_wrs('s',current_state,'s'); 
                else load_save_wrs('s',state1,'s');
             } 
             if (is[0]=='l' && direction=='f' && limitcheck==0)
                           load_save_wrs('s',this_firstseed,'s');    
             else if (is[0]=='o') load_save_wrs('s',bitseed,'s');
	     else if (is[0]=='t'){
	       /* save the transient */
	     }
	     put_free_9_4;
	     goto start;
	  }
	  break;       
       case 'L': /*load seed*/
	  if (!basinfield){
	     load_save_wrs('l',state1,'s');
	     put_free_9_4;
             seed_was_set=1;
	     goto start;
	  }
	  break;

       /* enter any on-the-fly option */
       case 'y':
	 if (forward_only && it!=NULL){
            /*isolate the prompt to see on-the-fly options*/
            sprintf(textb[9],"%s","boximage[4]");
	    putimage(xtopleft,prytopleft,boximage[4],COPY_PUT,textb[9]);
            sprintf(textb[9],"%s","boximage[9]");\
	    putimage(xtopleft,ytopleft,boximage[9],COPY_PUT,textb[9]);

            //draw_prompt_box(1);
            draw_box(-1,Maxx-vgax(130),2,Maxx-2,2+CHeight+vgay(6),1,0);
            sprintf(textb[0],"enter on-the-fly option:");
            outtext(textb[0]);
            input_string(1,0);/*any printing character*/
            if (is[0]!=13){ 
	         interrupt_stp(dp,ae,eg,it);
                 it->hex_rad=(double)it->fscale * cos(PI/6)*2/3;
            } 
            erase_box(Maxx-vgax(130),2,Maxx-2,2+CHeight+vgay(6)); 
            put_free_9_4;          
	    goto start;
	 }

       /*toggle local...nonlocal wiring -- done in 'y' above*/
       /*case '7':
	  if (forward_only && !loc_twod_fonly && nonlocal)
	     wiring_madelocal=abs(wiring_madelocal-1);
	     break;*/
             
       case 'W': /*hide the options window, Feb05*/
	 if (forward_only){
	    /*sprintf(textb[9],"%s","boximage[4]");
	      putimage(xtopleft,prytopleft,boximage[4],COPY_PUT,textb[9]);*/	    
	    put_free_9_4;
            input_string(1,0);
	    goto start;
	 }
       
       case 's':{ /*save rule*/
         char temptot;
	  put_free_9_4;    
          if (tot_only==0){
             temptot=totalistic; 
             totalistic=0;
          }
          /*not iso_rule -- see for73.c line 2490*/
          if (set_iso_input_histogram==1) load_save_wrs('s',carule[0],0);
	  else load_save_wrs('s',thisrule,0);
          if (tot_only==0) totalistic=temptot;
	  goto start;
       }       
       case 'l':{ /*load rule*/
         char temptot;
	  put_free_9_4;
          if (tot_only==0){
             temptot=totalistic; 
             totalistic=0;
          }          
          if (set_iso_input_histogram==1){
            /*not iso_rule, load rcode then convert to iso-rule -- see for73.c line 2490*/
            signed int thistablemax;
             thistablemax= (signed int)pow(value_range,(double)nhood)-1;   
             load_save_wrs('l',carule[0],0);
             isotropic_rule(0,carule[0],nhood,0,thistablemax,thistablemax,-2);
          }
	  else load_save_wrs('l',thisrule,0);
          if (tot_only==0) totalistic=temptot;
	  was_changed=1;
	  goto start;
       }       
       case '1': /*random bit flip - rule: attractor basin*/
          if (forward_only==0){
	     bit_flip('1',0);
	     was_changed=1;
	     put_free_9_4;
	     goto start;
          }
       case 'p': /*show in graph layout at same time*/
          if (forward_only==1 && graph_layout==1){
	     postScript_graph_state=0;
             draw_prompt_box(1);
             outtext("save network-graph snapshot to PScript: abort-q greyscale-P color-def:");
             input_string(1,0);
             if (is[0]=='q'); /*abort*/
             else{
                if (is[0]=='P') postScript_graph_state=2;
                else postScript_graph_state=1;
             }
          }
          break;

      case 'g': /*show in graph layout at same time*/
          if (forward_only==1){
	     graph_layout=abs(graph_layout-1);
             reset=1; 
          }
          break;
 
       case 'Z': /*flip for higher z*/
	  if (!rulemix){
	     bit_flip('Z',0);
	     was_changed=1;
	     put_free_9_4;
	  }
	  goto start;       
       case 'z': /*flip for lower z*/
	  if (!rulemix){
	     bit_flip('z',0);
	     was_changed=1;
	  }
          put_free_9_4;
	  goto start;

       /*case 'w': //flip nhood all 1s
	  bit_flip('w',0);
	  was_changed=1;
	  put_free_9_4;
	  goto start;*/

       case 'b': /*flip outputs of uniform nhoods to the nhood value 
                 (all0s->0 all1s->1 etc)*/
	  bit_flip('B',0);
	  was_changed=1;
	  put_free_9_4;
	  goto start;       
       case 'T': /*continue space-time pattern from top, and reset ittcount*/
	  if (forward_only) reset=1;
          break;
       case 'N':
          if (!basinfield){
             ittpause=stppause=0; 
             xbox=draw_prompt_box(2);
             sprintf(textb[0],
                  "pause: screen full-p, after f-gens(%d)-f",frozen_gens);
             outtext(textb[0]);
             moveto(xbox,gety+CHeight);       
	     outtext("or enter time-step (no pause-def):"); 
             input_string(5,0);
             if (is[0]=='f'){
                 ittpause=(unsigned long)frozen_gens;
                 stppause=1;
             }
             else if (is[0]=='p') stppause=1;
             else if (is[0]!=13 && atol(is)>0){
                 ittpause=atoi(is);
                 stppause=1;
             }
             if (ittpause>=1) reset=2;
          }
          put_free_9_4;
	  goto start;

       /*superseded because hide-W does the same job, and Q was confusing*/
       /*case 'Q': //to pause stp on 'q' or screenfull without this options window          
	  stppause=2; 
          put_free_9_4;
          goto start;*/

       case 'x': /*pressing x iterates ittpause time-steps*/
	 if (!basinfield){ 
             if (ittpause==0) ittpause=(unsigned long)frozen_gens;
             stppause=1;
             reset=2;
          }
	  break;
       case '+': /*pause at each itteration, is[0]=='+'*/          
	  break;

       case 'V':
            if (slowfactor==0) slowfactor=300;
            sprintf(textb[0],
	       "speed: max-(def), or slowmotion (try %d):",slowfactor);
	    draw_prompt_box(1);
	    outtext(textb[0]);
            input_string(6,0);
            if (is[0]==13) pre_speed=0;
            else if (atol(is)>1){ 
               slowfactor=atol(is);
               pre_speed=slowfactor*500;
            }
            it->stp_speed=pre_speed;
            break;

       case 'X': /*timesteps that may be  skipped, set with P on the fly*/          
          draw_prompt_box(1);
          sprintf(textb[0],"skip time-steps (now %d):",time_skip);
          outtext(textb[0]);
          input_string(4,0);
          if (is[0]!=13 && atol(is)>0) time_skip=atoi(is);
          put_free_9_4;
	  goto start;
      
       case 'f':{ /*filter colors*/ 
          char found;
          signed int k_index;

          if (eg->showlookupfreq==0) break;

         sprintf(textb[9],"%s","boximage[4]");
         putimage(xtopleft,prytopleft,boximage[4],COPY_PUT,textb[9]);	
	 if (!rulemix && forward_only){
             sprintf(textb[9],"%s","boximage[9]");
	     putimage(xtopleft,ytopleft,boximage[9],COPY_PUT,textb[9]);	
	 }

        start_filter:
          found=0;
	  /*draw_box(3,xtopleft,prybotright+vgay(3),
		      xbotright,prybotright+vgay(16)*2,1,0);*/
          xbox=draw_prompt_box(2);
	  /*moveto(xtopleft+3,prybotright+vgay(5));*/
	  outtext("filtered: ");
          for (z=tablemax; z>=0; z--){
	     if (get_bit(color_filter,z)==1){
                  sprintf(textb[0],"%d ",z);
                  outtext(textb[0]);
                  found=1;
             }
	   }
           if (found==0) outtext("none");
           /*moveto(xtopleft+3,prybotright+vgay(5)+CHeight);*/  
           moveto(xbox,gety+CHeight);       
	   sprintf(textb[0],
             "filter/undo enter +/- k-index (%d-0), max-m reset-r:",tablemax);
           outtext(textb[0]);

	   sprintf(textb[0],"%d",tablemax);
	   input_string(strlen(textb[0])+1,0);

    
           if (is[0]=='q' || is[0]==13){
              put_free_9_4;
	      goto start;
              /*
              sprintf(textb[9],"%s","boximage[3]");
              putimage (xtopleft,prybotright+vgay(3),boximage[3],COPY_PUT,textb[9]);
	      freeimage(boximage[3]);
              is[0]=0;
              break;*/
	   }
           if (is[0]=='m'){
	     /*find greatest unfilterd bar in histogram - filter it*/
             signed int biggest,bigbar=0;

             for (z=tablemax; z>=0; z--){
                 if (bigbar<hist_order[z] && get_bit(color_filter,z)==0){
                     bigbar=hist_order[z];
                     biggest=z; 
                 }
	     }
             set_bit1(color_filter,biggest);
             
           }

           else if (is[0]=='r'){
             if (found==1){
                for (z=tablemax; z>=0; z--) set_bit0(color_filter,z);
	     }
           }
	   else if (abs(atoi(is)) >=0 && abs(atoi(is))<=tablemax) {
               k_index=atoi(is);
               if (is[0]=='-') set_bit0(color_filter,abs(k_index));
               else set_bit1(color_filter,abs(k_index));

		     //if (k_index>0) set_bit1(color_filter,k_index);
		     //else set_bit0(color_filter,abs(k_index));
	   }
           erase_prompt_box(2);
           /*freeimage(boximage[3]);*/
           goto start_filter;
	}
    } /*end switch*/

    /*in case this takes time*/
    //xbox=
    inset_prompt_box(0,26,"freeing stuff forint - please wait",'m'); //!!
    //seems to leave debris - why ??
    put_free_9_4;
    
    /*erase_prompt_box(1);*/   
    /*reset=1 start at top and reset ittcount, =2 reset ittcount*/

    return(reset);
}

/*----------------------------------------------------------------------------*/









