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

/***************** DRAW PARAMETERS (borland=watcom) ***************/
#include "edecfunc.h"
#include <fcntl.h>

typedef struct D_prompts {
   char suppress_fuzz,
     show_details,
     end_label;
   unsigned int 
        itlimit;
   signed int
        D_sample,
        Hamm_step;
   float maxH;
} D_prompts;

/***************  list of functions in this file ************/
/*void select_pattern_scrolling(void)*/
/*void setup_plot(void)*/
/*void amend_layout(void)*/
void set_layout_defaults(void);
void draw_layout_preview(void);
/*void format_draw(void)*/
/*void data_att(void)*/
/*void postScript_basin(void)*/
/*void jumpgraph_basinfield(void)*/ //"also to select ibaf and istr_graph"
/*void set_mutation(void)*/
void set_bit_flips(void);
/*unsigned char wire_move(char what,unsigned char color1)*/
/*void select_foreward_back(void)*/
/*void forward_only_para(void)*/
void setup_int_sequence(void);
void setup_random_sequence(void);
void load_save_order(char load_save);
void set_all_orders(void);
/*unsigned long order_to_index(char *order,unsigned int thislineL)*/
/*void index_to_order(unsigned long index, char *thisorder,
                                           unsigned int thislineL)*/
/*void set_seq_update(char **thisrule)*/ /*changed from (void) May07 to allow
                                      totalistic codes*/
void duplicate_net(void);
/*void draw_Derrida_plot(char **thisrule)*/
char get_D_para(char interupted, D_prompts *this);
void draw_general_graph_frame(float this_maxH,char draw_clear,
   signed int xstart,signed int ystart,
        signed int xsize,signed int ysize,
         signed int xmaxdiv,signed int ymaxdiv);
/*void select_stepforward(void)*/

float xpspacing,ypspacing,/*spacing between basins, % half screen x-axis*/
      xpspacefact,ypspacefact;/* % increace in spacing for successive L*/

signed int fid_derrida_PS;
char derrida_postScript;

/**************** scroll space time pattern, 13 May 1993 ************/
void select_pattern_scrolling(void){
 double temp,xbox,tempx;
 char *tempcode1,dontbias;
 unsigned int leftboxx,rightboxx,boxy,poss;

   //fprintf(stderr,"\ndrparsxx: dontcompress=%d",dontcompress);

   /*cancel a patch (if set) in entropy scatter plot*/
   xstat1=ystat1=xstat2=ystat2=0;

   /*input-histogran according to iso-rule in forx.c*/
   set_iso_input_histogram=0;
   iso_rule_allowed=0;
   if (tot_only==0 && rulemix==0 && nhood_mixed==0){
      if (oned || (twod && nhood>=2 && nhood <=10) || (threed &&  (nhood==6 || nhood==7))){
         iso_rule_allowed=1;
      }
   }

   istr_node_count=0;//for istr_graph
   //NULLboundaries=0;
   jump_layout_only=0;/*the jump_graph without  links*/
   jump_graph=0;/*to show the jump_graph after drawing the basin of att field (with dontcompress on)*/
   graph_layout=0;/*to run stp on graph layX2out*/
   ibaf_graph=0;
   /*to show an interactive the state transition graph 
                 after drawing the basin of att field by exhaustive testing*/
   /*for interactive state transition graph, field, compression can be on or off, 
     also single basin and subtrees which can be partly drawn if limit backsteps
     or exceeds smax_istr_node_no, 
     or (including feild)  can be partly drawn if interrupted or paused*/ 
   istr_graph=0;
   screensavedemo=0;
   exhaustive_testing=0;
   Ham_bias=0; 
   psize_ps=pointsize;
   pre_speed=0; /*to slow down basins on-the-fly:*/
   slowfactor=0; /* or to slow on interrupt, or here, also apples to stp */
  
   pause_fact=1.0;/*to change length of pause, mutantdontpause*/
   
   update_prob=1.0;
   temp_update_prob=1.0;/*set the default update prob*/
   out_prob=1.0;/*set the default output prob*/
   temp_out_prob=1.0;
   entropy_poss=0; /*to analyse a single gene -- input entropy, density etc*/

   reorderRBN=1;
   border=0;  /*for fixed border 1,2,3d to try to absorb gliders*/
   b_value=0; 
   glider_rule_order=-1; /*start random, 1=sequential order*/

  
   i2d=b_i2d; /*b_i2d set in main, and also reset in duplicate_net*/
   j2d=b_j2d;
   
   diff_plot=0;

   if (oned==1) d_mode=1;
   else if (twod==2) d_mode=2;
   else if (threed) d_mode=4;

   /*set array for default sequential updating*/
   for (poss=0;poss<=L;poss++) seq_order[poss]=poss;
   if (fan_angle_fact==0) fan_angle_fact=1; 
   codetypeonly='a';
   seq_update=0;
   level_limit=Maxu;
   neutral_order=0;
   if (oned==1) scrolling=1;
   else scrolling=0;
   
   show_maj=-1;
   wires_to_move=1;
   /*if (oned){
      if (showbits_1d_as_2d==1) shownumbers=3;
   }*/
   /*sep=2->1 pix black div between cells, sep=1-> no div*/
   if (scale>vgax(3)) sep=2;
   else sep=1;
   /*run forwards only and compute nhood, for large 2d arrays*/
   if (loc_twod_fonly){
      if (twod) sprintf(textb[0],
	"2d local wiring (%dx%d), forwards only, cont-ret:",i2d,j2d);
      else if (threed) sprintf(textb[0],
         "3d local wiring  (%dx%dx%d), forwards only, cont-ret:",i3d,j3d,h3d);
      draw_prompt_box(1);
      outtext(textb[0]);
      input_string(1,0);
      erase_prompt_box(1);
      direction='f';
      limitcheck=0;
      return;
   }
   if (tot_only==1){
         is[0]='s';
         forward_only=show_ss_matrixF=1;
         direction='f';
         limitcheck=0;
         return;
    }

  start:
   acceptall=accept_from=forward_only=0;

   moveto(memory_box(0,NULL)+vgax(3),vgay(3));
   setcolor(lightred);
   outtext("basin parameters");
   setcolor(white);
   
   if (basinfield){
      sprintf(textb[0],
	  "accept all basin defaults-d");  
      sprintf(textb[1],
	  "restore defaults: all-a, layout only-L");       
   }
   else{
      sprintf(textb[0],
	  "accept all basin defaults-d, space-time pattern only-s");
      sprintf(textb[1],
	  "restore defaults: all-a, layout only-L");
   }
   
   sprintf(textb[2],"revise from:  ");

   sprintf(textb[3],
	  "start/misc-ret layout-l display/boundary-p ");
   /*if (basinfield) sprintf(textb[4],
	  "pause/data-t PScript-P graphs-g mutation-m:");
   else sprintf(textb[4],
   "pause/data-t PScript-P graph-g mutation-m:");*/
   
   /*now for basinfield or single bason /sbbtree*/
   sprintf(textb[4],"pause/data-t PScript-P graph-g mutation-m:");
   
   xbox=draw_prompt_box(4);
   outtext(textb[0]);
   moveto(xbox,gety+CHeight);
   outtext(textb[1]);
   moveto(xbox,gety+CHeight);
   setcolor(lightred);   
   outtext(textb[2]);
   setcolor(white);
   tempx=getx;
   moveto(tempx,gety);
   outtext(textb[3]);
   moveto(tempx,gety+CHeight);
   outtext(textb[4]);
   input_string(1,0);
   erase_prompt_box(4);
   
   if (is[0]=='q'){
#        if __UNIX__  /*erase "output parameters" box*/      
            leftboxx=(signed int)((float)Maxx)/3;
            rightboxx=((signed int)((float)Maxx)/2)-3;
            boxy=2;
            /*erase box*/
            setviewport(leftboxx,boxy,rightboxx,boxy+CHeight+vgay(6),1);
            clearviewport();
            setviewport(0, 0, Maxx, Maxy, 0);
#        elif __WATCOM__
            memory_box(1,NULL);
#        endif
         return;   
   } 
   else if (is[0]=='s' && !basinfield){
         forward_only=show_ss_matrixF=1;
         direction='f';
         limitcheck=0;
	 if (iso_rule_allowed==1 && isotropic_set==1){
           signed int tablemax;
            tablemax= (signed int)pow(value_range,(double)nhood)-1;
	    /*reset iso-rule for current rule*/
	    fprintf(stderr,"\nsetting iso-rule in select_pattern_scrolling");
            isotropic_rule(0,carule[0],nhood,0,tablemax,tablemax,-2);
         }
         return;
   }
   
   else if (is[0]=='d') acceptall=1;
   else if (is[0]=='l') accept_from='l';
   else if (is[0]=='p') accept_from='p';
   else if (is[0]=='t') accept_from='t';
   else if (is[0]=='P') accept_from='P';/*new category Dec09*/
   /*else if (basinfield && is[0]=='g') accept_from='g'; new category Dec09, then Jan2022* (was 'j')*/
   else if (is[0]=='g') accept_from='g'; //Dec09 jump-graph, Jan2022 ibaf-graph, March2025 isstr-graph 
   else if (is[0]=='m') accept_from='m';

   att_hist=att_trans=bin_trans=0;
   if (is[0]=='a' || is[0]=='A'|| is[0]=='L'){
      mutant_layout=0;
      layout_notset=1;
      successive_basins=0;
      show_one_att_state=0;
      orient_angle=0; 
      fan_angle_fact=1; 
      if (is[0]=='a'){
         NULLboundaries=0;
	 entropy_poss=0;
         if (scale>=6){ 
            node_tight=0; /*allows divs in bit/value pattern*/
            node_dots=1; /*put a dot on zero cell -- only useful for 2d nodes*/
         }          
         else{
            node_tight=1; /*no divs*/
            node_dots=0;  /*no dots*/
         }
         graph_layout=0;
         basin_postScript=0;
         stagger_even_rows=0;
	 start_edge_color=lightred; 
	 show_maj=-1;        
         jump_graph=0;
         reorderRBN=1;
         filedata=filestates=pdata=printstates=0; 	 
	 show_ss_matrix=show_ss_matrixF=0;
	 ss_m_att_only=0;
	 msize=vgax(200);
	 matrixcolor=10;
	 screensavedemo=0;
	 gd_z_graph=0;
	 stp=0;
	 if (oned==1) scrolling=1;
	 pre_fansize_freq_hist=0;
         diff_plot=0;
	 /*reset nominal array for in-degree histogram*/
	 if (maxinhist>0){
	    free(pre_fan_freq);
	    maxinhist=0;
	    sprintf(textb[0],"pre_fan_freq");
	    if ((pre_fan_freq=
	       (unsigned long *)calloc(1,sizeof(unsigned long)))
					==NULL) outof_memory(textb[0]);
	 }
         just_G=shownumbers=0;
	 hilight_learn=showbits_1d_as_2d=0;
	 labelsizefactor=0;
	 dontcompress=0;
	 if (regular2d) dontcompress=1;//regular2d change default to uncompressed
	 dontcopytrees=0;
	 fieldpause=0;
	 datapause=0;
	 /*mutate='b';*/
         mutate_wiring=0; /* 1=cumulative=1 2=restore original before*/
         mutate_wiring_and_rule=0; /* ... to mutate wiring as well as rule*/ 
         wires_to_move=1;	 
	 mutantdontpause=0;
         pause_fact=1.0;
      }
      goto start;
   }
   moveto(memory_box(0,NULL)+vgax(3),vgay(3));
   setcolor(lightred);
   outtext("accept defaults-d");
   setcolor(white);

  startmatrix:
   /*state-space matrix plotted simult. with basins/space-time pattern*/
   if (matrixcolor==0) matrixcolor=10;
   if (acceptall==0  && accept_from==0){
      if (show_ss_matrix==1) sprintf(textb[0],
        "state-space matrix (now ON): off-x, all states-m, attractor only-a");
     else sprintf(textb[0],
        "state-space matrix (now OFF): all states-m, attractor only-a");
      sprintf(textb[1],
        "show and change: matrix size-s, start color-c:");
      draw_prompt_box(2);
      setcolor(lightred);
      outtext("start/misc: ");
      setcolor(white);
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);
      outtext(textb[1]);
      input_string(1,0);
      erase_prompt_box(2);
      if (is[0]=='q')  goto start;
      else if (is[0]=='d') acceptall=1;
      else if (is[0]=='x'){
	 show_ss_matrix=0;
	 goto startmatrix;
      }	
      else if (is[0]=='m' || is[0]=='a'
	    || is[0]=='s' || is[0]=='c') show_ss_matrix=1;
      
      if (is[0]=='a') ss_m_att_only=1;
      else if (is[0]=='m') ss_m_att_only=0;
      else if (is[0]=='s'){
        signed int p_msize;
         p_msize=(signed int) ceil(( 100*(float)msize/(Maxx/2) ));
         /*fprintf(stderr,"msize=%d\n",msize);*/
	 sprintf(textb[0],
	  "change matrix size: %% of 1/2 screen (def %d%%):",p_msize);
	 xbox=draw_prompt_box(1);
	 outtext(textb[0]);
	 input_string(3,0);
	 erase_prompt_box(1);
	 if (is[0]=='q') goto start;
	 else if (is[0]=='d') acceptall=1;
	 else if (is[0]!=13 && atoi(is)>0){
             p_msize=atoi(is);
             msize=(signed int) ceil(( (float) (p_msize*(Maxx/2)) /100));
         }
      }
      else if (is[0]=='c'){
	 sprintf(textb[0],
	  "change start color (now %d): enter 1-15:",matrixcolor);
	 xbox=draw_prompt_box(1);
	 outtext(textb[0]);
	 input_string(2 ,0);
	 erase_prompt_box(1);
	 if (is[0]=='q') goto start;
	 else if (is[0]=='d') acceptall=1;
	 else if (is[0]!=13 && atoi(is)>=1 && atoi(is)<16)
						matrixcolor=atoi(is);
	 goto startmatrix;
      }
   }
   /*show in-degree frequency histogram*/
   if (acceptall==0 && accept_from==0 && screensavedemo==0){
      sprintf(textb[0],"in-degree frequency histogram-h:");
      draw_prompt_box(1);
      outtext(textb[0]);
      input_string(1,0);
      erase_prompt_box(1);
      if (is[0]=='q') goto start;
      else if (is[0]=='d') acceptall=1;
      else if (is[0]=='h'){
	 if (maxinhist==0) maxinhist=200;
	 draw_prompt_box(1);
	 sprintf(textb[0],
	  "select cut-off in-degree bin (50-5000, default %d):",maxinhist);
	 outtext(textb[0]);
	 input_string(5,0);
	 if (is[0]=='q') goto start;
	 if (is[0]==13 || is[0]=='d');
	 else if (atoi(is)>=50 && atoi(is)<=5000) maxinhist=atoi(is);
	 pre_fansize_freq_hist=1;
	 /*reset array for in-degree histogram*/
	 free(pre_fan_freq);
	 if ((pre_fan_freq=
	       (unsigned long *)calloc(maxinhist+1,sizeof(unsigned long)))
				   ==NULL) outof_memory("pre_fan_freq");
	 if (is[0]=='d') acceptall=1;
      }
      else{
	 pre_fansize_freq_hist=0;
	 /*reset nominal array for in-degree histogram*/
	 if (maxinhist>0){
	    free(pre_fan_freq);
	    maxinhist=0;
	    if ((pre_fan_freq=
	       (unsigned long *)calloc(1,sizeof(unsigned long)))
				   ==NULL) outof_memory("pre_fan_freq");
	 }
      }
   }

   /***** show/count states with majority of given a value -- (for the majority rule) ******/
   if (acceptall==0 && accept_from==0 && screensavedemo==0){
            show_maj=-1;
            sprintf(textb[0],
                   "show/count states with majority, enter (0-%d):",value_range-1);
	    draw_prompt_box(1);
	    outtext(textb[0]);
	    input_string(1,0);
	    erase_prompt_box(1);
	    if (is[0]=='q')  goto start;
	    else if (is[0]=='d') acceptall=1;
            else if (is[0]!=13 && atoi(is)>=0 && atoi(is)<value_range) show_maj=atoi(is);
   }

   
   /*continuous demo of basins (random rules) ramdom positions*/
   if (acceptall==0 && accept_from==0 && !pre_fansize_freq_hist){
      screensavedemo=0;
      if (basinfield==0 && rangeL==0){
	 sprintf(textb[0],"screensave demo -s:");
	 draw_prompt_box(1);
	 outtext(textb[0]);
	 input_string(1,0);
	 if (is[0]=='q')  goto start;
	 else if (is[0]=='d') acceptall=1;
	 else if (is[0]=='s'){ 
            screensavedemo=1;
            stp=0;
         }
      }
   }

   /*draw g-of-E density<->Z/Lambda graph, and Z - Lambda graph*/
  startgraph:
   gd_z_graph=0;
   pause_show_code=0;
   /*this whole section need updating for v>2*/
   if (!rulemix && acceptall==0 && accept_from==0 &&
		 screensavedemo==0 && pre_fansize_freq_hist==0){
      char do_sample=0;

      lambda_z_graph=totalgraphrules=0;
      if (value_range==2){
         sprintf(textb[0],
	   "G-density plot: Zpara-1, +Lambda ratio-2, size range-3");
         sprintf(textb[1],
	   "parameter plot: Zpara-Lda ratio (C-P data), Zleft-Zright graphs  -L:");
         xbox=draw_prompt_box(2);
         outtext(textb[0]);
         moveto(xbox,gety+CHeight);
         outtext(textb[1]);
      }
      else{ 
         sprintf(textb[0], "G-density plot:  size range-3:");
         xbox=draw_prompt_box(1);
         outtext(textb[0]);
      }
      
      input_string(1,0);
      erase_prompt_box(2);
      if (is[0]=='q')  goto start;
      else if (is[0]=='d') acceptall=1;
      else if (atoi(is)>0 && atoi(is)<=3){
	 gd_z_graph=atoi(is);
         if (gd_z_graph==3){ /*range of sizes*/
           char *rangeseed;
             rangebytesL=bytesL;
             startL=lineL;
             xbox=draw_prompt_box(2);
             outtext("G-density - size range:");        
             moveto(xbox,gety+CHeight);
	     sprintf(textb[0],"start size (def=%d):", lineL);
	     outtext(textb[0]);
	     input_string(2,0);
             if (is[0]=='q') goto startgraph;
	     if (atol(is)>0 && atol(is)<=30){
                startL=atol(is);
             }
             outtext("  end size (max=31):");
	     input_string(2,0);
             if (is[0]=='q') goto startgraph;
	     if (atol(is)>startL && atol(is)<=31){
                signed int z;
                endL=atol(is);
                totalgraphrules=endL-startL+1;
                rangeL=0;
                if (startL!=lineL){
		   if (basinfield==0){
                      /*remember seed state*/
                      if ((rangeseed=(char*)calloc(rangebytesL,sizeof(char)))
				      ==NULL) outof_memory("rangeseed");
                      memmove(rangeseed,bitseed,rangebytesL);
                   }
                   change_net_size(startL);
                   if (basinfield==0){
                      if (bytesL<rangebytesL) rangebytesL=bytesL;
                      for (z=L;z>=0;z--){ 
			 if (value_range==2){
                            set_bit(bitseed,z,get_bit(rangeseed,z));
			 }
                         else set_value(bitseed,z,get_value(rangeseed,z));
		      }
                      free(rangeseed);
                   }
                }
             }
	     else gd_z_graph=0;
             erase_prompt_box(2);
         }
	 else if ( (value_range>2 && nhood>1) 
                || ( value_range==2 && !(nhood<=3 || totalistic)) ){
	    do_sample=1;
	    draw_prompt_box(1);
	    sprintf(textb[0],
	       "G-density plot, number of rules (def 1250):");
	    outtext(textb[0]);
	    input_string(6,0);
	    if (is[0]==13) totalgraphrules=1250;
            else if (is[0]=='q') goto startgraph;
	    else if (atol(is)>1) totalgraphrules=atol(is);
	    else gd_z_graph=0;
	 }
	 else{
          signed int tablemax,codedec,ruledec;
	    lowlimZ=.2;
	    highlimZ=1;
	    draw_prompt_box(1);
	    sprintf(textb[0],"set min Z (def 0.2):");
	    outtext(textb[0]);
	    input_string(4,0);
	    if (is[0]=='q') goto startgraph;
	    else if ((isdigit(is[0]) || is[0]=='.') &&
		   atof(is)>=0 && atof(is)<1) lowlimZ=(float)atof(is);

	    sprintf(textb[0]," max Z (def 1):");
	    outtext(textb[0]);
	    input_string(4,0);
	    if (is[0]=='q') goto startgraph;
	    else if ((isdigit(is[0]) || is[0]=='.') &&
		   atof(is)>=0 && atof(is)<=1 && atof(is)>lowlimZ)
					highlimZ=(float)atof(is);
            /*make sure start rule has Z higer than lowlimZ*/ 
            tablemax= (signed int)pow(value_range,(double)nhood)-1;
            while(1){
	       if (totalistic && do_sample==0){
                  /*convert code to rule*/
                  if (totalistic==1) code2rule(carule[0],cacode[0],nhood);
                  else if (totalistic==2) v_code2rule(carule[0],v_code[0],
						      nhood,1);
                  if (value_range==2) z_parameter_all(nhood,0,carule[0]);
                  else z_parameter_all_mvalue(nhood,0,carule[0]); 
		  if (zparam[0]<lowlimZ){                    
                     codedec=dec_equiv(cacode[0],nhood);
	             /*fprintf(stderr,"codedec=%d Z=%f\n",codedec,zparam[0]);*/
		     codedec-=1;
                     if (value_range==2) 
                           dec_to_bit_line(cacode[0],codedec,nhood+1);
                     else dec_to_value_line(cacode[0],codedec,nhood+1);
                  }
                  else{
		     /*codedec=dec_equiv(cacode[0],nhood);
                     fprintf(stderr,"codedec=%d Z=%f\n",codedec,zparam[0]);*/
                    break;
                  }
               }
               /*else if (nhood<=3){*/
               else if (do_sample==0){
                  if (value_range==2) z_parameter_all(nhood,0,carule[0]);
                  else z_parameter_all_mvalue(nhood,0,carule[0]);
                  if (zparam[0]<lowlimZ){
                     ruledec=dec_equiv(carule[0],tablemax);
                     /*fprintf(stderr,"ruledec=%d Z=%f\n",ruledec,zparam[0]);*/
                     ruledec-=1;
                     if (value_range==2) 
                          dec_to_bit_line(carule[0],ruledec,tablemax+1);
                     else dec_to_value_line(carule[0],ruledec,tablemax+1);
                  }
                  else{
		     /*ruledec=dec_equiv(carule[0],tablemax);
                     fprintf(stderr,"ruledec=%d Z=%f\n",ruledec,zparam[0]);*/
                    break;
                  }
               }
            }    
	 }
      }
      else if (is[0]=='L') {
        char countdown=0;

         draw_prompt_box(1);
         sprintf(textb[0],
	   "plot: Zleft-Zright -1, Zpara - Lda ratio and C-P data-(def):");
	 outtext(textb[0]);
	 input_string(1,0);
	 if (is[0]=='q'){
	    erase_prompt_box(1);
	    goto startgraph;
	 }
         if (is[0]=='q') goto startgraph;
	 if (is[0]=='1') lambda_z_graph=2;        
	 else lambda_z_graph=1;
	 codetypeonly='c';
	 pause_show_code=0;
	 if (nhood<=3 || (totalistic==1 && value_range==2)){
	    totalgraphrules=1;
	    if (totalistic){
	       xbox=draw_prompt_box(2);
	       sprintf(textb[0],
		  "show only equivs-e all-a (def clusters):");
	       outtext(textb[0]);
	       input_string(1,0);
	       if (is[0]=='q'){
		  erase_prompt_box(2);
		  goto startgraph;
	       }
	       else if (is[0]=='e') codetypeonly='e';
	       else if (is[0]=='a') codetypeonly='a';
	       moveto(xbox,gety+CHeight);
	       sprintf(textb[0],
		  "pause to show codes-p:");
	       outtext(textb[0]);
	       input_string(1,0);
	       erase_prompt_box(2);
	       if (is[0]=='q') goto startgraph;
	       if (is[0]=='p') pause_show_code='1';
	    }
	 }
	 else {
	    dontbias=0;
	    xbox=draw_prompt_box(2);
            if (lambda_z_graph==1) sprintf(textb[1],"lambda-Z ");
            else if (lambda_z_graph==2) sprintf(textb[1],
	                                        "Zleft-Zright ");

            /*if (lambda_z_graph==1) sprintf(textb[0],
	              "plot, number of rules (def 2200):");
            else if (lambda_z_graph==2){  /*lambda_z_g
	       if (nhood<=5) sprintf(textb[0],
	          "plot: countdown-C sample size (def 2200):");
               else sprintf(textb[0],
	          "plot: sample size (def 2200):");
	    }*/
            if (nhood<=5 || totalistic==1) sprintf(textb[0],
	          "plot: countdown-C, sample size (def 2200):");
            else sprintf(textb[0],
	          "plot: sample size (def 2200):");


	    outtext(textb[1]);
            outtext(textb[0]);
	    input_string(8,0);
            

            if (is[0]=='C' && (nhood<=5 || totalistic==1)){
	      //countdown from set rule or code -- could be for all rule-space
	       countdown=1;
	    }
	    else if (is[0]==13) totalgraphrules=2200;
            else if (is[0]=='q') goto startgraph;
	    else if (atol(is)>1) totalgraphrules=atol(is);
                       
	    if (countdown==0){
               moveto(xbox,gety+CHeight);
	       sprintf(textb[0],
	            "random rule sample will have lambda bias, no-n:");
	       outtext(textb[0]);
            }

	    input_string(1,0);
            erase_prompt_box(2);
	    if (is[0]=='n') dontbias=1;
            if (is[0]=='q') goto startgraph;
	 }
         

	 if (totalgraphrules>0 || countdown==1){           
	    gofE_z_graph();  /*draw and title the graph outline*/
	    if (totalistic==1 && value_range==2){ /*for tcode -- only countdown*/
	       mutate=5; /*decriment code no -- countdown*/
	       allocate_code_mem();
	       sprintf(textb[0],"cacode[0]");
		if ((tempcode1=(char *)calloc
		    ((signed int)ceil((double)(nhood+1)/8),
			  sizeof(char)))==NULL)outof_memory(textb[0]);
	       memmove(tempcode1,cacode[0],
			 (signed int)ceil((double)(nhood+1)/8));
	    }
	    else if (nhood<=3 || countdown==1) mutate=3;   /*decriment rule no*/
	    else mutate=2;
	    memory_box(1,NULL);
            set_z_high=0;
	    draw_lambda_z_graph(dontbias);/*plot points*/
	    
	    if (totalistic==1 && value_range==2){
	       free(codetickoff);
	       free(tempcode);
	       memmove(cacode[0],tempcode1,
			 (signed int)ceil((double)(nhood+1)/8));
	       free(tempcode1);
	    }
	    lambda_z_graph=0;
	    mutate='b'; /*restore default mutation*/
	    moveto(memory_box(0,NULL)+vgax(3),vgay(3));
	    setcolor(lightred);
	    outtext("accept defaults-d");
	    setcolor(white);
	    goto startgraph;
	 }
      }
   }
  start40:
   /*show/dont show space-time pattern*/
   /* default stp=0 in all cases */
   if (acceptall==0 && accept_from==0){
              if (stp==1) sprintf(textb[1],"(now ON)"); 
              else sprintf(textb[1],"(now OFF)");
              sprintf(textb[0],"backwards space-time patterns %s tog-s:",textb[1]);
	      draw_prompt_box(1);
	      outtext(textb[0]);
	      input_string(1,0);
	      erase_prompt_box(1);
	      if (is[0]=='q')  goto start;
	      if (is[0]=='d') acceptall=1;
	      else if (is[0]=='s') stp=abs(stp-1);
              if (acceptall==0 && stp==1){
		 sprintf(textb[0],"sweep backwards space-time pattern-s, scroll-def:");
		 draw_prompt_box(1);
		 outtext(textb[0]);
		 input_string(1,0);
		 erase_prompt_box(1);
		 if (is[0]=='q')  goto start40;
		 else if (is[0]=='d') acceptall=1;
		 else if (is[0]=='s') scrolling=0;
              }
   }

   /*set NULLboudary conditions, for 1d only (for basins), also option for forwards only*/
   /*if (acceptall==0 && accept_from==0 && oned){ 
          if (NULLboundaries==1) sprintf(textb[0],
	         "NULL  boundaries, set PERIODIC-P:");
          else  sprintf(textb[0],
                 "PERIODIC boundaries, set NULL-N:");
	  draw_prompt_box(1); 
	  outtext(textb[0]);
          input_string(1,0);
          if (is[0]=='N'){
             NULLboundaries=1;
             dontcompress=1;
          }
          else if (is[0]=='P'){
             NULLboundaries=0;
             dontcompress=0;
          }
	  erase_prompt_box(1);
	  if (is[0]=='q')  goto start40;
	  else if (is[0]=='d') acceptall=1;
	  //else if (is[0]=='s') scrolling=0;
   }*/
   if (acceptall==0 && accept_from==0){ /*to slow down basins*/
          if (slowfactor==0) slowfactor=33000;
          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;
          }
	  erase_prompt_box(1);
	  if (is[0]=='q')  goto start40;
	  else if (is[0]=='d') acceptall=1;
	  //else if (is[0]=='s') scrolling=0;
   }

   temp=(double)CHeight*1.2/(double)scale;
   textscale=ceil(temp);
   if (textscale==0) textscale=1;
   if (accept_from==0) accept_from='l';
}

/************** select scale and position of basin, 13 May 93 ************/
void setup_plot(void){

 float r,oldpstartrad;
 signed int z,xbox;
 char acceptall_was_set=0;
 float pstartrad_min;

   /*mutant_layout=0;*/ /*now set to 0 in main*/
   if (twod) rangeL=0;

   /*get image below layout preview box, no outline or background*/
   if (acceptall==0  && accept_from=='l') 
              draw_box(3,0,0,Maxx/2-vgax(4),Maxy/2,0,-1);
   setcolor(white);

   if (layout_notset==1){
      set_layout_defaults();
      layout_notset=0;
   }
   else{
      xspacing=startxspacing;
      yspacing=startyspacing;
   }
   /*draw layout preview in 1/4 screen*/
   if (acceptall==0 && accept_from=='l'){
      draw_layout_preview();
      moveto(memory_box(0,NULL)+vgax(3),vgay(3));
      setcolor(lightred);
      outtext("accept defaults-d");
      setcolor(white);
   }

  start10:
   oldpstartrad=pstartrad;
   pstartrad_min=220.0/Maxx;
   if (acceptall==0 && accept_from=='l'){    
     if (basinfield) sprintf(textb[0],
	 "reset defaults: all-r, transients (%.1f,%d)-t",
                                           trans_shrink_fact,lastlevel);
      else sprintf(textb[0],
	 "reset defaults: all-r, transients (%.1f,%d)-t, mutants-M",
                                           trans_shrink_fact,lastlevel);
      sprintf(textb[1],
       "att rad, %% of 1/2 screen x-axis (min %.2f def %.3g):",
                                       pstartrad_min,pstartrad);
      xbox=draw_prompt_box(2);
      setcolor(lightred);
      outtext("layout: ");
      setcolor(white);
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);
      outtext(textb[1]);
      input_string(4,0);
      //erase_prompt_box(2);
      if (is[0]!=13 && atof(is)>=pstartrad_min) pstartrad=atof(is);
      if (is[0]=='q'){
	 erase_prompt_box(2);
	 /*restore image below 1/4 screen preview*/
         sprintf(textb[9],"%s","boximage[3]");
	 putimage(0,0,boximage[3],COPY_PUT,textb[9]);
	 freeimage(boximage[3]);
	 return;
      }
      if (is[0]=='t'){
	 /*May 2016: reset default trans-shrink and max levels*/
         xbox=draw_prompt_box(2);
         sprintf(textb[0],
         "transient defaults: reset original (F=1.0, L=90)-r");
         outtext(textb[0]);
         moveto(xbox,gety+CHeight);
         sprintf(textb[0],
         "amend: F (now %.2f):",trans_shrink_fact);
         outtext(textb[0]);
         input_string(4,0);         
         if (is[0]!=13 && atof(is)>=0.1) trans_shrink_fact=atof(is);
         else if (is[0]=='d') acceptall=acceptall_was_set=1;
         sprintf(textb[0],
         " L (now %d):",lastlevel);
         outtext(textb[0]);
         input_string(4,0);         
         if (is[0]!=13 && atof(is)>=1) lastlevel=atoi(is);
         else if (is[0]=='d') acceptall=acceptall_was_set=1;
         /*set up array of levels*/
         if (trans_shrink_fact<=0) trans_shrink_fact=1;
         free(rad);
         if ((rad=(float*)calloc(lastlevel+1,sizeof(float)))
				  ==NULL) outof_memory("rad");
         for (z=1;z<=lastlevel;z++){    /*lastindex=lastlevel-1*/
            if (z==1) r=startrad;
            else r += (startrad/trans_shrink_fact)/log(pow(z,2));
            rad[z-1]=r;
         }
	   
         erase_prompt_box(2); 
	 draw_layout_preview();
	 moveto(memory_box(0,NULL)+vgax(3),vgay(3));
	 setcolor(lightred);
	 outtext("accept defaults-d");
	 setcolor(white);
	 goto start10;
      }

      if (is[0]=='r'){
	 layout_notset=1;
	 set_layout_defaults();
	 layout_notset=0;
	 draw_layout_preview();
	 moveto(memory_box(0,NULL)+vgax(3),vgay(3));
	 setcolor(lightred);
	 outtext("accept defaults-d");
	 setcolor(white);
	 goto start10;
      }
      else if (is[0]=='d') acceptall=acceptall_was_set=1;
      else if (is[0]=='M' && basinfield==0){
         mutant_layout=1;
         set_layout_defaults();
         draw_layout_preview();
         moveto(memory_box(0,NULL)+vgax(3),vgay(3));
	 setcolor(lightred);
	 outtext("accept defaults-d");
	 setcolor(white);
	 goto start10;
      }
      
   }

   startrad=((float)Maxx/2)*(pstartrad/100);
   if (startrad<1.0) startrad=1.0;

   /*define rad of empty circle for screensavedemo*/
   demorad=startrad*5;
   
   /*if (direction=='f') demorad=startrad*5*lineL/11
                                          *((float)value_range/2);
   else demorad=startrad*5;
   //readjust for hires Dell 3200x1800 (def ddlab 2112x1584)
   demorad*=(925.0/(Maxx+1));*/

   /*set up array of levels*/
   if (trans_shrink_fact<=0) trans_shrink_fact=1;
   for (z=1;z<=lastlevel;z++){    /*lastindex=lastlevel-1*/
      if (z==1) r=startrad;
      else r += (startrad/trans_shrink_fact)/log(pow(z,2));
      rad[z-1]=r;
   }

  start20:
   /*set centre of first basin*/
   if (acceptall==0 && accept_from=='l'){
      xbox=draw_prompt_box(3);
      sprintf(textb[0],"start position, %% offset from screen center");
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);
      sprintf(textb[0],"x (def %.3g):",xoffset);
      outtext(textb[0]);
      input_string(4,0);
      if (is[0]=='q'){
	 erase_prompt_box(3);
	 goto start10;
      }
      if (is[0]=='d'){
	 acceptall=acceptall_was_set=1;
	 erase_prompt_box(3);
      }
      else if (is[0]!=13) xoffset=atof(is);

      if (acceptall==0){
	 moveto(getx+10,gety);
	 sprintf(textb[0],"y (def %.3g):",yoffset);
	 outtext(textb[0]);
	 input_string(4,0);
	 if (is[0]=='q'){
	    erase_prompt_box(3);
	    goto start20;
	 }
	 else if (is[0]=='d'){
	    acceptall=acceptall_was_set=1;
	    erase_prompt_box(3);
	 }
	 else if (is[0]!=13) yoffset=atof(is);
         if (acceptall==0 && !rangeL && basinfield){
	    successive_basins=0;
	    moveto(xbox,gety+CHeight);
	    outtext(
	       "show field as successive single basins-s, and pause-p:");
	    input_string(1,0);
	    if (is[0]=='q'){
	       erase_prompt_box(3);
	       goto start20;
	    }
	    else if (is[0]=='d') acceptall=acceptall_was_set=1;
	    else if (is[0]=='s'){
	       successive_basins=1;
	       datapause=0;
	    }
	    else if (is[0]=='p'){
	       successive_basins=1;
	       datapause=1;
	    }
	 }
      }
      erase_prompt_box(3);
   }
   fox=ox=(signed int) (((float)Maxx/2)*(1+xoffset/100 ));
   foy=oy=(signed int) (((float)Maxy/2)*(1-yoffset/100 ));

  start30:
   /*change default spacing in proportion to rad*/
   if (mutant_layout==0){
      xpspacing*=pstartrad/oldpstartrad;
      ypspacing*=pstartrad/oldpstartrad;
   }
   /*specify spacing between basins*/
   if (successive_basins==0 && (basinfield || rangeL 
                  || gd_z_graph || mutant_layout)){
      if (acceptall==0 && accept_from=='l'){
	 xbox=draw_prompt_box(3);
	 sprintf(textb[0],"basin spacing, %% of 1/2 screen");
	 outtext(textb[0]);
	 moveto(xbox,gety+CHeight);
	 sprintf(textb[0],"x spacing (def %.3g):",xpspacing);
	 outtext(textb[0]);
	 input_string(3,0);
	 if (is[0]=='q'){
	    erase_prompt_box(2);
	    goto start20;
	 }
	 else if (is[0]=='d'){
	    acceptall=acceptall_was_set=1;
	    erase_prompt_box(3);
	 }
	 else if (is[0]!=13) xpspacing=atof(is);
	 if (acceptall==0){
	    moveto(getx+10,gety);
	    sprintf(textb[0],"y spacing (def %.3g):",ypspacing);
	    outtext(textb[0]);
	    input_string(3,0);
	    if (is[0]=='q'){
	       erase_prompt_box(3);
	       goto start30;
	    }
	    if (is[0]=='d'){
	       acceptall=acceptall_was_set=1;
	       erase_prompt_box(2);
	    }
	    else if (is[0]!=13) ypspacing=atof(is);
	    /*erase_prompt_box(2);*/
	 }
                  
	 startxspacing=xspacing=
		  (signed int) (((float)Maxx/2)*(xpspacing/100 ));
	 startyspacing=yspacing=
		  (signed int) (((float)Maxy/2)*(ypspacing/100 ));

         rightborder=(xpspacing)/100;
	 /*min right border, then new row*/
	 sprintf(textb[0],
	    "right border %% of x spacing (def %.1f%%):",
				       rightborder*100);
	 moveto(xbox,gety+CHeight);
	 outtext(textb[0]);
	 input_string(4,0);
	 if (is[0]=='q') goto start30;
	 else if (is[0]=='d'){
	       acceptall=acceptall_was_set=1;
	       erase_prompt_box(3);
	 }
	 else if (is[0]!=13) rightborder=(float)atof(is)/100;
         
         if (stagger_even_rows==0) outtext(" tog stagger rows (now off)-s:");
         else if (stagger_even_rows==1) outtext(" tog stagger rows (now on)-s:");
         input_string(1,0);
         if (is[0]=='q') goto start30;
	 else if (is[0]=='d'){
	       acceptall=acceptall_was_set=1;
	       erase_prompt_box(3);
	 }
         else if (is[0]=='s')
             stagger_even_rows=abs(stagger_even_rows-1);

	 erase_prompt_box(3);
      }

     start40:
      /*select spacing increase*/
      if (rangeL){
	 if (acceptall==0 && accept_from=='l'){
	    xbox=draw_prompt_box(2);
	    sprintf(textb[0],
	      "%% increace spacing for successive network size,");
	    outtext(textb[0]);
	    moveto(xbox,gety+CHeight);
	    sprintf(textb[0],"x increace (def %.3g%%):",xpspacefact);
	    outtext(textb[0]);
	    input_string(3,0);
	    if (is[0]=='q'){
	       erase_prompt_box(2);
	       goto start30;
	    }
	    else if (is[0]=='d'){
	       acceptall=acceptall_was_set=1;
	       erase_prompt_box(2);
	    }
	    else if (is[0]!=13) xpspacefact=atof(is);
	    if (acceptall==0){
	       moveto(getx+10,gety);
	       sprintf(textb[0],"y increase (def %.3g%%):",ypspacefact);
	       outtext(textb[0]);
	       input_string(3,0);
	       if (is[0]=='q'){
		  erase_prompt_box(2);
		  goto start40;
	       }
	       else if (is[0]=='d'){
		  acceptall=acceptall_was_set=1;
		  erase_prompt_box(2);
	       }
	       else if (is[0]!=13) ypspacefact=atof(is);
	       erase_prompt_box(2);
	    }
	 }
	 xspacefact=1+(xpspacefact/100);
	 yspacefact=1+(ypspacefact/100);
      }
   }

   if (acceptall==0 && accept_from=='l'){
      /*draw layout preview in 1/4 screen*/
      draw_layout_preview();
      moveto(memory_box(0,NULL)+vgax(3),vgay(3));
      setcolor(lightred);
      outtext("accept defaults-d");
      setcolor(white);

      sprintf(textb[0],
       "revise layout-q, accept-ret:");
      draw_prompt_box(1);
      outtext(textb[0]);
      input_string(1,0);

      if (is[0]=='q'){
	 erase_prompt_box(1);
	 goto start10;
      }
      if (is[0]=='d') acceptall=acceptall_was_set=1;
   }

   if (acceptall_was_set==1 || (acceptall==0 && accept_from=='l')){
      /*restore image below 1/4 screen preview*/
      sprintf(textb[9],"%s","boximage[3]");
      putimage(0,0,boximage[3],COPY_PUT,textb[9]);
      freeimage(boximage[3]);
   }
   if (accept_from=='l') accept_from='p';
}

/********************* amemd basin layout ********************/
void amend_layout(void){
  unsigned int xbox;
  char newpos_was_set=0;

   /*set centre of next basin*/
  start20:
   erase_prompt_box(2);
   xbox=draw_prompt_box(1);
   sprintf(textb[0],"stop pause-s, amend angles-a, next pos-p, just spacing-ret:");
   outtext(textb[0]);
   input_string(1,0);
   if (is[0]=='q') return;
   if (is[0]=='s'){ 
      datapause=0;
      return;
   }
   if (is[0]=='a'){
      sprintf(textb[0],"change basin orientation anti-clockwise (now %d), enter angle:",
	                              (signed int)(orient_angle/deg));
      xbox=draw_prompt_box(2);
      outtext(textb[0]);
      input_string(4,0);
      if (is[0]=='q') goto start20;
      else if (is[0]=='-' || (is[0]!=13 && atoi(is)>=0))
             orient_angle=atof(is)*deg;            
      moveto(xbox,gety+CHeight); 
      if (fan_angle_fact==0) fan_angle_fact=1; 
   }
   if (is[0]=='p'){
      start15:
      xbox=draw_prompt_box(2);
      sprintf(textb[0],
    "(start=%.3g,%.3g) amend next pos, %% offset from screen center",
				     xoffset,yoffset);
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);
      sprintf(textb[0],"x (def %.3g):",
			(((float)(ox+xspacing)/(Maxx/2)-1)*100));
      outtext(textb[0]);
      input_string(3,0);
      if (is[0]=='q'){
	 erase_prompt_box(2);
	 goto start20;
      }
      else if (is[0]!=13) xoffset=atof(is);
      else xoffset=(((float)(ox+xspacing)/(Maxx/2)-1)*100);
      moveto(getx+10,gety);
      sprintf(textb[0],"y pos (def %.3g):",
				   -(((float)oy/(Maxy/2)-1)*100));
      outtext(textb[0]);
      input_string(3,0);
      if (is[0]=='q') goto start15;
      else if (is[0]!=13) yoffset=atof(is);
      else yoffset=-(((float)oy/(Maxy/2)-1)*100);
      erase_prompt_box(2);
      ox=firstox=(signed int) (((float)Maxx/2)*(1+xoffset/100 ));
      oy=(signed int) (((float)Maxy/2)*(1-yoffset/100 ));
      newpos_was_set=1;
   }
  start30:
   /*specify spacing between basins*/
   get_prompt_box(1,3);
   xbox=draw_prompt_box(3);
   sprintf(textb[0],"amend basin spacing %% of 1/2 screen");
   outtext(textb[0]);
   moveto(xbox,gety+CHeight);
   sprintf(textb[0],"x spacing (def %.3g):",xpspacing);
   outtext(textb[0]);
   input_string(3,0);
   if (is[0]=='q'){
      erase_prompt_box(3);
      goto start20;
   }
   else if (is[0]!=13) xpspacing=atof(is);
   moveto(getx+10,gety);
   sprintf(textb[0],"y spacing (def %.3g):",ypspacing);
   outtext(textb[0]);
   input_string(3,0);
   if (is[0]=='q') goto start30;
   else if (is[0]!=13) ypspacing=atof(is);
   xspacing=(signed int) (((float)Maxx/2)*(xpspacing/100 ));
   yspacing=(signed int) (((float)Maxy/2)*(ypspacing/100 ));
   if (newpos_was_set==1) ox-=xspacing;
   /*min right border, then new row*/
   sprintf(textb[0],
	    "select right border as %% of x spacing (def %.1f%%):",
				       rightborder*100);
   moveto(xbox,gety+CHeight);
   outtext(textb[0]);
   input_string(4,0);
   if (is[0]=='q') goto start30;
   else if (is[0]!=13) rightborder=(float)atof(is)/100 ;
   
   outtext(" clear screen-c");
   input_string(1,0);
   if (is[0]=='q') goto start30;
   else if (is[0]=='c') clearviewport();
   uncover_free_prompt_box(1);   
}

/********************* set layout defaults ************************/
void set_layout_defaults(void){
 float r;
 signed int z;

   trans_shrink_fact=1.0; /*asymptotic shrink for sucessive transient levels*/
   lastlevel=90; /*for asymptotic shrink above, then no shrink*/
   free(rad);
   if ((rad=(float*)calloc(lastlevel+1,sizeof(float)))
				  ==NULL) outof_memory("rad");
   stagger_even_rows=0;
   /*scale of basins, specify attractor radius*/
   if (gd_z_graph){
      if (basinfield) pstartrad=2;
      else pstartrad=4;
   }
   else if (mutant_layout==1) pstartrad=2;
   //else if (screensavedemo==1) pstartrad=4.5*((float)2/value_range);
   /*basin size defaults have same scale for all v/k/n*/
   else if (screensavedemo==1) pstartrad=4.5;
   else if (basinfield && lineL*value_range<=6 && !rangeL) pstartrad=12;
   else if (basinfield && lineL*value_range<=9 && !rangeL) pstartrad=9;
   else if (basinfield && rangeL) pstartrad=3;
   else if (basinfield || rangeL) pstartrad=6;
   else pstartrad=12;

   startrad=(signed int) (((float)Maxx/2)*(pstartrad/100 ));

   /*specify basin start position, % of 1/2 screen*/
   if (gd_z_graph){
      if (basinfield){	         
	 xoffset=-80;
	 yoffset=60;	 
      }
      else{
	 xoffset=-70;
	 yoffset=50;
      }
      if (stp) xoffset=
	     (signed int)((((float)lineL*scale)/(Maxx/2))*100)-100+30;
   }
   else if (basinfield && lineL<=9 && !rangeL){ /*small net size*/
      xoffset=-60;
      yoffset=30;
   }
   else if (basinfield || rangeL || mutant_layout){
      /*if (stp) xoffset=-70;
      else xoffset=-80;*/
      xoffset=-70;
      if (basinfield){
	 if (rangeL) yoffset=70;
	 else yoffset=50;
      }
      if (!basinfield) yoffset=50;
   }
   else{
      if (stp) xoffset=30;
      else xoffset=0;
      yoffset=0;
   }
   fox=ox=(signed int) (((float)Maxx/2)*(1+xoffset/100 ));
   foy=oy=(signed int) (((float)Maxy/2)*(1-yoffset/100 ));

   /*specify spacing between basins*/
   if (basinfield || rangeL || gd_z_graph || mutant_layout){
      if (gd_z_graph){
#        if __UNIX__	    
	    xpspacing=13;
	    ypspacing=6;            
#        elif __WATCOM__           
            xpspacing=13;
	    ypspacing=10;            
#        endif
      }
      else if (mutant_layout){
         xpspacing=22;
	 ypspacing=22;
      } 
      else{
	 xpspacing=pstartrad*5; /* was 30*/
         ypspacing=pstartrad*5;
	     
	 if (rangeL){
	    if (basinfield){
	       xpspacing=15;
	       ypspacing=15;
	    }
	    else{
	       xpspacing=20;
	       ypspacing=35;
	    }
	 }
      }
      rightborder=.45;
   }
   startxspacing=xspacing=
	      (signed int) (((float)Maxx/2)*(xpspacing/100 ));
   startyspacing=yspacing=
	      (signed int) (((float)Maxy/2)*(ypspacing/100 ));
   /*select spacing increase*/
   if (rangeL || (gd_z_graph==3 && basinfield==0)){
      if (basinfield){
	 xpspacefact=10;
	 ypspacefact=10;
      }
      else{
	 xpspacefact=6;
	 ypspacefact=4;
      }
   }
   xspacefact=1+(xpspacefact/100);
   yspacefact=1+(ypspacefact/100);
   /*set up array of levels*/
   for (z=1;z<=lastlevel;z++){    /*lastindex=lastlevel-1*/
      if (z==1) r=startrad;
      else r += startrad/log(pow(z,2));
      rad[z-1]=r;
   }
}

/***************  draw layout preview in 1/4 screen *********************/
void draw_layout_preview(void){
 float start,finish,az,
       showox,showoy,showxspacing,showyspacing;
 signed int z,zz,stemp,
	      bno,fno,fstart,fend,turns,Mx,My;
   
     ox=fox;
     oy=foy;
     showox=ox/2;
     showoy=oy/2;
     showxspacing=xspacing/2;
     showyspacing=yspacing/2;
     Mx=Maxx/2-vgax(4);
     My=Maxy/2;      
     draw_box(-1,0,0,Mx,My,1,0);
     setviewport(0,0,Mx,My,1);
     /*draw layout in 1/4 screen preview*/
     for (z=1;z<=lastlevel;z++){    /*lastindex=lastlevel-1*/
	 turns=0;
	 if (z%20==0 || z<=4) setcolor(yellow);
	 else setcolor(darkgray);
	 /*to display spacing of levels*/
	 start = PI/2;
	 finish = .1+(PI/2)+(PI*2);
	 angle = deg * 3;
	 /*draw first*/
	 for (az=start;az<=finish;az+=angle){
	    turns+=1;
	    cx = rad[z-1] * cos(az)/2+showox;
	    cy = rad[z-1] * sin(az)/2+showoy;
	    if (az==start) moveto(cx,cy);
	    else lineto(cx,cy);
	    if (turns==80) putpixel(rad[z-1]*cos(az-angle)/2+showox,
				    rad[z-1]*sin(az-angle)/2+showoy,white);
	 }
     }

     if (successive_basins==0 && 
             (basinfield || rangeL || mutant_layout)){
	fstart=startL;
	fend=endL;
 	if (basinfield || mutant_layout){ 
	   /*bno=30;*/
	  bno=(signed int)(
               (((float)Maxx/2)/startrad ) * 2 );
          if (bno<30) bno=30;
        }
	else bno=1;

	for (fno=fstart-1;fno<=fend-1;fno++){
	   if (gety>Maxy) break;
	   if (basinfield && rangeL) bno=fno+1;
	   else{
	      if (fno>fstart-1) showox+=showxspacing;
	   }
	   setcolor(yellow);
           new_basin_row=1;
	   for (zz=1;zz<=bno;zz++){
	      if (gety>Maxy) break;
	      if (zz>1) showox+=showxspacing;
	      /*start new line*/
	      if ((Mx-showox)<showxspacing*rightborder){
		 if (basinfield && rangeL) break;
		 showox=ox/2;
                 if (stagger_even_rows==1){
                    new_basin_row++; /*stagger even rows*/
                    if (new_basin_row%2 == 0) showox+=showxspacing*.5;
	         }
		 showoy+=showyspacing;
	      }
	      for (z=1;z<=4;z++){
		 for (az=start;az<=finish;az+=angle){
		    cx = rad[z-1] * cos(az)/2+showox;
		    cy = rad[z-1] * sin(az)/2+showoy;
		    if (az==start) moveto(cx,cy);
		    else lineto(cx,cy);
		 }
	      }
	   }
	   showxspacing*=xspacefact;
	   showyspacing*=yspacefact;
	   if (basinfield || mutant_layout){
	      showox=ox/2;
	      showoy+=showyspacing;
	   }
	   else if (rangeL){
	      if (basinfield) showox+=showxspacing;
	      /*start new line*/
	      if ((Mx-showox)<showxspacing*rightborder){
		 showox=ox/2;
		 showoy+=showyspacing;
	      }
	   }
	}
     }
     setcolor(yellow);
     stemp=textwidth("y=+100")+vgax(4);
     draw_box(-1,Mx/2+2,2,
		  Mx/2+stemp,CHeight+vgay(6)+2, 1,0);
     outtext("y=+100");
     draw_box(-1,Mx/2+2,My-CHeight-vgay(6)-2,
		  Mx/2+stemp,My-2, 1,0);
     outtext("y=-100");
     draw_box(-1,2,My/2-CHeight-vgay(6)-2,
		  stemp,My/2-2, 1,0);
     outtext("x=-100");
     draw_box(-1,Mx-stemp,My/2-CHeight-vgay(6)-2,
		  Mx-2,My/2-2, 1,0);
     outtext("x=+100");

     stemp=textwidth("basin layout preview")+vgax(4);
     draw_box(-1,Mx-stemp,My-CHeight-vgay(6)-2,
		  Mx-2,My-2, 1,0);
     outtext("basin layout preview");

     setcolor(lightred);
     line(0,My/2,Mx,My/2);
     line(Mx/2,0,Mx/2,My);
     rectangle(0,0,Mx,My);
     setviewport(0,0,Maxx,Maxy,1);
     setcolor(white);

}

/************ set various basin drawing choises, 13 May 1993 ***************/
void format_draw(void){
 signed int xbox;
 char sn;

   moveto(memory_box(0,NULL)+vgax(3),vgay(3));
   setcolor(lightred);
   outtext("accept defaults-d");
   setcolor(white);
   hilight_learn=0;

   /******* equivilent trees/basins, and NULL boundaty conditions ********/
  select10:
   if (acceptall==0 && accept_from=='p'){
      select10a:
     //fprintf(stderr,"\nregular2d=%d dontcompress=%d",regular2d,dontcompress); 
     // if (!rulemix){
         
	 if (nonlocal==1 && regular2d==0) sprintf(textb[0],
	     "non-local network, v%dk%d size=%d",value_range,nhood,lineL);
	 else if (nonlocal==0 && regular2d==0) sprintf(textb[0],
	     "local 1d CA, v%dk%d size=%d",value_range,nhood,lineL);
	 else if (regular2d) sprintf(textb[0],
	      "local 2d CA, v%dk%d size=%dx%d",value_range,nhood,i2d,j2d);
         else sprintf(textb[0],
	       "v%dk%d size=%dx%d", value_range,nhood,i2d,j2d);

	 //fprintf(stderr,"\ndontcompress=%d", dontcompress);

         if (NULLboundaries==0 && dontcompress==0 &&
	     (nonlocal==0 || compress_1d_local || regular2d)) //regular2d change default to uncompressed
                  sprintf(textb[2]," (compression ON, off-s:) ");
	 else if (NULLboundaries==0 && dontcompress==1 &&
	     (nonlocal==0 || compress_1d_local || regular2d)) 
	         sprintf(textb[2]," (compression OFF, on-s:) ");
	 
         else sprintf(textb[2]," (compression OFF) ");

         if (NULLboundaries==0){
	    /*dont allow NULL for twod basins (single or field),
              unresolved duplication of basins, 
              inconsistent results with exaustive, and seg faults*/
            if (regular2d) sprintf(textb[1],"Periodic boundaries%s:",textb[2]);
            else if (oned || basinfield==0){
               if (dontcompress==0) sprintf(textb[1],
                  "Periodic boundaries%sNull-N:",textb[2]);
               else sprintf(textb[1],
		  "Periodic boundaries%sNull-N:",textb[2]);
            }
         }
	 else if (NULLboundaries==1) sprintf(textb[1],
		   "Null boundaries%sPeriodic-P:",textb[2]);             
	 
	 xbox=draw_prompt_box(2);
         setcolor(lightred);
         outtext("display: ");
         setcolor(white);
	 outtext(textb[0]);
	 moveto(xbox,gety+CHeight);
	 outtext(textb[1]);
	 input_string(1,0);
	 erase_prompt_box(2);

	 if (is[0]=='q') return;
	 if (is[0]=='d') acceptall=1;
	 if (NULLboundaries==0){
	     if (is[0]=='s'){
	         dontcompress=abs(dontcompress-1);
		 goto select10a;
	     }
             else if (is[0]=='N' && oned){ /*dont allow for 2d*/
	         NULLboundaries=1;
                 dontcompress=1;
                 goto select10a;
	     }
         }
         if (NULLboundaries==1 && is[0]=='P'){ 
	     NULLboundaries=0;
             dontcompress=0;
             goto select10a;
         }
 
	 if (acceptall==0 && dontcompress==0){
	    sprintf(textb[0],
	         "copies of trees (& subtrees from uniforn states)");
	       sprintf(textb[1],
	    "suppress: all-3, show only g-of-E nodes: nornal-2 small-1:");
	    xbox=draw_prompt_box(2);
	    outtext(textb[0]);
	    moveto(xbox,gety+CHeight);
	    outtext(textb[1]);
	    input_string(1,0);
	    erase_prompt_box(2);

	    if (is[0]=='q') goto select10;
	    else if (is[0]=='d') acceptall=1;
	    dontcopytrees=0;
	    if (is[0]=='1') dontcopytrees=1; /*small spots*/
	    else if (is[0]=='2') dontcopytrees=2; /*normal circle-spots*/
	    else if (is[0]=='3') dontcopytrees=3; /*no spots*/
	 }
      //}
   }
   /*********select node type *************/
  select15:
   if (acceptall==0 && accept_from=='p'){      
      just_G=0; 
      if (shownumbers==-1) sn='n'; /*none*/
      else if (shownumbers==0) sn='s'; /*spot*/
      else if (shownumbers==1 && lineL<32) sn='c'; /*decimal*/
      else if (shownumbers==2) sn='h'; /*hex*/
      else if (shownumbers==3 && showbits_1d_as_2d==0) sn='b'; /*1d bitstring*/
      else if (shownumbers==3 && showbits_1d_as_2d==1) sn='B'; /*2d bitstring i x j*/
      else sn='h';

      xbox=draw_prompt_box(2);
      if (!((nonlocal==0 || regular2d) && !rulemix)){
           setcolor(lightred);
	   outtext("display: ");
           setcolor(white);
      }
      if (oned || threed){
	 if (max_dec_rule(lineL-1,value_range)==0) sprintf(textb[0],
	      "nodes: 2d-B 1d-b hex-h spot-s");
	 else sprintf(textb[0],
	      "nodes: 2d-B 1d-b hex-h dec-c spot-s");
      }
      else if (twod){
	 if (max_dec_rule(lineL-1,value_range)==0) sprintf(textb[0],
	    "nodes: 2d-b hex-h spot-s");
	 else sprintf(textb[0],
	    "nodes: 2d-b hex-h dec-c spot-s");
      }
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);
      sprintf(textb[0],
    "just Sym-nodes +S, just g-nodes +g, no g-nodes +G, none-n (def-%c):",sn);
      outtext(textb[0]);
      input_string(2,0);
      if (is[0]=='q'){
	 if (!((nonlocal==0 || regular2d) && !rulemix)) erase_prompt_box(2);
	 if ((nonlocal==0 || regular2d) && !rulemix) goto select10;
	 else return;
      }
      else if (is[0]=='d'){
	 acceptall=1;
	 if (!((nonlocal==0 || regular2d) && !rulemix)) erase_prompt_box(2);
      }
      if (!shownumbers=='3' || twod) showbits_1d_as_2d=0;
      if (is[0]=='c' && max_dec_rule(lineL-1,value_range)>0) shownumbers=1;
      else if (is[0]=='h') shownumbers=2;
      else if (is[0]=='b' || (is[0]=='B' && twod)){
	 hilight_learn=showbits_1d_as_2d=0;
	 shownumbers=3;
      }
      else if (is[0]=='B'){
	 shownumbers=3;
         sn='B';
	 showbits_1d_as_2d=1;
         //set_i2dxj2d();
         i2d=b_i2d;
         j2d=b_j2d;
      }
      else if (is[0]=='s') shownumbers=0;
      else if (is[0]=='n') shownumbers=-1;
      if (is[0]=='g' || is[1]=='g') just_G=1;
      if (is[0]=='G' || is[1]=='G') just_G=2;
      if (is[0]=='S' || is[1]=='S') just_G=3;
      erase_prompt_box(2);
      
      show_one_att_state=0;
      if (acceptall==0 && accept_from=='p'){
         sprintf(textb[0],
	   "highlight attractor (or subtree root) in 2d: one-1 all-a:");
         draw_prompt_box(1);
         outtext(textb[0]);
         input_string(1,0);
         if (is[0]=='q') goto select15;
         if (is[0]=='d') acceptall=1;
         else if (is[0]=='1') show_one_att_state=1;
         else if (is[0]=='a') show_one_att_state=2;        
         
         if (acceptall==0 && ( 
              showbits_1d_as_2d==1 ||
                 (twod && shownumbers==3) || 
                                   show_one_att_state) ){
	    i2d=b_i2d;
            j2d=b_j2d;

	    sprintf(textb[0],"2d node ij now %dx%d: reset i (max %d):",i2d,j2d,lineL);
	    if (i2d*j2d != lineL) fprintf(stderr,"\n%dx%d != %d", i2d,j2d,lineL);//trap error
	    draw_prompt_box(1);
	    outtext(textb[0]);
	    input_string(3,0);
	    if (is[0]=='q') goto select15;
	    else if (is[0]=='d') acceptall=1;
	    else if (is[0]!=13 && atoi(is)>0 && atoi(is)<=lineL){
	          i2d=atoi(is);
	          j2d=(signed int)ceil((double)lineL/i2d);
                  b_i2d=i2d; //to keep this setting
                  b_j2d=j2d;                             
	    }
         }
      }
   }

   if (shownumbers>0){
      if (acceptall==0 && accept_from=='p'){
	if (labelsizefactor==0) labelsizefactor=1;
	 /*state as dec or hex*/
	 if (shownumbers<3){
	    sprintf(textb[0],
       "dec/hex node scale (now %d), enter factor (now %.1f), original-o: ", 
                                              pointsize,labelsizefactor);
	    draw_prompt_box(1);
	    outtext(textb[0]);
	    input_string(3,0);
	    if (is[0]=='q') goto select15;
	    else if (is[0]=='d') acceptall=1;
	    else if (is[0]==13); /* do nothing*/
            else if (atof(is)>0 || is[0]=='o'){
	      signed int psize;
	       if (is[0]=='o') psize=psize_ps=pointsize;
               else{
	          labelsizefactor=atof(is);
                  psize=(signed int)(pointsize*labelsizefactor);
               }               
#              if __UNIX__ 
                  if (labelsizefactor>0){
                     sprintf(textb[1],"%s%d%s","-*-times-medium-r-*-*-*-",
                                                  psize*8,"-*-*-*-*-*-*");  
		     tempfont=XLoadQueryFont(D,textb[1]);
                  }
#              endif        
	       psize_ps=psize; /*for basin postSript, if selected later*/
	    }
	 }
      }
   }
   /*def cell scale*/
   if (shownumbers==3 || show_one_att_state || show_maj>=0){
      if (acceptall==0 && accept_from=='p'){
	    scale=4;
	    sprintf(textb[0],"cellscale (now %d pixels):",scale);
	    draw_prompt_box(1);
	    outtext(textb[0]);
	    input_string(2,0); /*as 2 digits max scale set here is 99*/
	    if (is[0]=='q') goto select15;
	    else if (is[0]=='d') acceptall=1;
	    else if (is[0]!=13 && atoi(is)>0) scale=atoi(is);
		 
	    //reset dives dots 
            if (scale>=6){ 
                   node_tight=0; /*allows divs in bit/value pattern*/
                   node_dots=1; /*put a dot on zero cell -- only useful for 2d nodes*/
	    }
	    else{
                   node_tight=1; /*no divs*/
                   node_dots=0;  /*no dots*/
            } 
      
            if (node_tight==1) outtext(" tog divs(now OFF)-t:");
            else outtext(" tog divs(now ON)-t:");
            input_string(1,0);
            if (is[0]=='q') goto select15;
            else if (is[0]=='d') acceptall=1;
            else if (is[0]=='t') node_tight=abs(node_tight-1);

            if (node_dots==0) outtext(" tog dots(now OFF)-t:");
            else outtext(" tog dots(now ON)-t:");
            input_string(1,0);
            if (is[0]=='q') goto select15;
            else if (is[0]=='d') acceptall=1;
            else if (is[0]=='t') node_dots=abs(node_dots-1);
      }
   }

   if (acceptall==0 && accept_from=='p'){
     
      sprintf(textb[0],"change basin orientation anti-clockwise (now %d), enter angle:",
	                              (signed int)(orient_angle/deg));
      xbox=draw_prompt_box(3);
      outtext(textb[0]);
      input_string(4,0);
      
      if (is[0]=='q'){
         erase_prompt_box(3); 
         goto select15;
      }
      else if (is[0]=='d'){ 
         acceptall=1;
         erase_prompt_box(3);
         goto skip;
      }
      else if (is[0]=='-' || (is[0]!=13 && atoi(is)>=0))
	     orient_angle=atof(is)*deg;
      
      moveto(xbox,gety+CHeight); 
      if (fan_angle_fact==0) fan_angle_fact=1; 
      sprintf(textb[0],"change pre-image fan angle (now %.2f), enter factor:",
	                                        fan_angle_fact);
      outtext(textb[0]);
      input_string(4,0);
      if (is[0]=='q'){ 
         erase_prompt_box(3);
         goto select15;
      }     
      else if (is[0]=='d'){
           acceptall=1;
           erase_prompt_box(3);
           goto skip;
      }
      else if (is[0]!=13 && atof(is)>0) fan_angle_fact=atof(is);
      /*input_string(6,0);
      if (is[0]=='q'){ 
         erase_prompt_box(3);
         goto select15;
      }     
      else if (is[0]=='d'){
           acceptall=1;
           erase_prompt_box(3);
           goto skip;
      }*/
           
      moveto(xbox,gety+CHeight);
 
      /*black background:  red-0 blue-1 green-2 yellow-3*/
      /*white backgroundg  red-0 brown-1 green-2 blue-3*/

      outtext("change start edge color (");
      setcolor(start_edge_color);
      outtext("now");
      setcolor(white);
      outtext(") ");
      setcolor(lightred);
      outtext("----0 ");
      setcolor(lightcyan);
      outtext("----1 ");
      setcolor(green);
      outtext("----2 ");
      setcolor(yellow);
      outtext("----3");
      setcolor(white);
      outtext(":");
 
      input_string(1,0);
      
      if (is[0]=='q'){ 
         erase_prompt_box(3);
         goto select15;
      }      
      else if (is[0]=='d'){
           acceptall=1;
      }                                                  
      if (is[0]!=13 && atoi(is)>=0 && atoi(is)<=3){
	 if (atoi(is)==0) start_edge_color=lightred;
          else if (atoi(is)==1) start_edge_color=lightcyan;
          else if (atoi(is)==2) start_edge_color=green;
          else if (atoi(is)==3) start_edge_color=yellow; 
      }
      erase_prompt_box(3);
   }   	    
  skip:
   if (accept_from=='p') accept_from='t';
}

/************ data, May 1993  ***************/
void data_att(void){
 signed int xbox;

   moveto(memory_box(0,NULL)+vgax(3),vgay(3));
   setcolor(lightred);
   outtext("accept defaults-d");
   setcolor(white);
   hilight_learn=0;
   	    
   /***pause to see data ***/
  select20:
   /***pause to see data, fields***/   
   if (rangeL==1 && basinfield){
      if (acceptall==0 && accept_from=='t'){
         draw_prompt_box(1);
         setcolor(lightred);
         outtext("pause/data: ");
         setcolor(white);
         sprintf(textb[0],"field range %d-%d, ",startL,endL);
         outtext(textb[0]);
	 outtext("pause after each field-f:");
	 input_string(1,0);
	 if (is[0]=='q') return;
	 fieldpause=0;
	 if (is[0]=='d') acceptall=1;
	 if (is[0]=='f') fieldpause=1;
      }
   }

   /***pause to see data, trees and basins***/
   if ((rangeL==1 && basinfield && fieldpause==1) ||
	  (!rangeL && basinfield && fieldpause==0) || !basinfield){
      if (acceptall==0 && accept_from=='t'){
	 if (successive_basins==1) datapause=1;
	 else datapause=0;
         draw_prompt_box(1);

         
         setcolor(lightred);
         outtext("pause/data: ");
         setcolor(white);
         
	 if (rangeL==1 || successive_basins==1 || basinfield)
	            outtext("fan-3 tree-2 basin-1 none-def:");
	 else outtext("fan-3 tree-2 none-def:");         
	 input_string(1,0);
	 if (is[0]=='q' && rangeL==1 && basinfield) goto select20;
	 else if (is[0]=='q') return;
	 else if (is[0]=='d') acceptall=1;
	 else if (is[0]=='0') datapause=0;
	 else if (is[0]=='1') datapause=1; /*pause after basin*/
	 else if (is[0]=='2') datapause=2; /*pause after tree*/
         else if (is[0]=='3') datapause=3; /*pause after subtree*/
      }
   }
   /*** select data to printer ***/
  select30:
   pdata=printstates=0;
#  if __UNIX__  /*no terminal to print to in DOS, better to save file below*/
   if (acceptall==0 && accept_from=='t'){  
      sprintf(textb[0],"print data: basin data only-1, and tree data-2");
      sprintf(textb[1],
        "include states: details-s/+s no-details-S/+S att-only-a/+a:");
      xbox=draw_prompt_box(2);
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);
      outtext(textb[1]);
      input_string(3,0);
      erase_prompt_box(2);
      if (is[0]=='q') goto select20;
      if (is[0]=='d') acceptall=1;
      else {
	char show_details=0;
	 if (is[0]=='1') pdata=1;
	 else if (is[0]=='2') pdata=2;
         
         if (is[0]=='s' || is[1]=='s' || is[2]=='s'){
              show_details=1;
              printstates=1;
         }
         if (is[0]=='S' || is[1]=='S' || is[2]=='S'){
              show_details=2;
              printstates=2;
         }         
         if (is[0]=='a' || is[1]=='a' || is[2]=='a'){ 
             printstates=3;
             if (show_details==2) printstates=4;             
	 }
      }
   }
#  endif
   /*** select data saved to file ***/
  select40:
   filedata=filestates=0;
   is[0]=is[1]=is[2]='0';   
   if (acceptall==0 && accept_from=='t'){
      sprintf(textb[0],"save data: basin data only-1, and tree data-2");
      sprintf(textb[1],
          "include states: details-s/+s no-details-S/+S att-only-a/+a:");         
      xbox=draw_prompt_box(2);
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);
      outtext(textb[1]);
      input_string(3,0);
      erase_prompt_box(2);
      if (is[0]=='q'){
#        if __UNIX__  
            goto select30;
#        elif __WATCOM__ 
            goto select20;
#     endif
      }
      if (is[0]=='d') acceptall=1;
      else {
        char show_details=0;
         if (is[0]=='1') filedata=1;
	 else if (is[0]=='2') filedata=2;

         if (is[0]=='s' || is[1]=='s' || is[2]=='s'){
              show_details=1;
              filestates=1;
         }
         if (is[0]=='S' || is[1]=='S' || is[2]=='S'){
              show_details=2;
              filestates=2;
         }           
         if (is[0]=='a' || is[1]=='a' || is[2]=='a'){ 
             filestates=3;
             if (show_details==2) filestates=4;             
	 }

	 if (filedata || filestates){ 
            signed int fid;
            char file_ret;           
 	    file_ret=select_filename("SAVE","DATA","*.dat","my_data");
	    if (file_ret=='q') goto select40;
	    memmove(filename_data,filename,13);
            fid=myopen(filename_data,1,1);
            if (fid==-1) file_error(filename_data);
	    close(fid);
	 }
      }
   }
   if (accept_from=='t') accept_from='P';
}

/************ PostScript - jump graph, Dec 2007 ***************/
void postScript_basin(void){
 signed int xbox;

   moveto(memory_box(0,NULL)+vgax(3),vgay(3));
   setcolor(lightred);
   outtext("accept defaults-d");
   setcolor(white);
   	      
  /*** select save basin drawing to postScript, color or greyscale  ***/
  select45:
   if (acceptall==0 && accept_from=='P'){
      xbox=draw_prompt_box(1);
      setcolor(lightred);
      outtext("PScript: ");
      setcolor(white);
      if (basin_postScript==1) sprintf(textb[1],"now p");
      else if (basin_postScript==2) sprintf(textb[1],"now P");
      else sprintf(textb[1],"now OFF");
      if (basin_postScript==1 || basin_postScript==2) sprintf(textb[0],
        "save basin to PostScript (%s): greyscale-P color-p cancel-0:",textb[1]);
      else sprintf(textb[0],
        "save basin to PostScript (%s): greyscale-P color-p:",textb[1]);
      outtext(textb[0]);
      input_string(1,0);
      erase_prompt_box(1);
      if (is[0]=='q') return;
      else if (is[0]=='d') acceptall=1;
      else if (is[0]=='0'){
         basin_postScript=0;
         goto select45;
      }
      else if (is[0]=='p') basin_postScript=1; /*color*/
      else if (is[0]=='P') basin_postScript=2; /*greyscale*/
      
      if (basin_postScript==1 || basin_postScript==2){
           signed int fid;
           char file_ret;            
 	    file_ret=select_filename("SAVE","PostScript file","*.ps","my_bPS");
	    if (file_ret=='q') goto select45;
	    memmove(filename_basin_PS,filename,13);
            fid_PS=myopen(filename_basin_PS,1,1);
            if (fid_PS==-1) file_error(filename_basin_PS);
	    //close(fid);
            close(fid_PS);
       }
   }
   if (accept_from=='P') accept_from='g';
}

/**** jump graph, Dec 2007, Jan2022 "ibaf-graph", istr-graph March 2025  ***********/
void jumpgraph_basinfield(void){
 signed int xbox;

   moveto(memory_box(0,NULL)+vgax(3),vgay(3));
   setcolor(lightred);
   outtext("accept defaults-d");
   setcolor(white);
 
  /*** select the jump-graph (set to 0 in main)*/
  select50:
   if (acceptall==0 && accept_from=='g'){
    
	    is[1]=0; //fixed
            jump_layout_only=0;
            jump_graph=0;
            ibaf_graph=0;
	    istr_graph=0;
            xbox=draw_prompt_box(1);
            setcolor(lightred);
            outtext("iteractive graphs: ");
            setcolor(white);
	    
	    if (basinfield){
	        outtext("istr-s ibaf-i, jump-j(no-edges+L):");
                input_string(2,0);
	    }
	    else{
	        outtext("state transition graph, istr-s:");
                input_string(1,0);
	    }	
            if (is[0]=='q') return;
            if (is[0]=='d') acceptall=1;

            if (basinfield){ /****/
               if (is[0]=='j'){
                  jump_graph=1;
                  if (is[1]!='L'){		   		  
		     if (dontcompress==0){
		        /*for simple 1d CA only, 
                          because for any other system compression will be off*/
			 outtext("-compression OFF:");
                         if (is[0]=='q') return;
                         if (is[0]=='d') acceptall=1;
		         input_string(1,0);	 
                      }
		      dontcompress=1; /*jump-graph with links compression must be off*/
                  }
                  else if (is[1]=='L' ){
		     signed int tempx;
		     char doagain;
		         jump_layout_only=1;
		         tempx=getx;
		         /*so do this for simple 1d CA only, 
                          because for any other system compression will be off*/
		         if (oned && !nonlocal && !rulemix){
		           startcomp:
		            doagain=0;		      
		            if (dontcompress==1) outtext("-compression OFF tog-t:");
		            if (dontcompress==0) outtext("-compression ON tog-t:");
		            if (is[0]=='q') return;
                            if (is[0]=='d') acceptall=1;
		            input_string(1,0);
		      
		            if (is[0]=='t'){
		                dontcompress=abs(dontcompress-1);
			        fillcolor=black;
			        bar(tempx,vgax(2),Maxx-vgax(3),CHeight*1.5);
			        moveto(tempx,gety);
			        doagain=1;
	                    }
		            if (doagain==1) goto startcomp;
			 }  
		      }	 
	          }//if (is[0]=='j'){
	       
                  else if (is[0]=='i'){
                     ibaf_graph=1; //interactive basin-of-attraction-field graph ibaf_graph
                              //April 2021,was ist-graph (intreractive state-transition graph)
                
		     //for simple 1d CA only, because for any other system compression will be off
		     if (dontcompress==0){  
                         outtext(" - compression OFF:");
                         if (is[0]=='q') return;
                         if (is[0]=='d') acceptall=1;
		         input_string(1,0);
                     }
		     dontcompress=1; /*ibaf-graph always has links socompression must be off*/
                  }
	          else if (is[0]=='s'){
		     /*for direct basin field with compression, see also single basin and subtrees*/ 
		     istr_graph=1;
                  }	    
	    }/*if (basinfield){*/ /****/
	    
	    else{ /*not basinfield*/
	       if (is[0]=='s'){ /*for single basin or subtree*/
	         istr_graph=1;
	       }
            }

	    /**************************** for istr_graph, June 2025 ******************************/ 
	    if (istr_graph==1 && rangeL==0){
	      //istr_graph callocked and freed in in mainxx
	       istr_node_count=0; /*count of state transition graph states as in grapb*/
	       early_exit_draw_fan=0;
	       /*compression of 2d does not work for the istr_graph,
		 and buggy for the classic graph, 
                so change to "dontcompress" if was selected (its not the default for 2d)*/
	       if (regular2d && dontcompress==0){
		   draw_prompt_box(1);
		   outtext("compressed istr-graph invalid for 2d, changed to uncompressed: cont-ret:");
		   input_string(1,0);
		   dontcompress=1;
	       }	   
            }
	    if (accept_from=='g') accept_from='m';
   }
}

/************** specify mutation for next network ***********************/
void set_mutation(void){
  signed int xbox;
  char which;

  select50:
   which=0;
   if (mutate!='n'){ 
      mutate='b';

      mutate_wiring=0; /* 1=cumulative=1 2=restore original before*/
      mutate_wiring_and_rule=0; /* ... to mutate wiring as well as rule*/ 
      wires_to_move=1;

      bits_to_flip=1;
      if (gd_z_graph || screensavedemo==1){
         if (totalistic==0) mutate=2; /*random rule*/
         if (gd_z_graph){
	    if (nhood<=3) mutate=3;   /*decriment rule no*/
	    if (totalistic) mutate=5; /*decriment code no*/
         }
      }
   }
   if (gd_z_graph==3){
      mutate='b';
      bits_to_flip=1;
   }
   if ((acceptall==0 && accept_from=='m') || gd_z_graph==3){
      if (value_range==2)
          sprintf(textb[0],"(for next) chain-c Post-P tcode-t kcode-k rcode-r none-n ");
      else sprintf(textb[0],"(for next) chain-c tcode-t kcode-k rcode-r none-n ");
      if (loc_twod_fonly) sprintf(textb[1],
	  "rule: special-s, set bits-b, single bit-1");
      else sprintf(textb[1],
	               "wiring-w/+w, rule: special-s, set bits/values-b, single bit/value-1");
      xbox=draw_prompt_box(2);
      setcolor(lightred);
      outtext("mutation: ");
      setcolor(white);
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);           
      outtext(textb[1]);
      if (mutate!='b'){
        if (isalpha(mutate)) sprintf(textb[0]," (def %c)",mutate);
        else sprintf(textb[0]," (def %d)",mutate);
      }
      //else sprintf(textb[0]," (def %c%lu)",mutate,bits_to_flip);
      else sprintf(textb[0],"-(def)");
      outtext(textb[0]);
      outtext(":");
      input_string(2,0);
      erase_prompt_box(2);
      if (is[0]=='q') return;
      if (is[0]=='d') acceptall=1;
      /* allow wiring mutation + rule mutation*/

      if (is[0]=='w' || is[1]=='w'){
        char temp_is0;
        unsigned int zu;
        signed int z;

	 temp_is0=is[0];
	 if (is[0]=='w') mutate_wiring=1;
         else if (is[1]=='w') mutate_wiring_and_rule=1;
	 nonlocal=1;
         /*backup current wiring*/
         for (zu=lineL-1;zu!=Maxu;zu--){
	   for (z=nhood-1;z>=0;z--){
	      wiring_backup[zu][z]=wiring[zu][z];
	   }
         }
	 wire_move('s',0); /*specify wire moves*/
	 if (is[0]=='q') goto select50;
         is[0]=temp_is0;
      }

      if (is[0]=='1') mutate='b'; /*to change back to single bit*/      
      if (is[0]=='n') mutate='n'; /*dont mutate*/
      if (is[0]=='b'){
	 mutate='b';
	 set_bit_flips();
	 if (is[0]=='q') goto select50;
      }
      if (is[0]=='c') mutate='c'; /*rand chain rules*/
      if (value_range==2 && is[0]=='P') mutate='P'; /*Post rules*/
      if (is[0]=='t') mutate='t'; /*rand tcode*/
      if (is[0]=='k') mutate='k'; /*rand kcode*/
      if (is[0]=='r') mutate=2; /*rand rcode*/ 
	
      if (is[0]=='s'){
        signed int tablemax,tablecodemax=0;
        unsigned long rule_dec_max,code_dec_max=0;

	 /*check if decimal is allowed*/
         tablemax= (signed int)pow(value_range,(double)nhood)-1;
         rule_dec_max=max_dec_rule(tablemax,value_range);
         if (rule_dec_max>0) sprintf(textb[7],"rcodeno-3 ");
         else sprintf(textb[7],"");

         if (totalistic==1) /*tcode*/ 
            tablecodemax=nhood*(value_range-1); /*max index of tcode table*/
         else if (totalistic==2){ /*kcode*/
            tablecodemax=v_tablecodemax[nhood]; /*max index of kcode table*/
         }
         if (totalistic){
              code_dec_max=max_dec_rule(tablecodemax,value_range);
              mutate=4; /*default tcode or kcode flip*/
	 }
	 else mutate=2;/*rnd rcode flip is default*/
         
         if (totalistic==1){ 
             sprintf(textb[4],"tcode");
             if (code_dec_max>0) sprintf(textb[6],"tcodeno-5 ");
             else sprintf(textb[6],"");
         }
	 else if (totalistic==2){
             sprintf(textb[4],"kcode");
             if (code_dec_max>0) sprintf(textb[6],"kcodeno-5 ");
             else sprintf(textb[6],"");
	 }
	 if (totalistic){
            sprintf(textb[0],"specify rcode or %s mutation",textb[4]);
            sprintf(textb[5],"%sflip-4",textb[4]);
	    if (code_dec_max>0) sprintf(textb[1],
	       "%s%s %srcodeflip-2 (def-%d)",textb[6],textb[5],textb[7],mutate);
	    
	    else sprintf(textb[1],"%s%s rcodeflip-2 (def-%d)",textb[6],textb[5],mutate);
	 }
	 else{
            sprintf(textb[0],"specify rcode mutation");
            sprintf(textb[1],"%srcodeflip-2 (def-%d)",textb[7],mutate);
	 }
         if  (mutant_layout==1) sprintf(textb[3], "(Mutant Layout Set) ");

	 if (!nhood_mixed) sprintf(textb[2],
	      "bit/value flip from left: cumulative-1 single-0:");
         else sprintf(textb[2],":");

	 xbox=draw_prompt_box(3);
	 outtext(textb[0]);
	 moveto(xbox,gety+CHeight);
	 outtext(textb[1]);
	 moveto(xbox,gety+CHeight);
         if  (mutant_layout==1) outtext(textb[3]);
	 outtext(textb[2]);
	 input_string(1,0);
	 erase_prompt_box(3);
	 if (is[0]=='q'){
	    if (loc_twod_fonly) return;
	    else goto select50;
	 }
	 if (is[0]=='d') acceptall=1;
	 else if (is[0]!=13 && atoi(is)<6 && atoi(is)>-1) mutate=atoi(is);
         if (mutate==2) mutate='b'; /*rnd bit/value in rcode*/
	 if (mutate==2 || mutate==3) totalistic=0;

	 /*** specify start and end bitflip position ***/
	 if (mutate==1 || mutate==0){
	    if (totalistic==0){
                 startmut=tablemax; /*rcode*/ 
                 sprintf(textb[4],"rcode");
            }           
	    else startmut=tablecodemax; /*tcode or kcode*/
	    endmut=0;
	    if (acceptall==0 && accept_from=='m'){
	       xbox=draw_prompt_box(2);
               if (value_range==2) sprintf(textb[0],
		    "%s: specify start - end position of bitflip (countdown)",textb[4]);
               else  sprintf(textb[0],
		    "%s: specify start - end position of valueflip (countdown)",textb[4]);
	       outtext(textb[0]);
	       moveto(xbox,gety+CHeight);
	       sprintf(textb[0],"start position (def %d):",startmut);
	       outtext(textb[0]);
	       input_string(4,0);
	       if (is[0]=='q'){
		  erase_prompt_box(2);
		  goto select50;
	       }
	       if (is[0]=='d'){
		  acceptall=1;
		  erase_prompt_box(2);
	       }
	       else if (is[0]!=13) startmut=atoi(is);
	       if (acceptall==0){
		  moveto(getx+10,gety);
		  sprintf(textb[0],"end position (def %d):",endmut);
		  outtext(textb[0]);
		  input_string(4,0);
		  erase_prompt_box(2);
		  if (is[0]=='q') return;
		  if (is[0]=='d') acceptall=1;
		  else if (is[0]!=13) endmut=atoi(is);
	       }
	    }
	 }
      }
   }
   if (istr_graph==0 && ibaf_graph==0 && jump_graph==0){
   /*** pause to see data, trees and basins ***/
      if (datapause==0){
         mutantdontpause=0;
         if (gd_z_graph || screensavedemo==1) mutantdontpause=1;
         if (acceptall==0 && accept_from=='m'){
	    if (mutantdontpause==0) sprintf(textb[0],
	      "don't pause after mutant-y:");
	    else sprintf(textb[0],
	      "pause after mutant-y:");
	    xbox=draw_prompt_box(2);
	    outtext(textb[0]);
	    input_string(1,0);
	 
	    if (is[0]=='q') goto select50;
	    else if (is[0]=='d') acceptall=1;
	    else if (is[0]=='y') mutantdontpause=abs(mutantdontpause-1);         
     
            if (mutantdontpause==1){
               moveto(xbox,gety+CHeight);
               sprintf(textb[0],
	         "change delay (now %.2f sec, max 100):",pause_fact);
               outtext(textb[0]);
               input_string(4,0);
	       if (is[0]=='q') goto select50;
               else if ((isdigit(is[0]) || is[0]=='.') &&
		   atof(is)>=0 && atof(is)<=100) pause_fact=(float)atof(is);

            }
         }
         erase_prompt_box(2);
      }
   }
}

/************* number of bits to flip in rule table  ************/
void set_bit_flips(void){
 signed int xbox,tablemax;
 signed long tb;
 unsigned int poss;
 
   tablemax= (signed int)pow(value_range,(double)nhood)-1;
   if (!rulemix) tb=tablemax+1;
   else{
      if (bits_to_flip==0) bits_to_flip=1;
      tb=0;/*total bits*/
      if (!nhood_mixed) tb=(tablemax+1)*lineL;
      else{
	 for (poss=0;poss<=lineL-1;poss++){
            tablemax= (signed int)pow(value_range,(double)nhood)-1;
	    tb+=(tablemax+1);
	 }
      }
   }
  start:
   sprintf(textb[0],
     "rcode: bits/values to flip=%d/%d=%.3g%%: all-a number-n %%-p:",
	      (unsigned int)bits_to_flip,(unsigned int)tb,
			    100*(double)bits_to_flip/tb);
   xbox=draw_prompt_box(2);
   outtext(textb[0]);
   input_string(1,0);
   moveto(xbox,gety+CHeight);
   if (is[0]=='q') return;
   if (is[0]=='a') bits_to_flip=-1;
   else if (is[0]=='p'){
      outtext("% of total bits/values:");
      input_string(3,1);
      if (is[0]=='q') goto start;
      if (is[0]!=13 && atoi(is)>0 && atoi(is)<100)
			      bits_to_flip=atoi(is)*tb/100;
   }
   else if (is[0]=='n'){
      outtext("number of bits/values:");
      input_string(6,1);
      if (is[0]=='q') goto start;
      if (is[0]!=13 && atoi(is)>0 && atoi(is)<tb) bits_to_flip=atoi(is);
   }
   erase_prompt_box(2);
}

/****************** move one or more wires   ******************/
unsigned char wire_move(char what,unsigned char color1){
  signed int tempx,tempy,xbox;
  unsigned int poss,wire;
  signed long tw;
  unsigned char tempcolor;
  char from_original_wiring=0;

   tempcolor=getcolor();
   setcolor(white);

   if (wires_to_move==0) wires_to_move=1;
   tw=0;/*total wires*/
   if (!nhood_mixed) tw=nhood*lineL;
   else{
      for (poss=0;poss<=lineL-1;poss++) tw+=nhoodm[poss];
   }

   if (what=='W' || what=='s'){ /*s=set only from set_mutation*/
     start:                     /*W from interrupt_stp()*/
      tempx=getx;
      tempx=getx;
      tempy=gety;
      
      sprintf(textb[0],
      "wires to move=%ld/%ld=%.3g%%(def): all-a number-n %%-p",
	          wires_to_move,tw,100*(double)wires_to_move/tw);
      if (what=='s') sprintf(textb[1],"local-L, from original wiring-w/+w:");
      else sprintf(textb[1],"local-L:");
      is[0]=0;
      is[1]=0;
      
      xbox=draw_prompt_box(2);
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);
      outtext(textb[1]);
      input_string(2,0);
      
      if (is[0]=='q') goto endWire_move;
      if (is[1]=='w' && what=='s') from_original_wiring=1;

      if (is[0]=='w' && what=='s') from_original_wiring=1;
      else if (is[0]=='L'){ /*restore local wiring*/
        unsigned int zu;
        signed int z;
	  for (poss=0;poss<=lineL-1;poss++){
             if (oned)  oneD_local_wire_cell(poss,lineL-1);
             else if (twod) wireup_2d_nhood(i2d-1,j2d-1,0,0);
             else if (threed) wireup_3d_nhood(i3d-1,j3d-1,h3d-1,0,0,0);
          }
          if (oned && !rulemix) nonlocal=0;
          if (twod && !rulemix) regular2d=1;
          /*backup current wiring*/
          for (zu=lineL-1;zu!=Maxu;zu--){
	    for (z=nhood-1;z>=0;z--){
	       wiring_backup[zu][z]=wiring[zu][z];
	    }
          }
	  mutate_wiring_and_rule=0;          
          if (what=='s') wires_to_move=1;
          erase_prompt_box(2);
          moveto(tempx,tempy);
          is[0]='q';          
          goto endWire_move;
      }
      else if (is[0]=='a') wires_to_move=tw;
      else if (is[0]=='p'){
         sprintf(textb[0]," %% of total wires:"); 
	 outtext(textb[0]);
	 input_string(3,1);
	 if (is[0]=='q') goto start;
	 if (is[0]!=13 && atoi(is)>0 && atoi(is)<100)
					  wires_to_move=atoi(is)*tw/100;
      }
      else if (is[0]=='n'){
	 outtext(" number of wires:");
	 input_string(4,1);
	 if (is[0]=='q') goto start;
	 if (is[0]!=13 && atoi(is)>0 && atoi(is)<tw) wires_to_move=atoi(is);

      }
      if (from_original_wiring==1 && what=='s'){ 
          mutate_wiring=2; /*restore original before rewiring*/
          if (wires_to_move==0) wires_to_move=1;
      }

      erase_prompt_box(2);
      moveto(tempx,tempy);
   }
   /*move one or more wires at random*/
   if (what=='m'){
      if (wires_to_move==tw){
	 for (poss=0;poss<=lineL-1;poss++)
			   randomly_wire_cell(poss,lineL-1);
      }
      else{
	 for (wire=1;wire<=wires_to_move;wire++){
	    poss=myrand()%lineL;
            /*fprintf(stderr,"\n%d",poss);*/
	    wiring[poss][myrand()%nhoodm[poss]]=myrand()%lineL;
	 }
      }
   }
 endWire_move:
   setcolor(tempcolor);
   return(color1);
}

/***** run CA forwards or backwards, (single basin or subtree) 19 June 1993 ********/
void select_foreward_back(void){
 signed int xbox;

   istr_node_count=0;//for istr_graph
   //fprintf(stderr,"\nselect_foreward_back");
 
   moveto(memory_box(0,NULL)+vgax(3),vgay(3));
   setcolor(lightred);
   outtext("accept defaults-d");
   setcolor(white);
   seq_update=0;
  start:
   is[0]=0;
   is[1]=0;
   exhaustive_testing=0;
   Ham_bias=0;
   show_ss_matrixF=0;
   limitcheck=Maxu-1; /*was 10000*/
   direction='f';
   setcolor(white);
   xbox=draw_prompt_box(2);
   outtext("backward for subtree-b, single basin of attraction-(def):");
   moveto(xbox,gety+CHeight);
   if (stp) outtext("space-time patterns only -S, tog backwards stp (now ON)-s/+s:");
   else outtext("space-time patterns only -S, tog backwards stp (now OFF)-s/+s:");
   input_string(2,0);
   if (is[0]=='q' || is[0]=='d') return;
   if (is[0]=='b'){ 
      direction='b';   /*backward, subtree only*/
      if (is[1]=='s') stp=abs(stp-1); /*toggle backwards stp*/
   }
   else if (is[0]=='S'){ /*abandon subtree or basin, run stp forward*/
       erase_prompt_box(2);
       direction='f';
       forward_only=1; 
       limitcheck=0;
       show_ss_matrixF=1;
   }

   else{
      if (is[0]=='s' || is[1]=='s') stp=abs(stp-1);  /*toggle backwards stp*/
      direction='f';   /*forward -- looking for attractor*/
      see_ppstack=0;
      sprintf(textb[2],"%s","");

      if (/*rulemix==0 &&*/ oned){
         if (nonlocal==0) sprintf(textb[4],"nonlocal-x ");
         else sprintf(textb[4],"local-x ");
      }
      else sprintf(textb[4],"");

      if (lineL<=max_exh_lu){ /*max_exh_lu depends on value_range*/
	if (NULLboundaries || rangeL) sprintf(textb[3],
                              "%sexh-e rmap-r",textb[4]);
        else sprintf(textb[3],"%sexh-e rmap-r seq-s",textb[4]);
      }
      else sprintf(textb[3],"%s",textb[4]);

      if (nonlocal){
	    sprintf(textb[2],"(nonlocal)");
            if (reorderRBN==1)
	       sprintf(textb[1],
                  "view ppstack-1 +pause-2, reorder(on) tog +R,");
            else if (reorderRBN==0)
	       sprintf(textb[1],
                  "view ppstack-1 +pause-2, reorder(off) tog +R"); 
      }
	 
      else{
	    sprintf(textb[2],"(local)");
	    sprintf(textb[1],"view ppstack-1:");
      }
      if (rangeL) sprintf(textb[0],"single basin %s n=%d-%d, %s",
			  textb[2],startL,endL,textb[3]);
      else sprintf(textb[0],"single basin %s n=%d, %s",
		  textb[2],lineL,textb[3]);
      
      xbox=draw_prompt_box(2);
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);
      outtext(textb[1]);
      outtext(" limit backsteps-b/+b:");
      is[1]=0;
      level_limit=Maxu;
      input_string(2,0);
      if (is[0]=='d'){
	    erase_prompt_box(2);
	    return;
      }
      if (is[0]=='q'){
	    erase_prompt_box(2);
	    goto start;
      }
      if (is[0]=='1') see_ppstack=1;
      if (is[0]=='2') see_ppstack=2; 
      if (((is[0]=='1' || is[0]=='2') && is[1]=='R') || is[0]=='R'){
            if (reorderRBN==1) reorderRBN=0;
            else if (reorderRBN==0) reorderRBN=1;           
      }
 
      if (is[0]=='x' /*&& rulemix==0*/ && oned){
	 if (nonlocal==0) nonlocal=1;
         else if (nonlocal==1){
            unsigned int poss;            
             for (poss=0;poss<=lineL-1;poss++)
                     oneD_local_wire_cell(poss,lineL-1);
              nonlocal=0;
         }
      }    

      else if (lineL<=max_exh_lu){ /*max_exh_lu=depends on value_range*/
	 if (is[0]=='e' || is[0]=='s') exhaustive_testing=1; //e=exh-austive, s=seq-uential
         else if (is[0]=='r') exhaustive_testing=2; //r=random map
         if (is[0]=='s' && NULLboundaries==0 && rangeL==0){
               erase_prompt_box(2);
	       set_seq_update();
	 }		             
      }
	 
      erase_prompt_box(2);
      if (neutral_order==0 && (is[0]=='b' || is[1]=='b')){
         draw_prompt_box(1);
	 /*if (istr_graph==1) outtext(
	    "enter max backward steps (istr-graph bare attractor-1), def-nolimit):");
	 else*/
	 outtext("enter max backward steps (bare attractor-0), def-nolimit):");
         input_string(5,0);
         //if (atoi(is)>0) def=Maxu
         level_limit=atoi(is);
	 //must be at least one for istr-graph, otherwize crash
	 //if (istr_graph==1 && level_limit==0) level_limit=1; 
         //fprintf(stderr,"\ndrpara1 level_limit=%d",level_limit);
      }      
   }
   if (direction=='f' && limitcheck==0) forward_only_para();
   if (is[0]=='q') goto start;
}

/****************** forward only parameters ********************/
void forward_only_para(void){
   unsigned int xbox;
   char dup_net;
   double tempx;

   /*start:*/
      diff_plot=0;
      reverse_value_order=0; /*for Antonio's rules*/
      single_entropy=0;      
      p_order=0; /*partial-order, upadate sequential rand subsets of the network*/
      porder_min=1;
      porder_max=lineL;

      
      /*rand_seed_percent=100;*/ 
      /*no longer global - fully random seed setting, % can be revised*/
      exhaustive_testing=0;
      seq_update=0;
      if (oned==1) scale=1; /*def cell scale for 1d*/

      moveto(memory_box(0,NULL)+vgax(3),vgay(3));
      setcolor(lightred);
      //outtext("accept defaults-d");
      outtext("space-time parameters");
      setcolor(white);

      gens=10;
      frozen_gens=20;
      stpgraph=2;  /*default show look-up frequency*/
      if (nhood_mixed || twod || threed) stpgraph=0;
      ncolor=0;  /*colors acc to nhoods*/
      ex_device=0; /*send/receive char to external device*/ 
      ittpause=stppause=0;
      show_ss_matrixF=0;
      if (show_ss_matrix==1) show_ss_matrixF=1;
      else show_ss_matrixF=0;
      att_hist=0;
      stp=1; /*show space-time pattern*/

   skip1:
      sprintf(textb[0],"accept all space-time pattern defaults-d");
      sprintf(textb[1],"revise from:  ");  
      sprintf(textb[2],
	"start/misc-ret boundaries-b updating-u ");
      if (value_range==2){
	 sprintf(textb[3], /*skeletons for binary systems only*/
	     "entropy-e damage-m attractors-a skeletons-s:");
      }
      else {
         sprintf(textb[3],
	     "entropy-e damage-m attractors-a:");
      }
      xbox=draw_prompt_box(3);
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);
      setcolor(lightred);   
      outtext(textb[1]);
      setcolor(white);
      tempx=getx;
      moveto(tempx,gety);
      outtext(textb[2]);
      moveto(tempx,gety+CHeight);
      outtext(textb[3]);
      input_string(1,0);
      erase_prompt_box(3);

      moveto(memory_box(0,NULL)+vgax(3),vgay(3));
      setcolor(lightred);
      outtext("accept defaults-d");
      setcolor(white);

      if (is[0]=='q' && tot_only==1){
	erase_memory_box(0);
	 moveto(xtext,gety);
         return;
      }
      else if (is[0]=='q' || is[0]=='d') return;
      else if (is[0]=='b') goto skip_boundaries;
      else if (is[0]=='u') goto skip_updating;
      else if (is[0]=='e') goto skip_entropy;
      else if (is[0]=='m') goto skip_damage;
      else if (is[0]=='a' || //attractor histogram
	      (is[0]=='s' && value_range==2)) //skeleton histogram
               goto skip_attractors;
      
      
      /* * * * * * * * * * cellcolor  * * * * * * * * * */
      sprintf(textb[0],
	"cellcolor: nhood-n value-(def):");
      draw_prompt_box(1);
      setcolor(lightred);
      outtext("start/misc: ");
      setcolor(white);
      outtext(textb[0]);
      input_string(1,0);
      if (is[0]=='q')  goto skip1;      
      else if (is[0]=='d') return;
      else if (is[0]=='n') ncolor=1;
     
       
      /* * * * * *  state-space matrix-y, return map * * * * * * * */
      /*keys same as on-the-fly*/
      sprintf(textb[0],"state-space matrix-y, return map-D:");
      draw_prompt_box(1);
      outtext(textb[0]);
      input_string(1,0);
      if (is[0]=='q')  goto skip1;
      else if (is[0]=='d') return;
      //if (is[0]=='m') show_ss_matrixF=1;
      //if (is[0]=='r') show_ss_matrixF='r';
      if (is[0]=='y') show_ss_matrixF=1; 
      if (is[0]=='D') show_ss_matrixF='r';
  
      /*this option too obscure -- superseded*/
      /*if (lineL<=max_exh_lu){ //max_exh_lu depends on value_range, set in main
	 sprintf(textb[0],"random map-r:");
	 draw_prompt_box(1);
	 outtext(textb[0]);
	 input_string(1,0);
	 if (is[0]=='q')  goto skip2;
         else if (is[0]=='d') return;
	 else if (is[0]=='r'){ 
             exhaustive_testing=2;
             ncolor=0;  //colors acc to nhoods
         }
       }*/

      /* * * * * * * * * * frozen geneeration size * * * * * * * * * */
      sprintf(textb[0] ,
	 "new 'frozen' generation size (min 2, now %d):",frozen_gens);
      draw_prompt_box(1);
      outtext(textb[0]);
      input_string(4,0);

      if (is[0]=='q') goto skip1;
      else if (is[0]=='d') return;
      else if (is[0]!=13 && atoi(is)>=2) frozen_gens=atoi(is);
      
      /* * * * * * * * * * cellscale  * * * * * * * * * */
      if (scale==1) sprintf(textb[0]," cellscale (now %d pixel):",scale);
      else sprintf(textb[0]," cellscale (now %d pixels):",scale);
      draw_prompt_box(1); 
      outtext(textb[0]);
      input_string(2,0);
      if (is[0]=='q') goto skip1;
      else if (is[0]=='d') return;
      else if (is[0]!=13 && atoi(is)>0) scale=atoi(is);

      /* * * * * * * * * * 1d 2d 3d  * * * * * * * * * */
      /*run STP in different dimension from native dimention*/
      { char this_d;
         if (oned==1){ 
           d_mode=1;
            this_d=1;
         }
         else if (twod==2){ 
            d_mode=2;
            this_d=2;
         }
         else if (threed){ 
            d_mode=4;
            this_d=3;
         }
         draw_prompt_box(1);
      
         sprintf(textb[0],
            "%dd network, show STP in 1d-1 2d-2 3d-3 (def %dd):",
                                                      this_d,this_d);
         outtext(textb[0]);
         input_string(1,0);
         if (is[0]=='q')  goto skip1;
         else if (is[0]=='d') return;
         else if (is[0]=='1') d_mode=1;
         else if (is[0]=='2') d_mode=2;
         else if (is[0]=='3') d_mode=4;      
      }
      
      /* * * * * * * * * * scrolling  * * * * * * * * * */
      if (d_mode==1 && oned){ /*scroll 1d*/
         scrolling=1;
         sprintf(textb[0],"sweep space-time pattern-s, scroll-def: ");
         draw_prompt_box(1);
         outtext(textb[0]);
         input_string(1,0);
         erase_prompt_box(1);
         if (is[0]=='q')  goto skip1;
         else if (is[0]=='d') return;
         else if (is[0]=='s') scrolling=0;
      }

      /* * * * * scrolling 2d -- do this on-the-fly, not here  * * * * * * */
      if (d_mode==2 && twod){
         scrolling=0;
         /*sprintf(textb[0],"scroll 2d space-time pattern-s, no-scroll-def: ");
         draw_prompt_box(1);
         outtext(textb[0]);
         input_string(1,0);
         erase_prompt_box(1);
         if (is[0]=='q')  goto skip1;
         else if (is[0]=='d') return;
         else if (is[0]=='s') scrolling=1;*/
      }

      /* * * * * * * * * * step and pause * * * * * * * * * */
      draw_prompt_box(1);
      outtext("step-s, pause screen full-p, or enter time-step (no pause-def):");
      input_string(5,0);
      if (is[0]=='q')  goto skip1;
      else if (is[0]=='d') return;
      else if (is[0]=='p') stppause=1;
      else if (is[0]=='s') stppause=-1;
      else if (is[0]!=13 && atol(is)>0){ 
         ittpause=atoi(is);
         stppause=1;
      }

      /* * * * slowdown stp - same as for attractor basins  * * * * */
      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]=='q')  goto skip1;
      else if (is[0]=='d') return;
      else if (is[0]==13) pre_speed=0;
      else if (atol(is)>1){ 
              slowfactor=atol(is);
              pre_speed=slowfactor*500; /*pre_speed is copied to it.stp_speed in forx.c*/
      }
   
      /* * * * * * * * * * glider_rules order * * * * * * * * * */
      if (no_glider_rules[value_range][nhoodm[0]]>=1){
         signed int g_no;
            glider_rule_order=0;
	    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);
            erase_prompt_box(2);
            if (is[0]=='q')  goto skip1;
	    else if (is[0]=='d') return;
	    else if (atoi(is)>=1 && atoi(is)<=g_no)  
                                  glider_rule_order=atoi(is)-1;
      }

      /* * * * * * * * * * invert kcode * * * * * * * * * */
      if (tot_only && totalistic==2){
        sprintf(textb[0],
	  "invert kcode value order -i:");
        draw_prompt_box(1);
        outtext(textb[0]);
        input_string(1,0);
        if (is[0]=='q')  goto skip1;
        else if (is[0]=='d') return;
        else if (is[0]=='i') reverse_value_order=1;
      }      
   
      /* * * * ** * * external device - not inplimented * * * * */
      /*ex_device=0;
      sprintf(textb[0],
	"send/receive char to external device-e:");
      draw_prompt_box(1);
      outtext(textb[0]);
      input_string(1,0);
      if (is[0]=='q')  goto skip1;      
      else if (is[0]=='d') return;
      else if (is[0]=='e') ex_device=1;*/


      /* * * * * * * * * * * boundary conditions * * * * */
      /*set NULLboudary conditions forwards only, for 1d,2d,3d, 
               also 1d only option for basins*/
   skip_boundaries:
          if (NULLboundaries==1) sprintf(textb[0],
	         "Null  boundaries, set Periodic-P:");
          else sprintf(textb[0],"Periodic boundaries, set Null-N:");
          
	  draw_prompt_box(1);
          setcolor(lightred);
          outtext("boundaries: ");
          setcolor(white);
	  outtext(textb[0]);
          input_string(1,0);
          if (is[0]=='N'){
             NULLboundaries=1;
             dontcompress=1;
          }
          else if (is[0]=='P'){
             NULLboundaries=0;
             dontcompress=0;
          }
	  erase_prompt_box(1);
	  if (is[0]=='q')  goto skip1;
	  else if (is[0]=='d') return;
   

      /* * * * * * * * * * * updating * * * * * * * * * * */
   skip_updating:
      
      draw_prompt_box(1);
      setcolor(lightred);
      outtext("updating: ");
      setcolor(white);
      outtext("sequential-s, partial-order-p, probabilistic-def:");
      input_string(1,0);
      if (is[0]=='q')  goto skip1;
      else if (is[0]=='d') return;
      else if (is[0]=='s') set_seq_update();
      else if (is[0]=='p'){
	signed int stringlength;
         sprintf(textb[0],"%d",lineL);
         stringlength=strlen(textb[0]);
         draw_prompt_box(1);         
	 sprintf(textb[0],
           "partial order updating: update subset limits (def 1:%d): min:",lineL);
         outtext(textb[0]);
	 input_string(stringlength,1);
         if (is[0]=='q')  goto skip_updating;
         else if (is[0]=='d') return;
	 else if (atoi(is)>=1 && atoi(is)<=lineL) porder_min=atoi(is);
         sprintf(textb[0]," max:");
         outtext(textb[0]);
         input_string(stringlength,1);
         if (is[0]=='q')  goto skip_updating;
         else if (is[0]=='d') return;
         else if (atoi(is)>=porder_min && atoi(is)<=lineL) porder_max=atoi(is);
         p_order=1;    
      }
      
      /*set update probability*/
           xbox=draw_prompt_box(2);
           sprintf(textb[0],
             "update prob (def %.2f%%) 0-100:", update_prob*100);
           outtext(textb[0]);
           input_string(7,0);
           if (is[0]=='q'){
	      erase_prompt_box(2);
              goto skip_updating;
           }    
           else if ((isdigit(is[0]) || is[0]=='.') &&
                      atof(is)>=0 && atof(is)<100){
	      update_prob= temp_update_prob=atof(is)/100;
           }
           /*set output probability*/
            moveto(xbox,gety+CHeight);
            sprintf(textb[0], /*prob to output correctly*/
                "output prob (def %.2f%%) 0-100:", out_prob*100);
            outtext(textb[0]);
            input_string(7,0);
            erase_prompt_box(2);
            if (is[0]=='q')  goto skip_updating;
            else if (is[0]=='d') return;	    
            else if ((isdigit(is[0]) || is[0]=='.') &&
                      atof(is)>=0 && atof(is)<100){
	         out_prob=temp_out_prob=atof(is)/100;
            } 
      
     
      /* * * * * * * * * * * entropy * * * * * * * * * * */
   skip_entropy:
        is[0]=is[1]=0;
	set_iso_input_histogram=0;
         /*pattern density-1, option removed here, can be toggled on-the-fly*/
	if (twod || threed || nhood_mixed){
	      sprintf(textb[0],
		      "none-(def) pattern-density-p");
	      if (iso_rule_allowed==1 && iso_tablemax>0)
		  sprintf(textb[1],"input-frequency/entropy-e, iso-i:");
	      else sprintf(textb[1],"input-frequency/entropy -e:");
	      
	 }                 
	 else{
	      sprintf(textb[0],
	      "none-n,  pattern-density -p");
	      if (iso_rule_allowed==1 && iso_tablemax>0)
	          sprintf(textb[1],"input-frequency/entropy-(def) iso-i:");
	      else sprintf(textb[1],"input-frequency/entropy-(def):");
	 }

         xbox=draw_prompt_box(2);
         setcolor(lightred);
         outtext("entropy/density: ");
         setcolor(white);
	 outtext(textb[0]);
	 moveto(xbox,gety+CHeight);
	 outtext(textb[1]);
	 input_string(1,0);
	 erase_prompt_box(2);
	 if (is[0]=='q') goto skip1;
	 else if (is[0]=='d') return;
         else if (is[0]=='n') stpgraph=0;
	 else if (is[0]==13 && (twod || threed || nhood_mixed)) stpgraph=0;
	 else if (is[0]=='i' && iso_rule_allowed==1 && iso_tablemax>0){
            /*input-histogran according to iso-rule in forx.c*/
	    set_iso_input_histogram=1;
	    stpgraph=2;
	 }    
         else if (is[0]==13 || is[0]=='e') stpgraph=2;
         else if (is[0]=='p') stpgraph=1;
 
	 if (nhood_mixed && stpgraph>1) single_entropy=1;
	 erase_prompt_box(1);
     
	 if (stpgraph>0){
            start_twod_ent: 
             if (!(nhood_mixed && stpgraph>1)){
                single_entropy=0;
                draw_prompt_box(1);
	        outtext("single-s all-(def):");
	        input_string(1,0);
	        if (is[0]=='q') goto skip_entropy;
	        else if (is[0]=='d') return;
	        else if (is[0]=='s') single_entropy=1;
	     }
	     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]=='q') goto skip_entropy;
	          else if (is[0]=='d') return;
	          else 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]=='q') goto  start_twod_ent;
	          else if (is[0]=='d') return;
	          else 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]=='d') return;
	          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]=='d') return;
	             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;
		  erase_prompt_box(2);
	       } 
	    }
            /* * * * * * * * * * * 'analysis' generation size * * * * * * * * * * */
            if (single_entropy==1) gens=500;
	    sprintf(textb[0],
	      "enter new 'analysis' generation size (min 1, now %d):",gens);
	    draw_prompt_box(1);
	    outtext(textb[0]);
	    input_string(5,0);
	    if (is[0]=='q') goto skip_entropy;
	    else if (is[0]=='d') return;
	    else if (is[0]!=13 && atoi(is)>0) gens=atoi(is);
	 }

        
      /* * * * * * * * * * * damage * * * * * * * * * * */
    skip_damage:  
      /*show difference betwwen two equal size/shape  networks*/
      /*if even length 1d or even width 2d*/      
      diff_plot=0;
      if (threed==0){ /*1d and 2d only, and network bigger than 16*/
         xbox=draw_prompt_box(2);
         setcolor(lightred);
         outtext("damage: ");
         setcolor(white);
         outtext("show difference between 2 networks");
         moveto(xbox,gety+CHeight);
         outtext("keep damage-f, don't keep-F, histograms: actual-a bins-b:");
         input_string(1,0);
         erase_prompt_box(2);
         if (is[0]=='q') goto skip1;
         if (is[0]=='f') diff_plot=2;
         else if (is[0]=='a') diff_plot=3;
         else if (is[0]=='b') diff_plot=4;
         else if (is[0]=='F') diff_plot=1;

         if (lineL<Maxu/2 && !loc_twod_fonly){
            dup_net=0;
	    draw_prompt_box(1);
	    outtext("duplicate network and seed-y:");
	    input_string(1,0);	   
	    erase_prompt_box(1);
	    if (is[0]=='q') goto skip_damage;
	    if (is[0]=='y'){
	       dup_net=1;
	       duplicate_net();
	    }
	    else if (is[0]=='d') return;
         }

         if ((oned && lineL%2!=0) || (twod && i2d%2!=0)){
	    if (diff_plot && dup_net==0){
               draw_prompt_box(1);
	       outtext("can't divide odd width network, cont-ret:");
	       input_string(1,0);	
               diff_plot=0;
            }
         }
	 return;
      }

      /* * * * * * * * attractors or skeletons* * * * * * * * * * */
    skip_attractors:
      if (diff_plot==0){
        char temp_a_s;
	 draw_prompt_box(1);
         setcolor(lightred);
         bin_trans=0;
	  
         if (is[0]=='s'){ 
             outtext("skeletons:");
             temp_a_s='s';
         }
         else if (is[0]=='a'){  /*default attractor histogram*/
             outtext("attractors:");
             temp_a_s='a';
         }
         setcolor(white);
         if (temp_a_s=='s') 
             outtext(" histogram, cancel-q, cont-ret:");
         else if (temp_a_s=='a')
	   //outtext(" histogram, cancel-q, trans:data/bins-t/b, cont-ret:");
	   /*trans:bins-b, to sort trans length into bins -- show in terminal, but abandoned*/
           outtext(" histogram, cancel-q, trans:data-t, cont-ret:");
	 input_string(1,0);
	 if (is[0]=='q')  goto skip1;
	 else if (is[0]=='d') return;
	 if (temp_a_s=='a'){
            stpgraph=0;
            att_hist=1;
            if (is[0]=='t') att_trans=1;
	    else if (is[0]=='b'){ /*trans:bins-b, to sort trans length into bins -- show in terminal, but abandoned*/
	      signed int zb;
	       bin_trans=1;
	       for (zb=0;zb<=10;zb++) transient_bin[zb]=0;//reset bins to zero
	    }   
            att_seed_dens=0;
            if (value_range==2){          
               draw_prompt_box(1);
               outtext(
                   "include seed density data for all-0/1s point attractors-a:");
               input_string(1,0);
               if (is[0]=='q')  goto skip_attractors ;
	       else if (is[0]=='d') return;
               if (is[0]=='a') att_seed_dens=1;
            }
         }
	 else if (temp_a_s=='s'){
            stpgraph=0;
	    att_hist=2;
            att_trans=0;
            ncolor=0;
	 }
      }   
}
/******* set up random sequence for sequential update  **********/ 
void setup_int_sequence(void){
    unsigned int poss,try,tickoffbytes,z;
    unsigned long checkindex;
    char *seq_tickoff,dir;
    signed int xbox,seq_tempy,rows;
    
          if (lineL>limitL) rows=Maxy/CHeight-4;         
          else rows=5;

        start:	     	  
	  tickoffbytes=(unsigned int)ceil( (double)lineL/8);
          if ((seq_tickoff=(char *)calloc(tickoffbytes,sizeof(char)))
				     ==NULL) outof_memory("seq_tickoff");        
	  seq_update=3;
          
          xbox=draw_prompt_box(rows);

          sprintf(textb[0],
               "enter cell index (no repeats) 0-%d or rnd-(def) back-b",lineL-1);
          outtext(textb[0]);
          moveto(xbox,gety+CHeight);
          seq_tempy=gety;          

	  for (poss=0;poss<=lineL-1;poss++){
             setfillstyle(SOLID_FILL,black);
             bar(xbox,gety,Maxx-3,gety+CHeight*(rows-1));
             /*show sequence so far*/
             moveto(xbox+CWidth*10,gety);             
             
             for (z=0;z<=L;z++){
                if (getx>=Maxx-CWidth*3) moveto(xbox,gety+CHeight);
		if (z<=poss-1){
                    sprintf(textb[2],"%d  ",seq_order[z]);
                    outtext(textb[2]);
                }
                else outtext("*  ");          
             }

             moveto(xbox,seq_tempy);
             sprintf(textb[1],"update %d: ",poss);
             outtext(textb[1]);
	    
             input_string(2,0);
  
             if (is[0]=='q') break;
             
	     if (is[0]==13) {
                try=myrand()%lineL;
	        dir=(myrand()%2)-1; /*choose -1 or 1 at random*/
	        if (dir==0) dir=1;
	     
	       try_again:	     
	        if (get_bit(seq_tickoff,try)==0){ /*if not used*/
		    seq_order[poss]=try;
		    set_bit1(seq_tickoff,try);
	        }
                else {		 
		    try=try+dir; /*randomly inc or dec index by one*/
		    if (try==lineL) try=0;
		    else if (try==Maxu) try=L;
                    goto try_again;
	        }            
             }
                   
             else if (is[0]!='b' && atoi(is)>=0 && atoi(is)<=L){
                try=atoi(is); 
	        if (get_bit(seq_tickoff,try)==0){                    
                    seq_order[poss]=try;
		    set_bit1(seq_tickoff,try);
	        } 
                else {
                   poss-=1;                
                   continue;
                }                  
	     }
             else if (is[0]=='b'){
	        if (poss>0){                  
                   set_bit0(seq_tickoff,seq_order[poss-1]);
                   poss-=2;
                   is[0]=0;                
                   continue;
	        }
                else{
                   free(seq_tickoff);
                   goto start;
                }
             }         
	  }
          if (is[0]=='q') goto skip_int;

          xbox=draw_prompt_box(3);
          sprintf(textb[0],
               "sequence complete 0-%d",lineL-1);
          outtext(textb[0]);
          moveto(xbox,gety+CHeight);

          setfillstyle(SOLID_FILL,black);
          bar(getx,gety,Maxx-3,gety+CHeight*(rows-1));
          for (poss=0;poss<=L;poss++){
              /*show final sequence*/
              if (getx>=Maxx-CWidth*3) moveto(xbox,gety+CHeight);
              sprintf(textb[2],"%d  ",seq_order[poss]);
              outtext(textb[2]);               
          }
          
          if (lineL<=12){
	     checkindex=order_to_index(seq_order,lineL);
             sprintf(textb[0]," (dec)=%lu",checkindex);
             outtext(textb[0]);
             sprintf(textb[0]," (hex)=%lx",checkindex);
             outtext(textb[0]);
          }
        
          moveto(xbox,gety+CHeight);          
          sprintf(textb[0],
	            "save/load-s/l reselect-r cont-ret:");

          outtext(textb[0]);
          input_string(1,0);

         skip_int:
          if (is[0]=='q') goto end_int_seq;
          else if (is[0]=='r'){
	     free(seq_tickoff);
	     goto start;
	  }	 
          else if (is[0]=='s' || is[0]=='l')
                            load_save_order(is[0]);
			    
         end_int_seq:         
          free(seq_tickoff);      
          erase_prompt_box(rows);
}

/******* set up random sequence for sequential update  **********/ 
void setup_random_sequence(void){
    unsigned int poss,zu,try,rows,startindex,endposs,tickoffbytes;
    char *seq_tickoff,dir;
    signed int tempx,tempy,xbox;
    unsigned long checkindex;
              
          if (lineL>limitL) rows=Maxy/CHeight-4;         
          else rows=5;
          get_prompt_box(8,rows);

        start:	     	  
	  tickoffbytes=(unsigned int)ceil( (double)lineL/8);
          if ((seq_tickoff=(char *)calloc(tickoffbytes,sizeof(char)))
				     ==NULL) outof_memory("seq_tickoff");
	  seq_update=3;
	  for (poss=0;poss<=L;poss++){
             try=myrand()%lineL;
	     dir=(myrand()%2)-1; /*choose -1 or 1 at random*/
	     if (dir==0) dir=1;
	     
	    try_again:	     
	     if (get_bit(seq_tickoff,try)==0){ /*if not used*/
		 seq_order[poss]=try;
		 set_bit1(seq_tickoff,try);
	     }
             else {		 
		 try=try+dir; /*randomly inc or dec index by one*/
		 if (try==lineL) try=0;
		 else if (try==Maxu) try=L;
                 goto try_again;
	     }             
	  }
         	  
          startindex=0;
          endposs=lineL-1;

	  tempx=getx;
	  tempy=gety;

         startjump:
          xbox=draw_prompt_box(rows);
          if (forward_only==0) sprintf(textb[0],
               "random order, n=%d",lineL);
	  else  sprintf(textb[0],
               "random order, n=%d  maxindex=%d",
                     lineL,lineL-1);
          outtext(textb[0]);   
          moveto(xbox,gety+CHeight);
          for (poss=startindex; poss<=lineL-1;poss++){
             if (getx>Maxx-CWidth*5){
	        moveto(xbox,gety+CHeight);
	        if (gety>=rows*CHeight-3*CHeight){
	           moveto(xbox,gety-CHeight);
	           break;
	        }
             }
             sprintf(textb[0],"%d ",seq_order[poss]);
             outtext(textb[0]);
          }

          if (lineL<=12){
	     checkindex=order_to_index(seq_order,lineL);
             sprintf(textb[0]," (dec)=%lu",checkindex);
             outtext(textb[0]);
             sprintf(textb[0]," (hex)=%lx",checkindex);
             outtext(textb[0]);
          }

          if (poss==Maxu) endposs=0;
	  else endposs=poss-1;
          moveto(xbox,gety+CHeight);
          sprintf(textb[0],
		  "order-tag shown from %d-%d",startindex,endposs);
          outtext(textb[0]);
          moveto(xbox,gety+CHeight);

          if (lineL<=limitL) sprintf(textb[0],
	           "save/load-s/l >-f <-b re-order-r cont-ret:");
          else if (poss!=Maxu) sprintf(textb[0],
	           "save/load-s/l >-f <-b more-m jump-j re-order-r cont-ret:");
          else sprintf(textb[0],
	            "save/load-s/l >-f <-b jump-j re-order-r cont-ret:");

          outtext(textb[0]);
          input_string(1,0);
          if (is[0]=='q') goto end_rand_seq;

	  /*{
              free(seq_tickoff);
              erase_prompt_box(rows);
              //set_seq_update();
              return;
	      }*/

          else if (is[0]=='f'){ /*forward order*/
	     erase_prompt_box(rows);
             for (zu=0;zu<=L;zu++) seq_order[zu]=zu;
             startindex=0;
	     goto startjump;
	  }

          else if (is[0]=='b'){ /*backward order*/
	     erase_prompt_box(rows);
             for (zu=0;zu<=L;zu++) seq_order[zu]=L-zu;
             startindex=0; 
	     goto startjump;
	  }

          else if (is[0]=='r'){
	     erase_prompt_box(rows);
	     free(seq_tickoff);
	     goto start;
	  }	
          else if (is[0]=='s' || is[0]=='l'){             
             load_save_order(is[0]);	
	     goto startjump;             
          }
          else if (forward_only){
             if (is[0]=='j' && lineL>limitL){ /*jump to new cell poss*/
                setfillstyle(SOLID_FILL,black);
                bar(xbox,gety+2,Maxx-3,gety+CHeight+2);
                sprintf(textb[0],"jump to index (%d-0):",lineL-1);
                moveto(xbox,gety);
                outtext(textb[0]);

                sprintf(textb[0],"%d",lineL-1);
                input_string(strlen(textb[0]),0);

                if (atoi(is)>=0 && atoi(is)<=lineL-1){
	           startindex=atoi(is);
	           erase_prompt_box(rows);
	           goto startjump;
                }
              }
              /*continue to next cell poss*/
              else if (is[0]=='m' && poss!=Maxu){ 
                 startindex=poss;
                 erase_prompt_box(rows);
                 goto startjump;
              }
	   }
         end_rand_seq:
           free(seq_tickoff);
           erase_prompt_box(rows);
           moveto(tempx,tempy);           
}

/************************* save, load, sequence order ********************/
void load_save_order(char load_save){ 
    unsigned int filebytes;
    char file_ret;
    signed int fid,tempx1,tempy1;

             tempx1=getx;
             tempy1=gety;            
             if (load_save=='l') sprintf(textb[4],"LOAD ");
            
             else if (load_save=='s') sprintf(textb[4],"SAVE ");
                      
             file_ret=select_filename(textb[4],
	                  "ORDER-DATA", "*.ord","my_order"); 
             if (file_ret=='q') goto endFunk;
             else{
                if (load_save=='l'){
		   fid=myopen(filename,0,0);	    
                   filebytes= filelength(fid);
		   if ( filebytes!=lineL*sizeof(unsigned int)){
		      draw_prompt_box(1);
		      sprintf(textb[0],
			"filesize(%d)!=netsize(%d), cont-ret",
			  filebytes/(unsigned int)sizeof(unsigned int),lineL);
		      input_string(1,0);
                      close(fid);
		      goto endFunk;
		   }
	        }
	        if (load_save=='s'){
		   fid=myopen(filename,1,0);	           
                }
		if (fid==-1){
		      file_error(filename);
                      close(fid);
	              goto endFunk;
	        }
		if (load_save=='s')
                   vret=write(fid,seq_order,lineL*sizeof(unsigned int));
                else if (load_save=='l') 
                   vret=read(fid,seq_order,lineL*sizeof(unsigned int));
                close(fid);
             }
             endFunk:             
             moveto(tempx1,tempy1);
}

/**************  set up all possible orders  *****************/ 
void set_all_orders(void){
  
   char indexjump;
   unsigned int *order,z;
   unsigned char tempcolor;
   unsigned long index,maxindex=0,startindex=0,checkindex;
   signed int rows,xbox,tempx,tempy;
   char order_seed_set=0;
   
    tempx=getx;
    tempy=gety;
    maxindex=fact((char)lineL)-1; /*factorial of size*/

    /*lineL=12 is the limit for unsigned long*/
    /*fprintf(stderr,"Maxlu=%lu",Maxlu);  
    for (z=0;z<=16;z++){ 
       fprintf(stderr,"\n%d!=%lu",z,fact((char)z));
    }*/

    /*allocate memory for order[index]*/
    if ((order=(unsigned int *)calloc(lineL,sizeof(unsigned int)))
			  ==NULL) outof_memory("order");

    index_to_order(0,order,lineL); /*default order is forward*/

   startjump:
    if (!indexjump) startindex=0;
    indexjump=0;
    rows=Maxy/CHeight-4;
    
    xbox=draw_prompt_box(rows);
    sprintf(textb[0],
        "all possible orders n=%d, %lu-%lu",
	                             lineL,startindex,maxindex);
    outtext(textb[0]);   
    moveto(xbox,gety+CHeight);
        
    outtext("dec  -  order-tag  -  hex");   
    moveto(xbox,gety+CHeight);
    
    for (index=startindex;index<=maxindex;index++){
       
       if (gety>=Maxy-vgay(20)-4*CHeight){
          moveto(xbox,gety-CHeight);
	  break;
       }
       sprintf(textb[0],"%lu -   ",index);
       outtext(textb[0]);

       index_to_order(index,order,lineL);

       for (z=0;z<=lineL-1;z++){
	   sprintf(textb[0],"%1x",order[z]);
           if (z%2==0){ /*alternate colors*/
	      tempcolor=getcolor();
	      setcolor(lightred);
	      outtext(textb[0]);
	      setcolor(tempcolor);
           }
           else outtext(textb[0]);
       }

       checkindex=order_to_index(order,lineL);
       sprintf(textb[0],"   - %lx",checkindex);
       outtext(textb[0]);
       moveto(xbox,gety+CHeight);
    }          
    moveto(xbox,gety+CHeight);
    /*     
    if (index<maxindex) sprintf(textb[0],
	           "jump/copy-j orderseed-s accept-a more-ret:");
    else sprintf(textb[0],"jump/copy-j orderseed-s accept-a top-ret:");
    */
    if (index<maxindex) sprintf(textb[0],
	           "jump/copy-j accept-a more-ret:");
    else sprintf(textb[0],"jump/copy-j accept-a top-ret:");
    
    outtext(textb[0]);
    input_string(1,0);

    if (is[0]=='q'){
       erase_prompt_box(rows);
       moveto(tempx,tempy);
       free(order);
       return;
    }
    else if (is[0]=='a'){
       if (order_seed_set==1) order_seed_set=0;
       else index_to_order(startindex,seq_order,lineL);
    } 
    else if (is[0]=='j'){
       setfillstyle(SOLID_FILL,black);
       bar(xbox,gety+2,Maxx-3,gety+CHeight+2);
       sprintf(textb[0],"select by index (0-%lu):",maxindex);
       moveto(xbox,gety);
       outtext(textb[0]);
       sprintf(textb[0],"%lu",maxindex);
       input_string(strlen(textb[0]),0);

       if (atol(is)>=0 && atoi(is)<=maxindex){
	  startindex=atol(is);
          index_to_order(startindex,seq_order,lineL);	  
	  indexjump=1;
	  erase_prompt_box(rows);
          was_changed=1;
	  goto startjump;
       }
    }
    
    /* dont see the point of this so remove Dec 2025
    else if (is[0]=='s'){
          reset_neutral_buffs();
          moveto(Leftx,vgay(315));          
          sprintf(textb[6],"order seed, max=(dec)%lu=(hex)%lx ",
                                              statespace,statespace);
          select_seed(0,bitseed, textb[6], 1);
	  
	  //moveto(memory_box(0,NULL)+2,2);
	     //print_current_state_twod(bitseed,white,1);
	  
	  checkindex=dec_equiv(bitseed,lineL-1);	      
          restore_network_buffs();	  	  
	  index_to_order(checkindex,seq_order,lineL);
	  was_changed=1;
          order_seed_set=1;
	  goto startjump;    
    }*/
    
    else if (is[0]==13){ /*continue to next index*/
       order_seed_set=0;
       if (index<maxindex) startindex=index;
       else startindex=0;
       indexjump=1;
       erase_prompt_box(rows);
       goto startjump;
    }
    erase_prompt_box(rows);
    moveto(tempx,tempy);
    free(order);
}

/******* return the index 0-(lineL(factorial)-1 of a given order ********/  
unsigned long order_to_index(unsigned int *order, unsigned int thislineL){
  unsigned int *posorder,z,z1,z2,M; 
  unsigned long temp,index=0;

    if ((posorder=(unsigned int *)calloc(thislineL,sizeof(unsigned int)))
			     ==NULL) outof_memory("posorder");
    M=thislineL-1;
    for (z1=0;z1<=M;z1++) posorder[z1]=z1;  /* 0.1.2,3 if size=4 */
  
    for (z=0; z<=M-1; z++){
       for (z1=0;z1<=M-z;z1++){
	   if (order[z]==posorder[z1]) break;
       }
       temp=(unsigned long)(z1*fact((char)M-z));
       for (z2=z1;z2<=M-1;z2++) posorder[z2]=posorder[z2+1]; 
       index+=temp;

    }
    free(posorder);
    return(index);
}
/******* assign the order of a given index 0-(lineL(factorial)-1)*********/
void index_to_order(unsigned long index, unsigned int* thisorder,
		                     unsigned int thislineL){
  char notfound;
  //unsigned int *posorder,temp;
  signed int *posorder,temp;
  signed int z,z1,M;
  unsigned long rem;

    M=thislineL-1;
    /*if ((posorder=(unsigned int *)calloc(lineL,sizeof(unsigned int)))
               ==NULL) outof_memory("posorder");*/
    if ((posorder=(signed int *)calloc(lineL,sizeof(unsigned int)))
               ==NULL) outof_memory("posorder");
    for (z1=0;z1<=M;z1++) posorder[z1]=z1;  /* 0.1.2,3 if size=4 */
     
    for (z=0;z<=M;z++){
       if (z<M){
	 //if (z==0) temp=(unsigned int)(index/fact(M-z));
	 //else  temp=(unsigned int)(rem/fact(M-z)); 
          if (z==0) temp=(signed int)(index/fact((char)(M-z)));
	  else  temp=(signed int)(rem/fact((char)(M-z))); 
          thisorder[z]=posorder[temp];
	  rem=index%fact((char)(M-z)); /*modulus, remainder*/	   
          for (z1=temp;z1<=M-1;z1++) posorder[z1]=posorder[z1+1]; 
       }
       else if (z==M){
          /*last order entry*/   
          for (temp=0;temp<=M;temp++){
	     notfound=0;
	     for (z1=0; z1<M; z1++){
                if (temp==thisorder[z1]){
	           notfound=1;
	           break;
	        }
	     }  
	     if (notfound==0) break;
             else continue;	       
           }
           thisorder[z]=temp;
       }
     }
     free(posorder);
}
/********** set the order for sequential updating  *****************/
void set_seq_update(void){
   unsigned int poss;

  start_seq_update:
     seq_update=0;
     if (forward_only==0){
        moveto(memory_box(0,NULL)+vgax(3),vgay(3));
        outtext("backtrack sequential-q");
        setcolor(white);
     }

     draw_prompt_box(1);
     if (forward_only==0) sprintf(textb[1],"");
     else sprintf(textb[1]," rernd-R"); /*for space-time patterns only*/

     if (lineL<=limitL && lineL<=12) sprintf(textb[2]," all-S");
     else sprintf(textb[2],"");
     
     if (lineL<=limitL || forward_only)
	 sprintf(textb[0],"sequential update: >-(def) <-b rnd-r%s set-s%s:",
                               textb[1],textb[2]);
     else sprintf(textb[0],"sequential update: >-(def) <-b rnd-r%s:",textb[1]);
     outtext(textb[0]);
     input_string(1,0);

     if (is[0]=='q'){
        seq_update=0;
        return;
     }                                        
     if (is[0]=='b'){
        seq_update=1; /*default order from right to left, 0 to n-1*/
        for (poss=0;poss<=L;poss++) seq_order[poss]=poss;        
        is[0]=0; 
     }
     else if (is[0]=='r'){
	 seq_update=3;
	 setup_random_sequence();
         if (is[0]=='q') goto start_seq_update;
     }
     /*re-randomize at each time-step*/ 
     else if (is[0]=='R' && forward_only==1) seq_update=4; 
     else if (is[0]=='s' && 
              ((forward_only==0 && lineL<=limitL) || forward_only==1)){        
	 seq_update=3;
	 setup_int_sequence();
         if (is[0]=='q') goto start_seq_update;
     }
     
     /*lineL=12 is the limit for unsigned long*/
     else if (is[0]=='S' && lineL<=limitL && lineL<=12){
	 seq_update=3;
	 set_all_orders();
         if (is[0]=='q') goto start_seq_update;
     }
     else{
         seq_update=2;
         for (poss=0;poss<=L;poss++) seq_order[poss]=L-poss;
     }
     if (forward_only==0) dontcompress=1;
}

/******* duplicate 1d or 2d network in network twice the size **********/ 
void duplicate_net(void){	
 signed int tablemax,tablebytes,
              t_codemax,t_codebytes,
              v_codemax,v_codebytes,
              ii,jj,wirejj;
 char wire,z;
 unsigned int zu;
 char *nhoodm_temp,**carule_temp,**cacode_temp,**v_code_temp,*bitseed_temp;
 unsigned int **wiring_temp;
 //fprintf(stderr,"\n1 rulemix=%d",rulemix);
	 /*double the network by making identical copy*/
         /*copy existing network architecture to temp arrays*/
         /**********************allocate and copy nhood mix**********/
	 if ((nhoodm_temp=(char *)calloc(lineL,sizeof(char)))
				   ==NULL) outof_memory("nhoodm_temp");
         memmove(nhoodm_temp,nhoodm,lineL*sizeof(char));
//fprintf(stderr,"\n -2 ");
         /************** allocate and copy rulemix  ******************/
         /*note: single rule networks have only carule[0] allocated*/
         if (tot_only==0){
           tablemax= (signed int)pow(value_range,(double)nhood)-1;
           tablebytes=(signed int)ceil(value_bits * (double)(tablemax+1)/8);
           /*one rule only*/
           if ((carule_temp=(char**)calloc(1,sizeof(char*)))
				   ==NULL) outof_memory("carule_temp");
           if ((carule_temp[0]=(char *)calloc(tablebytes,sizeof(char)))
				   ==NULL) outof_memory("carule_temp[0]");
           memmove(carule_temp[0],carule[0],tablebytes);
         }
         t_codemax=nhood*(value_range-1); /*max index of codetable*/
         t_codebytes=(signed int)ceil(value_bits * (double)(t_codemax+1)/8);
//fprintf(stderr,"\n tm=%d tb=%d",t_codemax,t_codebytes);
         /*one tcode only*/
         if ((cacode_temp=(char**)calloc(1,sizeof(char*)))
				   ==NULL) outof_memory("cacode_temp");
         if ((cacode_temp[0]=(char *)calloc(t_codebytes,sizeof(char)))
				   ==NULL) outof_memory("cacode_temp[0]");
         memmove(cacode_temp[0],cacode[0],t_codebytes);

         v_codemax=v_tablecodemax[nhood];
         v_codebytes=(signed int) /*bytes for k-code, min=1*/
                       ceil(value_bits * (double)(v_codemax+1)/8);
//fprintf(stderr,"\n vm=%d vb=%d",v_codemax,v_codebytes);
          /*one vcode only*/
         if ((v_code_temp=(char**)calloc(1,sizeof(char*)))
				   ==NULL) outof_memory("v_code_temp");
         if ((v_code_temp[0]=(char *)calloc(v_codebytes,sizeof(char)))
				   ==NULL) outof_memory("v_rule_temp[0]");
         memmove(v_code_temp[0],v_code[0],v_codebytes);

         if (rulemix){
            if (tot_only==0){
               if ((carule_temp=(char**)realloc(carule_temp,
                   lineL*sizeof(char*)))==NULL) outof_memory("carule_temp");
               for (zu=1;zu<=lineL-1;zu++){
                  sprintf(textb[0],"carule_temp[%d]",zu);
                  if ((carule_temp[zu]=(char *)calloc(tablebytes,sizeof(char)))
					==NULL) outof_memory(textb[0]);
                  memmove(carule_temp[zu],carule[zu],tablebytes);
               }
            }
            if ((cacode_temp=(char**)realloc(cacode_temp,
                   lineL*sizeof(char*)))==NULL) outof_memory("cacode_temp");
            for (zu=1;zu<=lineL-1;zu++){
               sprintf(textb[0],"cacode_temp[%d]",zu);
               if ((cacode_temp[zu]=(char *)calloc(t_codebytes,sizeof(char)))
					==NULL) outof_memory(textb[0]);
               memmove(cacode_temp[zu],cacode[zu],t_codebytes);
            }
            if ((v_code_temp=(char**)realloc(v_code_temp,
                   lineL*sizeof(char*)))==NULL) outof_memory("v_code_temp");
            for (zu=1;zu<=lineL-1;zu++){
               sprintf(textb[0],"v_code_temp[%d]",zu);
               if ((v_code_temp[zu]=(char *)calloc(v_codebytes,sizeof(char)))
					==NULL) outof_memory(textb[0]);
               memmove(v_code_temp[zu],v_code[zu],v_codebytes);
            }            
         }
//fprintf(stderr,"\n-3 lineL=%d ",lineL);
         /*************** allocate and copy wiring  **************/  
         /*note: homogenious wiring networks still have all wiring
           specified, except "loc_twod_fonly" */       
         if ((wiring_temp=(unsigned int**)
                     calloc(lineL,sizeof(unsigned int*)))
					==NULL) outof_memory("**wiring_temp");
         for (zu=0;zu<=lineL-1;zu++){
	    sprintf(textb[0],"wiring_temp[%d]",zu);
	    if ((wiring_temp[zu]=
	       (unsigned int*)calloc(nhood,sizeof(unsigned int)))
					==NULL) outof_memory(textb[0]);
	    memmove(wiring_temp[zu],wiring[zu],
	                         nhood*sizeof(unsigned int));
         }

//fprintf(stderr,"\n-4 bytesL=%d ",bytesL );
         /*************** allocate and copy seed  **************/
         if ((bitseed_temp=(char *)calloc(bytesL,sizeof(char)))
					==NULL) outof_memory("bitseed");
         memmove(bitseed_temp,bitseed,bytesL);
//fprintf(stderr,"\n-5 ");
         /******* free current network *********/          
	 if (rulemix){
	    if (tot_only==0) free_mem_rulemix();
	    free_mem_tcodemix();
	 }
	 /***************** added, should not be ness ********/
         free_mem_tcode0();
         if (tot_only==0){
	      free_mem_rule0();
              free_mem_rule0_extra();
              free_mem_all_0s_all_1s_rules();
	      free_mem_iso(nhood);
         }
         /*************************/    
	 free_mem_wiring();
         free(nhoodm);
	 free_mem_CA_states();
//fprintf(stderr,"\n-6 ");
	 /*************** double network size  ************/
	 lineL*=2;
	 L=lineL-1;
	 if (twod){ 
            i2d*=2;
            b_i2d=i2d;
         }
	 /*no of bytes required to contain lineL bits*/
         bytesL=(signed int)ceil(((double)(value_bits*lineL))/8);
//fprintf(stderr,"\n-7 bytesL=%d",bytesL );
	 /*************** allocale double network ************/
	 if ((nhoodm=(char *)calloc(lineL,sizeof(char)))
				   ==NULL) outof_memory("nhoodm");
         /************** added, should not be ness ***********/
         allocate_mem_tcode0(nhood);
         if (tot_only==0){
	    allocate_mem_rule0(nhood);
            allocate_mem_rule0_extra(nhood);	
	    allocate_mem_all_0s_all_1s_rules(nhood);
	    allocate_mem_iso(nhood);
         }
	 /*************************/
	 if (rulemix){
	    if (tot_only==0) allocate_mem_rulemix(nhood);
	    allocate_mem_tcodemix(nhood);
         }
//fprintf(stderr,"\n allocate_mem_wiring() ");
	 allocate_mem_wiring();
	 allocate_mem_CA_states();
//fprintf(stderr,"\n-8 ");
	 /*********** copy nhood mix **********/
	 if (!nhood_mixed){
	    for (zu=0; zu<=lineL-1;zu++) nhoodm[zu]=nhood;
	 }
         else{
            if (oned){	    
	       memmove(nhoodm+lineL/2,nhoodm_temp,
                              (lineL/2)*sizeof(char));
               memmove(nhoodm,nhoodm_temp,(lineL/2)*sizeof(char));	      
            }
            else{
               for (jj=j2d-1;jj>=0;jj--){
                  for (ii=i2d/2-1;ii>=0;ii--){
		     nhoodm[jj*i2d+i2d/2+ii]=nhoodm_temp[jj*i2d/2+ii];
                     nhoodm[jj*i2d+ii]=nhoodm_temp[jj*i2d/2+ii];
                  }	
               }  
            }
         }
//fprintf(stderr,"\n-9 ");
         /**************** copy wiring *****************/     
         nonlocal=1;
         if (oned){
	    for (zu=lineL/2-1;zu!=Maxu;zu--){
	       for (wire=nhoodm_temp[zu]-1;wire>=0;wire--){       
		   wiring[zu+lineL/2][wire]=
                               wiring_temp[zu][wire]+lineL/2;
                   wiring[zu][wire]=wiring_temp[zu][wire];
               }
	    }
         }         
         else{
            for (jj=j2d-1;jj>=0;jj--){
	       for (ii=i2d/2-1;ii>=0;ii--){
		  for(wire=nhoodm_temp[jj*i2d/2+ii]-1;wire>=0;wire--){
                     wirejj=wiring_temp[jj*i2d/2+ii][wire]/(i2d/2);
                     wiring[jj*i2d+i2d/2+ii][wire] = 
                          wiring_temp[jj*i2d/2+ii][wire]+(wirejj+1)*i2d/2;
                     wiring[jj*i2d+ii][wire] = 
                          wiring_temp[jj*i2d/2+ii][wire]+wirejj*i2d/2;
                  }
	       }		        
	    }
         }
         for (zu=0;zu<=lineL/2-1;zu++){
//fprintf(stderr,"\n%d: ",zu);
//for (z=0;z<=nhood-1;z++) fprintf(stderr," %d ",wiring_temp[zu][z]);
             free(wiring_temp[zu]);
         }
         free(wiring_temp);
//fprintf(stderr,"\ntemp_wiring freed\n");
//for (z=0;z<=lineL/2-1;z++) fprintf(stderr," %d ",nhoodm_temp[z]);   
         free(nhoodm_temp); 
//fprintf(stderr,"\n-10 lineL=%d ",lineL);  
         /***** recalculate cell out degree frequency ****/
         /*freed and reallocated in allocate_mem_wiring - free_mem_wiring*/
           cell_out_freq();
//fprintf(stderr,"-11 ");
         /************ copy rule, tcode, kcode, or mix ************/
         if (tot_only==0){ 
            tablemax= (signed int)pow(value_range,(double)nhood)-1;
            tablebytes=value_bits * (signed int)ceil((double)(tablemax+1)/8);
	    
         }
         t_codemax=nhood*(value_range-1); /*max index of codetable*/
         t_codebytes=(signed int)ceil(value_bits * (double)(t_codemax+1)/8);
         v_codemax=v_tablecodemax[nhood];
         v_codebytes=(signed int) /*bytes for k-code, min=1*/
                       ceil(value_bits * (double)(v_codemax+1)/8);
         if (rulemix==0){ 
            if (tot_only==0) memmove(carule[0],carule_temp[0],tablebytes);
            memmove(cacode[0],cacode_temp[0],t_codebytes); 
            memmove(v_code[0],v_code_temp[0],v_codebytes);
         }

         if (rulemix){
            if (oned){
               for (zu=lineL/2-1;zu!=Maxu;zu--){
                  if (tot_only==0){
                     memmove(carule[zu+lineL/2],carule_temp[zu],tablebytes);
                     memmove(carule[zu],carule_temp[zu],tablebytes);
                  }
                  memmove(cacode[zu+lineL/2],cacode_temp[zu],t_codebytes);
                  memmove(cacode[zu],cacode_temp[zu],t_codebytes);
                  memmove(v_code[zu+lineL/2],v_code_temp[zu],v_codebytes);
                  memmove(v_code[zu],v_code_temp[zu],v_codebytes);
	       }
            }

            if (twod){
               for (jj=j2d-1;jj>=0;jj--){
                  for (ii=i2d/2-1;ii>=0;ii--){
                     if (tot_only==0){
		        memmove(carule[jj*i2d+i2d/2+ii],
                          carule_temp[jj*i2d/2+ii],tablebytes);
                        memmove(carule[jj*i2d+ii], 
                          carule_temp[jj*i2d/2+ii],tablebytes);
                     }
                     memmove(cacode[jj*i2d+i2d/2+ii],
                          cacode_temp[jj*i2d/2+ii],t_codebytes);
                     memmove(cacode[jj*i2d+ii], 
                          cacode_temp[jj*i2d/2+ii],t_codebytes);

                     memmove(v_code[jj*i2d+i2d/2+ii],
                          v_code_temp[jj*i2d/2+ii],v_codebytes);
                     memmove(v_code[jj*i2d+ii], 
                          v_code_temp[jj*i2d/2+ii],v_codebytes);
                  }	
               }               
	    }
	 }


         if (tot_only==0){
            if (rulemix){
	       for (zu=1;zu<=lineL/2-1;zu++) free(carule_temp[zu]);
            }         

            free(carule_temp[0]);
	    free(carule_temp);
         }

         if (rulemix){
            for (zu=1;zu<=lineL/2-1;zu++) free(cacode_temp[zu]);
         }
         free(cacode_temp[0]);
	 free(cacode_temp);

         if (rulemix){        
            for (zu=1;zu<=lineL/2-1;zu++) free(v_code_temp[zu]);
         }
         free(v_code_temp[0]);
	 free(v_code_temp);

//fprintf(stderr,"-12 ");
         /***** show duplicated rule-wiring scheme ************/
         show_w_r_scheme();
//fprintf(stderr,"-13 ");
         /******************** copy state *******************/
         if (oned){
            for (zu=lineL/2-1;zu!=Maxu;zu--){
	        if (value_range==2){
                   set_bit(bitseed,zu+lineL/2,
			    get_bit(bitseed_temp,zu));
		   set_bit(bitseed,zu,get_bit(bitseed_temp,zu));
	        }
                else{
                   set_value(bitseed,zu+lineL/2,
			    get_value(bitseed_temp,zu));
		   set_value(bitseed,zu,get_value(bitseed_temp,zu));
	        }
            }
         }
         else{
            for (jj=j2d-1;jj>=0;jj--){
	       for (ii=i2d/2-1;ii>=0;ii--){
                   if (value_range==2){
                      set_bit(bitseed,jj*i2d+i2d/2+ii,
                         get_bit(bitseed_temp,jj*i2d/2+ii));
                      set_bit(bitseed,jj*i2d+ii,
                         get_bit(bitseed_temp,jj*i2d/2+ii));
                   } 
                   else{
                      set_value(bitseed,jj*i2d+i2d/2+ii,
                         get_value(bitseed_temp,jj*i2d/2+ii));
                      set_value(bitseed,jj*i2d+ii,
                         get_value(bitseed_temp,jj*i2d/2+ii));
                   } 
	       }		        
            }
         }
//fprintf(stderr,"-15 bytesL=%d",bytesL);
         free(bitseed_temp);
         /*see/ammend result*/
         moveto(vgax(50),gety);
         select_seed(0,bitseed,"SEED",0);     
}

/********************* draw Derrida plot *******************/
/*draw Derrida plot - 
  set randomly pairs of initial states with given 
  Hamming distance, plot H(t0)-H(t1) for a large set of pairs,
  repeat for all possible values H(t0)*/

void draw_Derrida_plot(char **thisrule){      
  signed int posx,posy,xbox,z,i,temp,tempx,tempy,
              Dt0,Dt1,
              xstart,ystart,xsize,ysize;
              
  unsigned int    n,zu,zu1,Hamm,Hamm_reached,
                   bitno,itcount;

  char              cellscale,redrawn_nofizz=0,
                   keep=0,autokeep=0,D_was_drawn=0,
                   interrupt_run,Hamm_step_changed,   
                   **Dseed, **Dnextseed,*temppoint, 
                   *first_state1, *comp_state1, *firstcomp_state1,
                   original_value;
 
 D_prompts         Dp;
 
 unsigned char     tempcolor,tempcolor1;
 signed int      sample,temp_Hamm_step,expoD,max_expoD;
 float             totalDt1,*buff_average_Dt1,expoD_total;
 /*for canalyzing data*/  
 unsigned int    poss,cgenenet,*wnhood;
 unsigned long     inputtotal,cinputnet;
 float             cinputfreq,cgenefreq;

 /*for automatic dec range of rules*/
 char automatic=0,automatic_end=0,comps_complete=0,
   *catemp,*ca_original,
   *ca_tickoff,rule_type; /*ca_tickoff for equiv classes and rule clusters*/
 unsigned long ruledec,rule_space,rule_space_bytes,rule_dec_max;                          
 signed int tablemax,tablebytes,equiv_count=0;
 float derrida_coeff;
 char plot_this=1;//no longer necessary, always =1
 
      /*no noise*/
      if (temp_out_prob==0) temp_out_prob=1.0;
      if (temp_update_prob==0) temp_update_prob=1.0;

      xstart=Maxx/2 - vgax(30);
      ystart=Maxy-vgax(50);
      xsize=ysize=vgay(300);

      if (Maxx>=799) cellscale=5;
      else cellscale=4;
      draw_box(11,xstart-vgax(30),ystart-ysize-vgay(20),
      	                                Maxx-2,ystart+vgax(20),1,black);	  
      moveto(xstart,ystart-ysize-CHeight*1.5);
      outtext("Derrida plot");
      /*set defaults*/
      Dp.maxH=1.0;    /*max normalized Ham of the plot xy-axis, can be < 1.0*/
      Dp.D_sample=25; /*the sample for each Ham distance*/
      Dp.Hamm_step=1; /*interval between successive initial Hamm on x-axis*/
      Dp.itlimit=1;   /*forward iterations for final Ham*/
      Dp.suppress_fuzz=0; 
      D_was_drawn=0;

      /*Derrida exponent, slope of start of plot*/
      max_expoD=lineL/5;
      expoD=(signed int)ceil((double)lineL/40);
      if (expoD>15) expoD=15;
      if (expoD>max_expoD) expoD=max_expoD;

      /*memory for pseudo-nhood*/
      if ((wnhood=(unsigned int *)calloc(nhood,sizeof(unsigned int)))
			      ==NULL) outof_memory("wnhood");
     
      /*memory for seed - successor pairs*/ 
      sprintf(textb[0],"mem for Derrida");
      if ((buff_average_Dt1=(float*)calloc(lineL+1,sizeof(float)))
				    ==NULL) outof_memory(textb[0]);
  
      if ( (Dseed =(char**) calloc(2,sizeof(char*)))
				 ==NULL) outof_memory(textb[0]);
      if ( (Dnextseed =(char**) calloc(2,sizeof(char*)))
				 ==NULL) outof_memory(textb[0]);
      for (z=0;z<=1;z++){
         if ((Dseed[z]=(char*)calloc(bytesL,sizeof(char)))
				    ==NULL) outof_memory(textb[0]);
         if ((Dnextseed[z]=(char*)calloc(bytesL,sizeof(char)))
		         	    ==NULL) outof_memory(textb[0]);
      }
      if ((first_state1=(char*)calloc(bytesL,sizeof(char)))
				    ==NULL) outof_memory(textb[0]);
      if ((comp_state1=(char*)calloc(bytesL,sizeof(char)))
				    ==NULL) outof_memory(textb[0]);
      if ((firstcomp_state1=(char*)calloc(bytesL,sizeof(char)))
				    ==NULL) outof_memory(textb[0]);

      /*for automatic ECA with equiv rules and rule clusters*/
      if (tot_only==0){ /*if not TFOmode, tcode and kcode treated as rode*/
	  rule_type=1; //rcode
          tablemax= (signed int)pow(value_range,(double)nhood)-1;/*rcode*/
      }
      else{ /*if in TFOmode*/
         rule_type=2; //tcode or kcode
	 if (totalistic==1)
             tablemax=nhood*(value_range-1);//tcode, totalistic=1
	 else if (totalistic==2) 
             tablemax=v_tablecodemax[nhood];//kcode, totalistic=2
      }
      tablebytes=(signed int) ceil(value_bits * (double)(tablemax+1)/8);
      if ((catemp=(char *)calloc(tablebytes,sizeof(char)))
				             ==NULL) outof_memory("catemp");
      if ((ca_original=(char *)calloc(tablebytes,sizeof(char)))
				             ==NULL) outof_memory("ca_original");
      memmove(ca_original,thisrule[0],tablebytes);/*restore original rule*/
      rule_dec_max=max_dec_rule(tablemax,value_range);
      //fprintf(stderr,"\nrule_dec_max=%lu",rule_dec_max);

      if (rule_dec_max>0){     
         rule_space=(unsigned long)(pow(value_range,(double)(tablemax+1)));
         rule_space_bytes=ceil(rule_space/8);
         
         if ((ca_tickoff=(char *)calloc(rule_space_bytes,sizeof(char)))
				    ==NULL) outof_memory("ca_tickoff");
         ruledec=dec_equiv(thisrule[0],tablemax);
         equiv_count=0;
      }
      
   prompts: 
      if (rulemix==0 && automatic){ /*automatic plot for CA*/
	 is[0]=0;         
         expoD_total=0;
	 

        next_ruledec:
	  
         if (comps_complete==0 && ruledec>=rule_space-1){
               automatic=0;
               automatic_end=1;
               memmove(thisrule[0],ca_original,tablebytes);/*restore original rule*/
         }    
         else{
	    automatic_end=0;
            show_rule_bottom(nhoodm[0],0,thisrule[0],0);

            if (comps_complete==0){
               ruledec++;
               if (get_bit(ca_tickoff,ruledec)==1){ /*filter this rule*/
		  /*fprintf(stderr,"\n %lu filtered", ruledec);*/		  
                  goto next_ruledec;
               }
	    }
            dec_to_value_line(thisrule[0],ruledec,tablemax+1);
            //fprintf(stderr,"\nruledec=%lu",ruledec);
	 }
         goto skip_prompts; 
      }

      /*------------------ initial prompts ------------------*/
      redrawn_nofizz=0; 
      xbox=draw_prompt_box(3);
      if (D_was_drawn) sprintf(textb[0],
	 "Derrida plot: redraw (no spread)-r, quit-q, ");
      else sprintf(textb[0],"Derrida plot: quit-q, ");
      outtext(textb[0]);
      if (expoD>=1){                    
         sprintf(textb[0],
           "Dc sample (def %d, max %d):",expoD,max_expoD);
      }
      outtext(textb[0]); 
      input_string(2,0);
      if (expoD>=1){
         if (is[0]!=13 && atoi(is)>0 && atoi(is)<=max_expoD) 
                                                 expoD=atoi(is);
      }
      expoD_total=0;
      if (is[0]=='q') goto end;          
      
      if (is[0]=='r' && D_was_drawn){ 
         /*redraw graph*/
         draw_general_graph_frame(Dp.maxH,
				  keep,xstart,ystart,xsize,ysize,10,10);
         /*draw red diagonal*/
         setcolor(lightred);          
         line(xstart,ystart,xstart+xsize,ystart-ysize);
         setcolor(white);

         /*draw average curve*/               
         if (Hamm_reached==0) Hamm_reached=(unsigned int)(lineL*Dp.maxH);
	    for (Hamm=1;Hamm<=Hamm_reached-Dp.Hamm_step
                                         ;Hamm+=Dp.Hamm_step){
              line(xstart+((float)(Hamm)/(lineL*Dp.maxH)
                                      )*(float)xsize, 
              ystart-buff_average_Dt1[Hamm]*(float)ysize,
              xstart+((float)(Hamm+Dp.Hamm_step)/(lineL*Dp.maxH)
                                      )*(float)xsize, 
              ystart-buff_average_Dt1[Hamm+Dp.Hamm_step]*(float)ysize);
              /*if graph projects above top of frame*/
              if (ystart-buff_average_Dt1[Hamm+Dp.Hamm_step]*
                                    (float)ysize<ystart-ysize) break;
         }
         erase_prompt_box(3);
         redrawn_nofizz=1;
         goto forward_skip;
      }
      moveto(xbox,gety+CHeight);
      keep=get_D_para(0,&Dp);
      /*draw graph with correct axes*/      
      draw_general_graph_frame(Dp.maxH,keep,xstart,ystart,xsize,ysize,10,10);
           
      /*draw red diagonal*/
      setcolor(lightred);          
      line(xstart,ystart,xstart+xsize,ystart-ysize);
      setcolor(white);

      erase_prompt_box(3);
      if (is[0]=='q') goto prompts;     
      tempcolor=getcolor();
      /*-------------------- initial_prompts -------------*/
    skip_prompts:
      
      xbox=draw_prompt_box(2);
      sprintf(textb[0],
	 "plotting Derrida, sample=%d, iterations=%d step=%d",
                                  Dp.D_sample,Dp.itlimit,Dp.Hamm_step);
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);
      outtext("quit/pause-q");
     
      Hamm_reached=0;
      //input_string(1,0);
      //is[0]=0;
      if (automatic || automatic_end==1){
           draw_general_graph_frame(Dp.maxH,autokeep,
                            xstart,ystart,xsize,ysize,10,10);
           /*to keep last automatic plot superimposed*/ 
	   if (automatic==0 && automatic_end==1) automatic_end=0;
      }
      else draw_general_graph_frame(Dp.maxH,keep,
                            xstart,ystart,xsize,ysize,10,10);
      /*draw red diagonal*/
      setcolor(lightred);          
      line(xstart,ystart,xstart+xsize,ystart-ysize);
      setcolor(white); 

      moveto(xstart,ystart-ysize+2);
      tempcolor1=getcolor();
      setcolor(green);
      if (nhood_mixed) sprintf(textb[0]," v%d k-mix=%d-%d",
                         value_range,nhood_lb,nhood_ub);
      else sprintf(textb[0]," v%d  k=%d",value_range,nhood);
      outtext(textb[0]);
      if (threed) sprintf(textb[0]," network size= %dx%dx%d",
                                      i3d,j3d,h3d);
      else if (twod) sprintf(textb[0]," network size= %dx%d",
                                      i2d,j2d);
      else  sprintf(textb[0]," network size= %d",lineL);
      outtext(textb[0]);

      moveto(xstart,gety+CHeight);
      if (oned){
         if (!nonlocal) outtext(" one-d CA wiring");
         else outtext(" random one-d wiring");
      }
      else if (twod){
         if (regular2d) outtext(" two-d CA wiring");
         else outtext(" random two-d wiring");
      }
      else if (threed){
         if (regular3d) outtext(" three-d CA wiring");
         else outtext(" random three-d wiring");
      }
      if (nonlocal && !regular2d){
	  if (twod){
             if ((signed int)zonesize==i2d) outtext(" no limit");
             else{
                 sprintf(textb[0]," zone=%d",zonesize);
                 outtext(textb[0]);
             }
          }
	  else{
             if (zonesize==lineL) outtext(" no limit");
             else{
                 sprintf(textb[0]," zone=%d",zonesize);
                 outtext(textb[0]);
             }
	  }
      }
      moveto(xstart,gety+CHeight);
      inputtotal=cinputnet=cgenenet=0;
      
      if (rulemix && tot_only==0){/*check canalyzing gene/input, rcode only %*/         
         for (poss=lineL-1;poss!=Maxu;poss--){
            if (nhood_mixed) inputtotal+=nhoodm[poss];
            canalyzing(nhoodm[poss],0,carule[poss]);
            if (canaltotal>0){
	       cinputnet+=canaltotal;
	       cgenenet+=1;
	    }
         }
         
         if (!nhood_mixed) inputtotal=lineL*nhood;
         cinputfreq=(float)cinputnet/inputtotal;
         cgenefreq=(float)cgenenet/lineL;
	 sprintf(textb[0],
	   " rcode-mix: canalyzing inputs=%lu/%lu=%.1f%%",
			cinputnet,inputtotal,cinputfreq*100);
         setfillstyle(SOLID_FILL,black);
	 bar(getx+1,gety,getx+CWidth*.75*strlen(textb[0]),gety+CHeight*2);
	 outtext(textb[0]);
	 moveto(xstart,gety+CHeight);
	 sprintf(textb[0],
	   "          genes=%d/%d=%.1f%%",
			   cgenenet,lineL,cgenefreq*100);
	 outtext(textb[0]);
      }
      else{
         if (tot_only==1){
            if (rulemix){
	       if (totalistic==1)  sprintf(textb[0]," tcode-mix");
               else sprintf(textb[0]," kcode-mix");
            }
            else{
               if (totalistic==1) sprintf(textb[0]," homogeneous tcode");
               else sprintf(textb[0]," homogeneous kcode");
            }
         }
         else sprintf(textb[0]," homogeneous rcode");

         setfillstyle(SOLID_FILL,black);
         bar(getx+1,gety,getx+CWidth*.75*strlen(textb[0]),gety+CHeight);
         outtext(textb[0]);	 
      }
  
      setcolor(tempcolor1);

      Hamm_step_changed=0;
      
      for (Hamm=1;Hamm<=((unsigned int)lineL* Dp.maxH);
	                                Hamm+=Dp.Hamm_step){          
          totalDt1=0;
          if (interrupt_run==1 && is[0]=='q'){ 
             is[0]=0;  
             Hamm_reached=Hamm-Dp.Hamm_step;  
             break;
	  }          
          interrupt_run=0;
         
          for (sample=1;sample<=Dp.D_sample;sample++){
             if (event_ready()){
                if (is[0]=='q'){                    
                   interrupt_run=1;   
                   xbox=draw_prompt_box(3);                          
                   sprintf(textb[0],                                 
	              "interrupted at Hamm=%.3f, quit now-q, cont-ret:",
                                         (float)(Hamm-1)/lineL);
                   outtext(textb[0]);                                  
                   input_string(1,0);                             
                   switch (is[0]){  
		     case 'q':                   
                        Hamm-=Dp.Hamm_step; 
                        automatic=0; 
                        break;                          
                   }
                   moveto(xbox,gety+CHeight);                    
                   temp_Hamm_step=Dp.Hamm_step;

                   if (is[0]!='q') get_D_para(1,&Dp);

                   if (temp_Hamm_step!=Dp.Hamm_step) Hamm_step_changed=1; 
                   Hamm-=Dp.Hamm_step;
                   erase_prompt_box(3);

                   xbox=draw_prompt_box(2);
                   sprintf(textb[0],
	             "plotting Derrida, sample size=%d, iteration limit=%d",
                                                 Dp.D_sample,Dp.itlimit);
                   sprintf(textb[1],"Hamming step=%d, quit/pause-q",
                                                         Dp.Hamm_step);
                   outtext(textb[0]);
                   moveto(xbox,gety+CHeight);
                   outtext(textb[1]);
                   break;              
                }         
             }

             for (z=0;z<=1;z++){
                if (z==0){
                   /*set a random seed*/
		  for (zu1=L;zu1!=Maxu;zu1--){
		     if (value_range==2){
                           set_bit(state1,zu1,((myrand()%100)/50));
		     }
                     else set_value(state1,zu1,myrand()%value_range);
		   }
                   memmove(first_state1,state1,bytesL);
                   memmove(Dseed[z],state1,bytesL); 
	        }
                /*set pair seed at random Ham Hamming distance from first*/
                else if (z==1){
                   /*flip bits if Hamm <= lineL/2*/ 
                  if (value_range==2){              
                   if (Hamm<=lineL/2){                       
                      bitno=0;
                      while(1){
                         bitno+=1;
                         zu1=myrand()%lineL; 
                         /*flip a bit at random position*/
                         set_bit(first_state1,zu1,abs(get_bit(first_state1,zu1)-1));
                         /*restore flip if not different*/
                         if (get_bit(first_state1,zu1)==get_bit(Dseed[0],zu1)){ 
                             set_bit(first_state1,zu1,abs(get_bit(first_state1,zu1)-1));
                             bitno-=1;
                         } 
                         memmove(state1,first_state1,bytesL);
                         memmove(Dseed[z],first_state1,bytesL); 
                         if (bitno==Hamm) break;
                      } 	           
                      memmove(Dseed[z],first_state1,bytesL); 

	           }
                   else if (Hamm>=lineL/2+1){
                      /*restore bits in compliment if Hamm >= lineL/2 + 1*/  
                      for (zu1=L;zu1!=Maxu;zu1--) 
                           set_bit(comp_state1,zu1,abs(get_bit(Dseed[0],zu1)-1));
                      memmove(firstcomp_state1,comp_state1,bytesL);
                      bitno=0;
                      while(1){
                         if (Hamm==lineL) break;
                         bitno+=1;
                         zu1=myrand()%lineL; 
                         /*flip a bit at random position in compliment*/
                         set_bit(comp_state1,zu1,abs(get_bit(comp_state1,zu1)-1))
                         /*restore flip*/
			  if (get_bit(comp_state1,zu1)==get_bit(firstcomp_state1,zu1)){
                                set_bit(comp_state1,zu1,abs(get_bit(comp_state1,zu1)-1));
                                bitno-=1;
                          }
                          if (bitno==lineL-Hamm) break;
                      } 	           
                      memmove(state1,comp_state1,bytesL);
                      memmove(Dseed[z],comp_state1,bytesL); 
	           }
		  }
                  else{ /* if value_range > 2 */
                      bitno=0;
                      while(1){
                         bitno+=1;
                         zu1=myrand()%lineL; 
                         /*flip a bit at random position*/
                         original_value=get_value(first_state1,zu1);
                         set_value(first_state1,zu1,myrand()%value_range);
                         /*restore flip if not different*/
                         if (get_value(first_state1,zu1)==get_value(Dseed[0],zu1)){ 
                             set_value(first_state1,zu1,original_value);
                             bitno-=1;
                         } 
                         memmove(state1,first_state1,bytesL);
                         memmove(Dseed[z],first_state1,bytesL); 
                         if (bitno==Hamm) break;
                      } 	           
                      memmove(Dseed[z],first_state1,bytesL); 
                  }
                }
              
                itcount=0;
	        while(1){
                   itcount++;
                   for (n=L; n!=Maxu; n--){
	              /*local nhood with periodic boundary conditions*/
	              if (nonlocal==0){
	                 /*i.e. for nhood=9 lineL=3 to work*/
	                 if (L<nhoodm[n]/2){
		            for (i=0;i<=nhoodm[n]-1;i++){
		               temp=lineL+n-(nhoodm[n]/2)+i;
		               if (temp<0) temp+=lineL;
		               wnhood[i]=abs(temp)%lineL;
		            }
	                 }
	                 else{
		            for (i=0;i<=nhoodm[n]-1;i++)
			       wnhood[i]=(lineL+n-(nhoodm[n]/2)+i)%lineL;
	                 }
	              }    
	              /*set local 2d wiring*/
	              else if (loc_twod_fonly){
                         if (twod==2) wire_2d_local(n,wnhood);
                         else if (threed==3) wire_3d_local(n,wnhood); 
                      }
	              /*nonlocal=1, get psuedo-nhood from wiring scheme*/
	              else{
	                 for (i=0;i<=nhoodm[n]-1;i++) 
                                      wnhood[i]=wiring[n][i];
	              }
                                           
                      /*xxxxxxxxxxxx next time-step xxxxxxxxxxxxxxxxx*/
	              next_time_step(thisrule,state1,state2,0,NULL,1,wnhood, n,0);
                       /*xxxxxxxxxxxx end next time-step xxxxxxxxxxxxx*/

                      /*{ //this also works but is superseded
                      unsigned int u; 
                      u=0; //find dec value of actual or pseudo-nhood
	                 for (i=nhoodm[n]-1;i>=0;i--){
	                    if (value_range==2) u+=(get_bit(state1,wnhood[i])*
                                (signed int)pow(2,(double)i));
                            else u+=get_value(state1,wnhood[i])*
                                (signed int)pow(value_range,(double)i);
                         }
	                 //set cell next line according to rule look-up table
                         if (!rulemix){
                            if (value_range==2){ 
		               set_bit(state2,n,get_bit(thisrule[0],u));
                            }
                            else set_value(state2,n,get_value(thisrule[0],u));
	                 }
                         else{
		            if (value_range==2){
                               set_bit(state2,n,get_bit(thisrule[n],u));
                            }
                            else set_value(state2,n,get_value(thisrule[n],u));
		         } 
                      }*/

	           }/*for loop*/            
                   if (itcount==Dp.itlimit){
                       itcount=0;
                       memmove(Dnextseed[z],state2,bytesL);
                       break;
                   }                                  
                   temppoint=state1; /*copy state2 to state1*/
	           state1=state2;
	           state2=temppoint;                 
	        } /*while loop*/             
             }/*next z*/ 
	    
             Dt0=Hamm;
             Dt1=0;
             /*check Hamming distance*/
             for (zu=0;zu<=lineL-1;zu++){
                if (value_range==2){
                   if (get_bit(Dnextseed[0],zu)!=
                            get_bit(Dnextseed[1],zu)) Dt1+=1; 
                }
                else{ 
                   if (get_value(Dnextseed[0],zu)!=
                            get_value(Dnextseed[1],zu)) Dt1+=1; 
                } 
             }                           
             /*draw pixels for sample*/             
             if (Dp.suppress_fuzz==0){
                putpixel(xstart+
                  ((float)Dt0/(lineL*Dp.maxH))*(float)xsize,
		      ystart-((float)Dt1/(lineL*Dp.maxH))*
			 (float)ysize,yellow);
             }
             totalDt1+=(float)Dt1/(lineL*Dp.maxH);
             
             /*see whats happening for small networks*/
             if (Dp.show_details){                                 
                if (lineL<=40){                  
                   xbox=draw_prompt_box(3);
                   foldposs=64;
                   print_layered_bitstring(Dseed[0],L,cellscale,2,-1,0);
                   moveto(getx+vgax(10),gety); 
                   print_layered_bitstring(Dseed[1],L,cellscale,2,-1,0);
                   moveto(xbox,gety+CHeight);
                   print_layered_bitstring(Dnextseed[0],L,
                                                        cellscale,2,-1,0);
                   moveto(getx+vgax(10),gety);
                   print_layered_bitstring(Dnextseed[1],L,
                                                        cellscale,2,-1,0);
                   moveto(xbox,gety+CHeight);
		}
                else draw_prompt_box(1);
                sprintf(textb[0],"sample=%d H(t0)=%d H(t%d)=%d q-quit:",
                                     sample,Dt0,Dp.itlimit,Dt1);
                outtext(textb[0]);
                input_string(1,0);   
                if (is[0]=='q'){
                   Dp.show_details=0;
                   is[0]='0';
                   if (lineL<=50) erase_prompt_box(3);
                   else erase_prompt_box(1); 
                }        
             }       
          }/*next sample*/
          if (interrupt_run==0){
             buff_average_Dt1[Hamm]=totalDt1/Dp.D_sample;

             /*plot average*/
             setcolor(white);             
             if (Hamm>1 && Hamm_step_changed==0){
                line(xstart+((float)(Hamm-Dp.Hamm_step)/(lineL*Dp.maxH)
			     )*(float)xsize, 
                   ystart-buff_average_Dt1[Hamm-Dp.Hamm_step]*(float)ysize,
                     xstart+((float)(Hamm)/(lineL*Dp.maxH))*(float)xsize, 
                       ystart-buff_average_Dt1[Hamm]*(float)ysize);
             
                
	     }
             if (redrawn_nofizz==0 &&
                   Dp.Hamm_step==1 && expoD>=1 && Hamm<=expoD &&
                                    Hamm>0 && Hamm_step_changed==0){
                
                expoD_total+=buff_average_Dt1[Hamm]/
		                    ((float)(Hamm)/(lineL*Dp.maxH));
                /*fprintf(stderr,"\n %d: %.3f/%.3f=%.3f total=%.3f",
		     Hamm,buff_average_Dt1[Hamm],
			(float)(Hamm)/(lineL*Dp.maxH), 
                          buff_average_Dt1[Hamm]/
                            ((float)(Hamm)/(lineL*Dp.maxH)),
			    expoD_total);*/
             }        
	  }
          /*to skip average plot if Hamm_step changed*/
	  if (Hamm_step_changed){
             if (Hamm_step_changed==2) Hamm_step_changed=0; 
             else if (Hamm_step_changed==1) Hamm_step_changed=2; 
          }         
          /*if graph projects above top of frame*/
          if (ystart-buff_average_Dt1[Hamm]*(float)ysize<ystart-ysize)
	                                       break;
      }/*next Hamm*/

    forward_skip:
      if (automatic==0){
         //set_medium_font();
         set_small_font();
         //setcolor(lightgreen);
         setcolor(yellow);
         sprintf(textb[0],"");
	
         if (Dp.end_label==1){ /*print default label at end of curve*/
           if (rulemix==0 && rule_dec_max>0){
              /*show rule in dec or hex at end of plot, no of iterations superseded*/
            
             /*rule_type=1; rcode
               rule_type=2; tcode or kcode*/
             if (nhood<=3 && value_range==2) /*rule dec number at end of plot*/
                sprintf(textb[0],"%lu ", dec_equiv(thisrule[0],tablemax));
             else if (nhood<=5 && rule_type==2 && value_range==2)
                sprintf(textb[0],"%lu ", dec_equiv(thisrule[0],tablemax));
             else{ /*rule hex number at end of plot*/ 
	        print_current_bitstring_hexbytes(1,rule_type,thisrule[0],nhood,Maxx,white,7);
                sprintf(textb[0],"%s",bigbuf);
             }
           }
           else sprintf(textb[0],"%d ", Dp.itlimit); /*print iteration no.*/
	 }
         else if (Dp.end_label==2){ /*show zparameter instead*/
	     if (rulemix==0 && rule_dec_max>0){
	        /*sprintf(textb[1],"zl=%.3g zr=%.3g Z=%g ",
	        zparam[1],zparam[2],zparam[0]);*/
                sprintf(textb[0],"%g ",zparam[0]);
	     }
	 }      
         
         if (Dp.end_label==1 || Dp.end_label==2){/*otherwise omit label altogether,
                                                  or show cluster number if active */
            posx=xstart+((float)(Hamm-1)/(lineL*Dp.maxH))*(float)xsize;
            posy=ystart-buff_average_Dt1[Hamm-Dp.Hamm_step]*(float)ysize;
            if (posy<ystart-ysize) posy=ystart-ysize;
      
            //setcolor(lightgreen);
	    /*if ((nhood<=3 && value_range==2) || //draw a small box
             (nhood<=5 && rule_type==2 && value_range==2) || (Dp.end_label==2))
                          draw_box(-1,posx,posy,posx+CWidth*5*1.0,posy+CHeight,1,black);
	    else //draw a variable size small box to fit the rule in hex
	     draw_box(-1,posx,posy,posx+CWidth*(tablebytes*2),posy+CHeight,1,black);*/
	    draw_box(-1,posx,posy,posx+CWidth*(strlen(textb[0])+1),posy+CHeight,1,black);	 
	 
           outtext(textb[0]);
	   //input_string(1,0); /*pause after data box, debug??*/
	 
	 }
         restore_def_font();
      }

     skip_plot: /*to skip the plot for reflection symmetries -- elementary rules*/

      D_was_drawn=1;
      /*draw red diagonal*/
      setcolor(lightred);
      line(xstart,ystart,xstart+xsize,ystart-ysize);          
      if (Dp.show_details) erase_prompt_box(3);   

      setcolor(white);
      xbox=draw_prompt_box(2);   
      sprintf(textb[0],"Derrida plot complete,");
      outtext(textb[0]);

      sprintf(textb[1],"");
      if (redrawn_nofizz==0 && expoD>=1){
	double ratio;

         if (Dp.Hamm_step==1 && Dp.itlimit==1){ /*these must=1 for Derrida coefficient*/
	    signed int this_step;
            double D_angle;

	    /* compute angle
            PI/2                                | over 30 +
            |  /PI/4 =45 degrees, D_exponent: <  45=0,
            | /                                 | under 30 -
            |/_______0 */
      
            if (Hamm>=expoD) this_step=expoD;
	    else this_step=Hamm; 

	    ratio=expoD_total/this_step;
            D_angle = (float)atan (ratio) * 57.2958;
            sprintf(textb[4]," slope=%.1fdeg  Dc=%.3f (%d H)",
                                   D_angle,log2(ratio),this_step);  
            outtext(textb[4]); /*printed inside Derrida plot*/
         }

	 /************* new for automatic ***************************/
         if (rulemix==0 && value_range==2){
           char temp_pdata;
	   
             temp_pdata=pdata; 
             pdata=1; /*to allow printing hex to xterm*/

            /*show Derrida coeff in xterm for one rule*/
	    if (automatic==0 && automatic_end==0){ 
	      /*fprintf(stderr,"\n%lu %.3f",
                 dec_equiv(thisrule[0],(signed int)pow(value_range,
		   (float)nhood)-1),log2(ratio) );*/
	    }
           
	    else if (automatic){
              signed int mtablemax, mtablebytes;
              unsigned long temp_ruledec;
              char xnhood,temp_totalistic,print_this=0;

/******************************************************************/	      
#             define print_rule {\
	              if (rule_dec_max>0 && xnhood<=3 && value_range==2)\
                         fprintf(stderr,"%lu ",ruledec);\
	              else if (rule_dec_max>0 && xnhood<=5 && rule_type==2 && value_range==2)\
                         fprintf(stderr,"%lu ",ruledec);\
                      else{\
		         print_current_bitstring_hexbytes(1,rule_type,catemp,xnhood,Maxx,white,3);\
                         fprintf(stderr," ");\
                      }\
	       }
/******************************************************************/	      
               /*draw automatically from start rule, filter/show equivalents, 
                                               show Derrida coeff in xterm*/
               /*automatic: starting with the currrent rule number ...
                           1=rest of equivalence class, one plot 4 rules
                           2=rest of clusters, one plot 8 rules, includes complements
                           3=rest of all rules in rulespace 
                the initial rule is plotted first, then option "automatic-1/2/3"
                return exits the Derrida plot*/
              
	         /*disable totalistic if tot_only==0, 
                   for totalistic use TFOmode, tot_only=1*/
	      
                 temp_totalistic=totalistic;
                 if (tot_only==0 && totalistic) totalistic=0;
	         xnhood=nhood;
		 mtablemax=tablemax;
                 mtablebytes=tablebytes;
                 if (comps_complete==0) temp_ruledec=ruledec; 
                 memmove(catemp,thisrule[0],mtablebytes);

		 /*draw automatically from start rule, filter/show equivalents, 
                                               show Derrida coeff in xterm*/

		if (comps_complete==0)
		  fprintf(stderr,"\n%d: ",equiv_count);
                else fprintf(stderr,"\n    ");
		 
                /*start rule*/
                ruledec=dec_equiv(catemp,mtablemax);
                print_rule;
                set_bit(ca_tickoff,ruledec,1);
                if (automatic==1 || automatic==2){
                   /*n=negative_transformation*/
                   negative_transformation(catemp,mtablebytes,mtablemax);/*neg*/
                   ruledec=dec_equiv(catemp,mtablemax);
                   print_rule;
                   set_bit(ca_tickoff,ruledec,1);
                   if (totalistic==0){
                      /*r=reflection_transformation -- first revert to start rule*/
                      negative_transformation(catemp,mtablebytes,mtablemax);/*back*/
                      reflection_transformation(catemp,xnhood,mtablebytes,mtablemax);/*ref*/
                      ruledec=dec_equiv(catemp,mtablemax);
                      print_rule;
                      set_bit(ca_tickoff,ruledec,1);
                      /*nr=negati1ve-reflection -- keep reflection above, make negative*/
                      negative_transformation(catemp,tablebytes,mtablemax);/*neg of ref*/
                      ruledec=dec_equiv(catemp,mtablemax);
                      print_rule;
                      set_bit(ca_tickoff,ruledec,1);
                   }
		    
                   if (Dp.Hamm_step==1 && Dp.itlimit==1){
                         fprintf(stderr," %.3f",log2(ratio) );
                         if (comps_complete==0) derrida_coeff=log2(ratio);
		         if (automatic==2 && comps_complete==1)
                            fprintf(stderr," (%.3f)",derrida_coeff-log2(ratio) ); 
	   	   }
		   		   		   
                   if (automatic==2) comps_complete=abs(comps_complete-1);
		   //fprintf(stderr," cc=%d",comps_complete);
                }
               		
                if (automatic==2 && comps_complete==1){
		   memmove(catemp,thisrule[0],mtablebytes);
                   complementary_transformation(catemp,mtablebytes,mtablemax);
                   ruledec=dec_equiv(catemp,tablemax);
                   goto prompts; 
		}
                if (automatic==3 && Dp.Hamm_step==1 && Dp.itlimit==1)
                                       fprintf(stderr," %.3f",log2(ratio) );

		/*show sym SY, semi-asym SA , or fully-asym FA, alongside list*/
	        if (nhood==3 && oned){ //for v/k = 2/3 only, add symmetry categories in xtermm
	           if (get_bit(catemp,6) == get_bit(catemp,3)
		       && get_bit(catemp,4) == get_bit(catemp,1) ) fprintf(stderr," SY");
	           else if (get_bit(catemp,6) != get_bit(catemp,3)
		       ^ get_bit(catemp,4) != get_bit(catemp,1) ) fprintf(stderr," SA");
	           else if (get_bit(catemp,6) != get_bit(catemp,3)
		       && get_bit(catemp,4) != get_bit(catemp,1) )  fprintf(stderr," FA");
	        }
		
		if (plot_this==1){ //if (print_this){ also works
                   set_small_font();
                   setcolor(yellow);
                   sprintf(textb[0],"");

                   /*to show cluster first rule numbers -- comment out if not required*/
                   if (Dp.end_label==1){
                      set_medium_font();
	              setcolor(yellow);
	              sprintf(textb[0],"%d ", equiv_count);
                   }	 
		   else
                  /*to show cluster numbers -- comment out if not required*/
	
                  if (Dp.end_label==1){ /*print default label at end of curve*/
                    if (rulemix==0 && rule_dec_max>0){
                       /*show rule in dec or hex at end of plot, no of iterations superseded*/            
                       /*rule_type=1; rcode
                         rule_type=2; tcode or kcode*/
                       if (nhood<=3 && value_range==2) /*rule dec number at end of plot*/
                         sprintf(textb[0],"%lu ", dec_equiv(thisrule[0],tablemax));
                       else if (nhood<=5 && rule_type==2 && value_range==2)
                         sprintf(textb[0],"%lu ", dec_equiv(thisrule[0],tablemax));
                       else{ /*rule hex number at end of plot*/ 
	                 print_current_bitstring_hexbytes(1,rule_type,thisrule[0],nhood,Maxx,white,7);
                         sprintf(textb[0],"%s",bigbuf);
                       } 
                     }
                     else sprintf(textb[0],"%d ", Dp.itlimit); /*print iteration no.*/
                  }
                  else if (Dp.end_label==2){ /*show zparameter instead*/
	             if (rulemix==0 && rule_dec_max>0){
	                /*sprintf(textb[1],"zl=%.3g zr=%.3g Z=%g ",
	                  zparam[1],zparam[2],zparam[0]);*/
                        sprintf(textb[0],"%g ",zparam[0]);
	             }
                  }      
		  
		  if (Dp.end_label==1 || Dp.end_label==2){/*otherwise omit label altogether,
                                               or show cluster number if active */
                      posx=xstart+((float)(Hamm-1)/(lineL*Dp.maxH))*(float)xsize;
                      posy=ystart-buff_average_Dt1[Hamm-Dp.Hamm_step]*(float)ysize;
                      if (posy<ystart-ysize) posy=ystart-ysize;
      
	              draw_box(-1,posx,posy,posx+CWidth*(strlen(textb[0])+1),posy+CHeight,1,black);	 
	 
                      outtext(textb[0]);
	              //input_string(1,0); /*pause after data box debug??*/
	 
                  }
                  restore_def_font();
		  setcolor(white);
                } /*draw data in box*/
		
                if (comps_complete==0){
                   ruledec=temp_ruledec;
                   equiv_count++;
                }  
                if (autokeep==0){
                   /*show Dc and sample size in Derrida plot window*/
                    moveto(xstart+CWidth*10,ystart-ysize-CHeight*1.5);
                    //draw_box(-1,getx,gety,xstart+xsize+vgax(8),gety+CHeight*1.3,0,0);
		    draw_box(-1,getx,gety,Maxx-vgax(4),gety+CHeight*1.3,0,0);
                    sprintf(textb[0],"sample=%d steps=%d ",
                            Dp.D_sample,Dp.Hamm_step);
                    outtext(textb[0]);
                    outtext(textb[4]); //Dc

		    outtext(" auto-q next-ret:"); 
                    input_string(1 ,0);//pause to see
                    if (is[0]==13);
                    else if (is[0]=='q') autokeep=1; //undo pause
                } 
                if (tot_only==0 && totalistic) totalistic=temp_totalistic;

                
		
            }/**** end  automatic ****/
            pdata=temp_pdata;  
         } 
         
      } /*for Derrida coefficient*/
      
      /*show Dc and sample size in Derrida plot window*/     
      tempx=getx;
      tempy=gety;          
      //moveto(xstart+CWidth*10,ystart-ysize-CHeight*1.5);
      moveto(xstart,ystart-ysize-CHeight*1.5);
      draw_box(-1,getx,gety,xstart+xsize+vgax(8),gety+CHeight*1.3,0,0);
      sprintf(textb[0],"Derrida plot  sample=%d steps=%d ",
                            Dp.D_sample,Dp.Hamm_step);
      outtext(textb[0]);
      outtext(textb[4]);
      moveto(tempx,tempy);

      moveto(xbox,gety+CHeight);
      if (automatic==0){
         if (rulemix==0){
	   if (rule_dec_max>0){ /*rule can be expressed as a decimal number*/
	     fprintf(stderr,"\n%lu ",rule_dec_max);
	      if (tot_only==0 && value_range==2)  sprintf(textb[0],
	         "reset-r canalyzing-C reviserule-v automatic-1/2/3 keep+k):");
              else if (value_range==2)  sprintf(textb[0], /*includes tot_only==1*/
	         "reset-r reviserule-v automatic-1/2/3 keep+k):");
              else sprintf(textb[0],
	         "reset-r reviserule-v automatic-3 keep+k):");/*automatic count only*/
	   }
	   else{ /*automatic not valid if rule cannot be expressed as a decimal number*/
	      if (tot_only==0 && value_range==2)  sprintf(textb[0],
	         "reset-r canalyzing-C reviserule-v):");
              else sprintf(textb[0], "reset-r reviserule-v:");
	   }
	 }
         else{
            if (tot_only==0) sprintf(textb[0],"reset-r canalyzing-C:");
            else sprintf(textb[0],"reset-r:");
         }
         outtext(textb[0]);
         input_string(2,0);        
      }
      
     end:
      if (is[0]=='r' || is[0]=='C'){
          if (is[0]=='C'){ 
             if (rulemix) set_canalyzing_net(0);
             else set_canalyzing_rule(0);
          }
	  is[0]=0;	  
          goto prompts;
      }
      if (is[0]=='r'){
         is[0]=0;	  
         goto prompts;
      }
      else if (is[0]=='C' && tot_only==0){
         if (rulemix) set_canalyzing_net(0);
         else set_canalyzing_rule(0);
	 is[0]=0;	  
         goto prompts;
      }
      else if (rulemix==0 && is[0]=='v'){ /*revise/reset single rule, for CA*/
          revise_rule_or_code(0);
          /*for automatic ECA with equiv rules and rule clusters*/
          if (totalistic==0) tablemax= (signed int)pow(value_range,(double)nhood)-1;/*rcode*/ 
          else if (totalistic==1) tablemax=nhood*(value_range-1);/*tcode, totalistic=1*/
          else if (totalistic==2) tablemax=v_tablecodemax[nhood];/*kcode, totalistic=2*/
          tablebytes=(signed int) ceil(value_bits * (double)(tablemax+1)/8);
          if (totalistic==0) memmove(thisrule[0],carule[0],tablebytes);
          else if (totalistic==1) memmove(thisrule[0],cacode[0],tablebytes);
          else if (totalistic==2) memmove(thisrule[0],v_code[0],tablebytes);
                 
          free(catemp);   
          if ((catemp=(char *)calloc(tablebytes,sizeof(char)))
				             ==NULL) outof_memory("catemp");
          free(ca_original);
          if ((ca_original=(char *)calloc(tablebytes,sizeof(char)))
				             ==NULL) outof_memory("ca_original");
          memmove(ca_original,thisrule[0],tablebytes);/*restore original rule*/
 
          if (rule_dec_max>0){ 
             free(ca_tickoff);
             rule_space=(unsigned long)(pow(value_range,(double)(tablemax+1)));
             rule_space_bytes=ceil(rule_space/8);
             if ((ca_tickoff=(char *)calloc(rule_space_bytes,sizeof(char)))
				    ==NULL) outof_memory("ca_tickoff");
             ruledec=dec_equiv(thisrule[0],tablemax);
          }
          if (totalistic==0) show_rule_bottom(nhood,0,carule[0],0);
          if (totalistic==1) show_rule_bottom(nhoodm[0],0,cacode[0],0);
          else if (totalistic==2) show_rule_bottom(nhoodm[0],0,v_code[0],0);
          is[0]=0;	  
          goto prompts;
       }
       else if (rulemix==0 && rule_dec_max>0 && 
                        (is[0]=='1' || is[0]=='2' || is[0]=='3')){
	   if (is[1]=='k') autokeep=1;
	   else autokeep=0;
	   if (value_range==2 && is[0]=='1') automatic=1; 
           else if (value_range==2 && is[0]=='2') automatic=2; 
           else if (is[0]=='3') automatic=3; 
           is[0]=0;
           
           free(ca_tickoff);
           rule_space=(unsigned long)(pow(value_range,(double)(tablemax+1)));
           rule_space_bytes=ceil(rule_space/8);
           if ((ca_tickoff=(char *)calloc(rule_space_bytes,sizeof(char)))
				    ==NULL) outof_memory("ca_tickoff");
           ruledec=dec_equiv(thisrule[0],tablemax);

           equiv_count=1;
           if (automatic==1 ||automatic==2){
	     if (tot_only==0){
	         /*fprintf(stderr,
		  "\ntotalistic=%d tablemax=%d tablebytes=%d rule space=%lu, rule_space_bytes=%lu",
		     totalistic,tablemax=%d tablebytes,rule_space,rule_space_bytes);*/
                 fprintf(stderr,"\nrcode table=%d rulespace=%lu",tablemax+1,rule_space);
                 fprintf(stderr,"\n#:  s   n   r   nr");/*title*/
                 if (Dp.Hamm_step==1 && Dp.itlimit==1) fprintf(stderr,"  Dc");/*title*/
             }
             else if (tot_only==1){ /*TFOmode, totalistic rules are symmetric - reflections equal*/
	         if (totalistic==1) fprintf(stderr,"\ntcode table=%d rulespace=%lu",
			                                         tablemax+1,rule_space);
                 if (totalistic==2) fprintf(stderr,"\nkcode table=%d rulespace=%lu",
			                                         tablemax+1,rule_space);
                 fprintf(stderr,"\n#:  s   n   Dc");/*title*/
             } 
           }
           
           goto skip_prompts; 
       }
       else if (automatic) goto prompts;

       free(wnhood);         
       free(buff_average_Dt1);
       for (z=0;z<=1;z++){
         free(Dseed[z]);
         free(Dnextseed[z]);
       }
       free(Dseed);               
       free(Dnextseed);     
       free(first_state1);     
       free(comp_state1);         
       free(firstcomp_state1);

       if (rule_dec_max>0) free(ca_tickoff);   
       free(catemp);
       free(ca_original);
       
       setcolor(tempcolor);
       erase_prompt_box(2);       

       /*restore box*/
       sprintf(textb[9],"%s","boximage[11]");
       putimage(xstart-vgax(30),ystart-ysize-vgay(20),
                                   boximage[11],COPY_PUT,textb[9]);
       freeimage(boximage[11]);
}

/******************** Derrida Prompts *******************/
char get_D_para(char interupted, D_prompts *this){
   signed int xbox;
   char keep=0; /*keep old graph*/
      xbox=getx;
      if (interupted==0){
         sprintf(textb[0],"maxH (def %.3f):",this->maxH);
         outtext(textb[0]);
         input_string(4,0);	
         if (is[0]=='q') goto end;     
         if (is[0]!=13 && atof(is)>0 &&  atof(is)<=1)
	              this->maxH=atof(is);
         moveto(getx+CWidth*1.5,gety);
      }
	 
      sprintf(textb[0],"sample (def %d):",this->D_sample);
      outtext(textb[0]);
      input_string(4,0);	
      if (is[0]=='q') goto end;     
      if (is[0]!=13 && atoi(is)>0) this->D_sample=atoi(is);
     
      moveto(getx+CWidth*1.2,gety);
      /*reversed: if suppress_fuzz==0 spread is ON!*/	
      if (this->suppress_fuzz==0) outtext("tog spread (ON)-s:"); 
      else if (this->suppress_fuzz==1) outtext("tog spread (OFF)-s:"); 
      input_string(1,0);	
      if (is[0]=='q') goto end;     
      if (is[0]=='s') this->suppress_fuzz=abs(this->suppress_fuzz-1);

      moveto(getx+CWidth*1.2,gety);
      this->show_details=0;
      outtext("details-d:"); 
      input_string(1,0);	
      if (is[0]=='q') goto end;     
      if (is[0]=='d') this->show_details=1;

      moveto(xbox,gety+CHeight);
      this->end_label=1;
      if (tot_only || rulemix) outtext("label-0:");
      else outtext("label-Z/0:"); 
      input_string(1,0);	
      if (is[0]=='q') goto end;     
      if (is[0]=='0') this->end_label=0;
      else if (tot_only==0 && rulemix==0){
         if (is[0]=='Z') this->end_label=2;
      }
	
      moveto(getx+CWidth*1.2,gety);
      sprintf(textb[0],"iterations (def %d):",this->itlimit);
      outtext(textb[0]); 
      input_string(3,0);	
      if (is[0]=='q') goto end;               
      if (is[0]!=13 && atoi(is)>0) this->itlimit=atoi(is);
      
      moveto(getx+CWidth*1.2,gety);     
      sprintf(textb[0],
           "Ham steps (def %d net=%d):",this->Hamm_step, lineL);
      outtext(textb[0]); 
      input_string(4,0);	
      if (is[0]=='q') goto end;              
      if (is[0]!=13 && (atoi(is)>0 && atoi(is)<lineL)) 
                                  this->Hamm_step=atoi(is);
     
      moveto(getx+CWidth*1.2,gety);     
      outtext("keep-k:"); 
      input_string(1,0);
      if (is[0]=='k') keep=1;
      if (is[0]=='q') goto end;

    end:
      erase_prompt_box(3);
      return(keep);                       
}

/****************** draw_general_graph_frame *********************/
void draw_general_graph_frame(float this_maxH,char draw_clear,
   signed int xstart,signed int ystart,
        signed int xsize,signed int ysize,
         signed int xmaxdiv,signed int ymaxdiv){
  signed int tempx,tempy, tempx1,tempy1,z;
  unsigned char existcolor;
 

      if (draw_clear==1) return;
     
      tempx=getx;
      tempy=gety;
      existcolor=getcolor();
      /*clear space*/      
      draw_box(-1,xstart-vgax(30),ystart-ysize-vgay(20),
	       Maxx-2,/*xstart+xsize+vgax(10),*/ystart+vgax(20),1,0);
      setcolor(black);
      /*remove right edge of box*/
      line(xstart+xsize+vgax(10),ystart-ysize-vgay(20)+1,  
           xstart+xsize+vgax(10),ystart+vgax(20)-1 );

      moveto(xstart,ystart-ysize-CHeight*1.5);
      outtext("Derrida plot");
       
      setcolor(lightred);
      
      draw_box(-1,xstart,ystart-ysize,
	             xstart+xsize,ystart,1,0);

      /*draw x axis divisions*/
      moveto(xstart,ystart);         
      tempx1=getx;
      tempy1=gety;

      for (z=1;z<=xmaxdiv-1;z++){
	 moveto(getx+xsize/10,tempy1);
	 linerel(0,vgay(3));
      }
      /*draw y axis divisions*/
      moveto(xstart,ystart);
      tempx1=getx;
      for (z=1;z<=ymaxdiv-1;z++){
	 moveto(tempx1,gety-ysize/10);
	 linerel(-vgax(3),0);
      }

      /*label x axis*/
      moveto(xstart,ystart+CHeight/4);
      outtext("0");
      moveto(xstart+xsize/3,ystart+vgax(5));      
      outtext("Hamming distance (t0)");
      moveto(xstart+xsize-CWidth*2,ystart+CHeight/4);
      if (this_maxH<=0.009) sprintf(textb[0],"%.3f",this_maxH);
      else if (this_maxH<=0.09) sprintf(textb[0],"%.2f",this_maxH);
      else if (this_maxH<=0.9) sprintf(textb[0],"%.2f",this_maxH);
      else  sprintf(textb[0],"%.1f",this_maxH);
      
      setfillstyle(SOLID_FILL,black);
      bar(getx,gety,getx+CWidth*2.7,gety+CHeight);
      outtext(textb[0]);

      /*label y axis*/
      moveto(xstart-CWidth*2,ystart-CHeight);
      outtext("0");
      moveto(xstart-vgax(28),ystart-ysize/2);
      outtext("H(t+)");
      moveto(xstart-CWidth*3,ystart-ysize);
      	        
      bar(getx,gety,getx+CWidth*2.7,gety+CHeight);      
      outtext(textb[0]);

      setcolor(existcolor);
      moveto(tempx,tempy);
}


/***** if running backward, run forward n steps first, 13 May 93 ********/
void select_stepforward(void){
 signed int xbox;

   exhaustive_testing=0;
   setcolor(white);
   if (direction=='b'){
     start:
      xbox=draw_prompt_box(2);
      sprintf(textb[0],"forwards before backwards?");
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);
      sprintf(textb[0],"how many steps (def 0):");
      outtext(textb[0]);      
      input_string(5,1);
      
      if (is[0]=='q'){
	 erase_prompt_box(2);
	 return;
      }
      if (is[0]==13) stepforward=0;
      else stepforward=atol(is);

      erase_prompt_box(2);

      is[0]=is[1]=is[2]=0;
      see_ppstack=0;
      sprintf(textb[3],"%s","");
      neutral_order=0;

      if (/*rulemix==0 &&*/ oned){
         if (nonlocal==0) sprintf(textb[4],"nonlocal-x ");
         else sprintf(textb[4],"local-x ");
      }
      else sprintf(textb[4],"");

      if (lineL<=12 && value_range==2 && stepforward==0){
	if (NULLboundaries || rangeL) sprintf(textb[3],
                              "%sexh-e rmap-r ",textb[4]);
	else if (istr_graph==0 && ibaf_graph==0)
	    sprintf(textb[3],"%sexh-e rmap-r seq-s nto-o",textb[4]);
	else sprintf(textb[3],"%sexh-e rmap-r seq-s ",textb[4]);
      }
      else if (lineL<=max_exh_lu){ /*max_exh_lu depends on value_range*/
	if (NULLboundaries || rangeL) sprintf(textb[3],
                              "%sexh-e rmap-r",textb[4]);
        else sprintf(textb[3],"%sexh-e rmap-r seq-s",textb[4]);
      }
      else sprintf(textb[3],"%s",textb[4]);

      if (nonlocal){
	 sprintf(textb[2],"(nonlocal)");
         if (reorderRBN==1)
	    sprintf(textb[1],
               "view ppstack-1 +pause-2, reorder(on) tog +R,");
         else if (reorderRBN==0)
	    sprintf(textb[1],
               "view ppstack-1 +pause-2, reorder(off) tog +R,");
      }
      else{
	 sprintf(textb[2],"(local)");
	 sprintf(textb[1],"view ppstack-1:");
      }
      if (rangeL) sprintf(textb[0],"subtree %s n=%d-%d, %s",
				       textb[2],startL,endL,textb[3]);
      else sprintf(textb[0],"sub-tree %s n=%d, %s",
				       textb[2],lineL,textb[3]);
      xbox=draw_prompt_box(2);
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);
      outtext(textb[1]);
      outtext(" limit backsteps-b/+b:");
      is[1]=0;
      level_limit=Maxu;
      input_string(2,0);
      if (is[0]=='q'){
	 erase_prompt_box(2);
	 goto start;
      }

      if (is[0]=='1') see_ppstack=1;
      if (is[0]=='2') see_ppstack=2;
      if (((is[0]=='1' || is[0]=='2') && is[1]=='R') || is[0]=='R'){
         if (reorderRBN==1) reorderRBN=0;
         else if (reorderRBN==0) reorderRBN=1;
      }
      if (is[0]=='x' /*&& rulemix==0*/ && oned){
	 if (nonlocal==0) nonlocal=1;
         else if (nonlocal==1){
            unsigned int poss;            
             for (poss=0;poss<=lineL-1;poss++)
                     oneD_local_wire_cell(poss,lineL-1);
              nonlocal=0;
         }
      }    
            
      else if (lineL<=max_exh_lu){ /*max_exh_lu depends on value_range*/
	 if (is[0]=='e' || is[0]=='s') exhaustive_testing=1;
	 else if (is[0]=='r') exhaustive_testing=2;
	 else if (is[0]=='o' && NULLboundaries==0 &&
                     value_range==2 && stepforward==0
                     && istr_graph==0 && ibaf_graph==0)
		  neutral_order=1;
	 if (is[0]=='s' && NULLboundaries==0 && rangeL==0){
            erase_prompt_box(2);
            set_seq_update();
         }  	           
      }
      erase_prompt_box(2);
      if (neutral_order==0 && (is[0]=='b' || is[1]=='b')){
         draw_prompt_box(1);
         outtext("enter max backward steps (bare attractor-0, def-nolimit):");
          input_string(5,0);
          //if (atoi(is)>0) def=Maxu
          level_limit=atoi(is);
          //fprintf(stderr,"\n drpara2 level_limit=%d", level_limit);
      }
   }
}

/**********************************************************************/












