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

/****** select wiring options and wire up random Boolean network ******/
/************************** Oct 93 *******************************/
#include "edecfunc.h"
#include <unistd.h>
#if __UNIX__
#   include <fcntl.h>
#endif
/***************  list of functions in this file *************/
/*void select_wiring_options(void)*/
unsigned int set_max_zonesize(void);
void bias_random_wiring(void);
void modify_3d_zone(void);
void force_rand_links_layer(void);
void check_bi_links(void);
/*void wire_up_network(char net_arch);*/

void wiring_matrix(void);
void hypercube(void);
/*void cell_out_freq(void);
void oneD_local_wire_cell(unsigned int poss,unsigned int maxL);
void randomly_wire_cell(unsigned int poss,unsigned int maxL);*/

void randomly_wire_cell_Kbias(unsigned long tot_wires,
             unsigned int poss,unsigned int maxL);
char center_distinct(signed int wire, 
                   signed long thisposs,unsigned int poss);

unsigned int print_wiring_scheme(signed int leftbox,char makefontsmall,
    char parts, unsigned int startindex,char print_xterm);/*include postScript*/
void print_wiring_cell(signed int startx,
		   signed int starty, unsigned int poss);
void av_z_para(void);
void revise_rule_graphic(char g_type,char block_set,char show_block,
   signed int low_ii,signed int low_jj,signed int low_hh,
   signed int high_ii,signed int high_jj,signed int high_hh,
   unsigned int thisposs,unsigned int startposs,unsigned int endposs);
void cut_in_out_links(unsigned int poss);
void delete_cell(unsigned int poss);
void reset_k(char showrules,char block_set,char show_block,
	unsigned int poss,unsigned int startposs,unsigned int endposs);
void rewire_single_cell(unsigned int poss);
/********************** 1d **********************************/
void show_graphic_wiring_1d(char w_type,char showrules);
void draw_ring_of_cells(unsigned int poss,
                       float c_scale,char c_tempcolor,char c_line,
                           float wox, float woy,
                              float w_angle, float w_cyclerad);
void draw_1d_graphics_prompt(unsigned int startposs,
                                unsigned int endposs,
			        unsigned int poss,
                                unsigned int step,
                                char showrules, char block_set);
signed int jump1d(void);
void show_all_in_out_1d(char show_all,float left,float right,
    float bottom,float top,signed int textbx,signed int textby,
         float nhoodlevel,float cellx,float cscale,
           float cscale1,float csep,float csep1,
		 char direct_wire,char showrules,unsigned int poss,
                    char w_type,float wox, float woy,
                      float celly,float w_angle, float w_cyclerad);
void draw_1d_links(float bottom,float top,float nhoodlevel,
       float cellx,float cscale,float cscale1,float csep,
            char direct_wire,char showrules,unsigned int poss,char just_block);

void draw_1d_links_c(float wox, float woy,
           float cellx,float celly,
               float cscale,float csep,
                  char direct_wire,char showrules,unsigned int poss,
                    float w_angle, float w_cyclerad,char just_block);

void untangle_wiring(unsigned int poss, char showrules,
	     char *catemp, char *ca_tickoff,
		       char *nhoodbits, char *swap_nhoodbits);
void draw_save_3d_frame(float fscale, 
			signed int sboxx, signed int sboxy, char draw_3d_grid);

/******************* 2d and 3d *************************************/
void show_graphic_wiring_2d_3d(char showrules);
void draw_2d_3d_graphics_prompt(unsigned int startposs,
                                unsigned int endposs,
			        unsigned int poss,
                                char showrules, char block_set,
                                char suppress_links,char suppress_links_block);
void draw_hexagonal_2d_cell_wiring(double this_hex_rad,
       float this_cscale,
          char this_show_2d_divs,char this_dots, unsigned char thiscolor,
                unsigned char outcolor,
			   signed int x1,signed int y1);
void draw_2d_3d_links(unsigned int poss,
       float right, float start_bottom, float bottom,
       float cscale, float csep, float fscale, char direct_wire, 
        char show_pindex, char suppress_links, char outcolor, char block_set);

void jump2d_3d(signed int *ij);
char outside_2d_3d_block(unsigned int zzu,
       signed int low_ii,signed int low_jj,signed int low_hh,
       signed int high_ii,signed int high_jj,signed int high_hh);
/*void wireup_2d_nhood(signed int itop,signed int jtop,
			    signed int ibot,signed int jbot)*/
/*void wireup_3d_nhood(signed int itop,signed int jtop,
    signed int htop,signed int ibot,signed int jbot,
                                              signed int hbot)*/
/*void wire_2d_local(unsigned int poss,unsigned int *pnhood)*/
/*void wire_3d_local(unsigned int poss,unsigned int *pnhood)*/
char pndood_2or3(char dim,unsigned int poss, signed int wire);

/*void show_w_r_scheme(void)*/
char save_load_print_net(void);

/***** converting network index to ii,jj,hh and vice-versa *******/
/*            2d$
              ii=poss%i2d;
	      jj=poss/i2d;
              poss=i2d*jj + ii;

              3d
              ii=poss%i3d;
	      jj=poss%(i3d*j3d)/i3d;
              hh=poss/(i3d*j3d);    
              poss=(i3d*j3d*hh) + (i3d*jj) + ii;    */

//char hex2d=0, made global Sept2018

char defaultwiring,  /*0-no defaults, 1-regular 1d 2-2d 3-3d*/
     acceptallw,     /*=1, accept all wiring defaults*/
     fixmidwire,     /*cell wired to itself =9
		        not  "      "       =8
			    no restriction  =0  */
     distinct,       /*no duplicate wiring*/
     same_wiring;   /*apply same random wiring template everywhere*/
     
signed long zonewiring=0; /*wiring pos assigned in zone*/

unsigned long tot_wires;
unsigned int tot_bi_links,tot_self_links,
          poss_n; /* psuedo nhood wire positions, from pndood_2or3() */
char small_font; /*indicates font size has been reduced*/
signed int i_n,j_n,h_n; /*psuedo nhood wire co-ords, from pndood_2or3()*/
char ib=0,jb=0,hb=0; /*to suppress periodic boundary conditions*/
signed int i_p,i_m,j_p,j_m,h_p,h_m;
char escape_wires=0; /*some wires not confined in zone*/
signed int sup_3d_layers[4];

signed int direct_3d_link_layer=-1;
char force_layers_set=0, ca_bias=0;

/*to save the wiring graphic as a vector postscript*/
char  filename_wiring_PS[13],file_ret_w;

/*to fill 2d or 3d block sells or leave empty, March 2018*/
unsigned char block_fill_color;                          
char fill_block_cells=1,  //start with red
     gridcolor2d=0; //for 2d only: start lightgray, toggle black (if white background)

/**** defs for 2d and 3d local wiring (h_n=hh for 3d) ****/
/*see char pndood_2or3 */

/*             n2w  n2 n2e
           nw1 n1w  n1 n1e ne1
      w2n  w1n  nw  n  ne  e1n e2n
      w2   w1   w   c  e   e1  e2
      w2s  w1s  sw  s  se  e1s e2s
           sw1 s1w  s1 s1e se1  
               s2w  s2 s2e
*/

#define northwest  h_n=hh;i_n=ii+1;j_n=jj+1;\
		   if (i_n>i2d-1) i_n=0;\
		   if (j_n>j2d-1) j_n=0;
#define northwest1  h_n=hh;i_n=ii+2;j_n=jj+2;\
                    if (j_n>j2d-1) j_n=j_n%j2d;\
                    if (i_n>i2d-1) i_n=i_n%i2d;

#define north      h_n=hh;j_n=jj+1;i_n=ii;\
		   if (j_n>j2d-1) j_n=0;
#define north1     h_n=hh;j_n=jj+2;i_n=ii;\
                   if (j_n>j2d-1) j_n=j_n%j2d;
#define north2     h_n=hh;j_n=jj+3;i_n=ii;\
                   if (j_n>j2d-1) j_n=j_n%j2d;

#define north1east     h_n=hh;j_n=jj+2;i_n=ii-1;\
		       if (j_n>j2d-1) j_n=j_n%j2d;\
                       if (i_n<0) i_n=i2d-1;
#define north2east     h_n=hh;j_n=jj+3;i_n=ii-1;\
		       if (j_n>j2d-1) j_n=j_n%j2d;\
                       if (i_n<0) i_n=i2d-1;
#define north1west     h_n=hh;j_n=jj+2;i_n=ii+1;\
		       if (j_n>j2d-1) j_n=j_n%j2d;\
                       if (i_n>i2d-1) i_n=0;
#define north2west     h_n=hh;j_n=jj+3;i_n=ii+1;\
		       if (j_n>j2d-1) j_n=j_n%j2d;\
                       if (i_n>i2d-1) i_n=0;

#define northeast  h_n=hh;i_n=ii-1;j_n=jj+1;\
		   if (i_n<0) i_n=i2d-1;\
		   if (j_n>j2d-1) j_n=0;
#define northeast1  h_n=hh;i_n=ii-2;j_n=jj+2;\
                    if (j_n>j2d-1) j_n=j_n%j2d;\
                    if (i_n<0) i_n=i2d+i_n;

#define west       h_n=hh;i_n=ii+1;j_n=jj;\
		   if (i_n>i2d-1) i_n=0;
#define west1      h_n=hh;i_n=ii+2;j_n=jj;\
		   if (i_n>i2d-1) i_n=i_n%i2d;
#define west2      h_n=hh;i_n=ii+3;j_n=jj;\
		   if (i_n>i2d-1) i_n=i_n%i2d;

#define west1north      h_n=hh;i_n=ii+2;j_n=jj+1;\
		        if (i_n>i2d-1) i_n=i_n%i2d;\
                        if (j_n>j2d-1) j_n=0;
#define west2north      h_n=hh;i_n=ii+3;j_n=jj+1;\
		        if (i_n>i2d-1) i_n=i_n%i2d;\
                        if (j_n>j2d-1) j_n=0;
#define west1south      h_n=hh;i_n=ii+2;j_n=jj-1;\
		        if (i_n>i2d-1) i_n=i_n%i2d;\
                        if (j_n<0) j_n=j2d-1;
#define west2south      h_n=hh;i_n=ii+3;j_n=jj-1;\
		        if (i_n>i2d-1) i_n=i_n%i2d;\
                        if (j_n<0) j_n=j2d-1;
#define centre     h_n=hh;j_n=jj;i_n=ii;

#define east       h_n=hh;i_n=ii-1;j_n=jj;\
		   if (i_n<0) i_n=i2d-1;
#define east1      h_n=hh;i_n=ii-2;j_n=jj;\
		   if (i_n<0) i_n=i2d+i_n;
#define east2      h_n=hh;i_n=ii-3;j_n=jj;\
		   if (i_n<0) i_n=i2d+i_n;
#define east1north      h_n=hh;i_n=ii-2;j_n=jj+1;\
		        if (i_n<0) i_n=i2d+i_n;\
                        if (j_n>j2d-1) j_n=0;
#define east2north      h_n=hh;i_n=ii-3;j_n=jj+1;\
		        if (i_n<0) i_n=i2d+i_n;\
                        if (j_n>j2d-1) j_n=0;
#define east1south      h_n=hh;i_n=ii-2;j_n=jj-1;\
		        if (i_n<0) i_n=i2d+i_n;\
                        if (j_n<0) j_n=j2d-1;
#define east2south      h_n=hh;i_n=ii-3;j_n=jj-1;\
		        if (i_n<0) i_n=i2d+i_n;\
                        if (j_n<0) j_n=j2d-1;

#define southwest  h_n=hh;i_n=ii+1;j_n=jj-1;\
		   if (i_n>i2d-1) i_n=0;\
		   if (j_n<0) j_n=j2d-1;
#define southwest1  h_n=hh;i_n=ii+2;j_n=jj-2;\
                    if (j_n<0) j_n=j2d+j_n;\
                    if (i_n>i2d-1) i_n=i_n%i2d;

#define south      h_n=hh;j_n=jj-1;i_n=ii;\
		   if (j_n<0) j_n=j2d-1;
#define south1     h_n=hh;j_n=jj-2;i_n=ii;\
		   if (j_n<0) j_n=j2d+j_n;
#define south2     h_n=hh;j_n=jj-3;i_n=ii;\
		   if (j_n<0) j_n=j2d+j_n;
#define south1west     h_n=hh;j_n=jj-2;i_n=ii+1;\
		       if (j_n<0) j_n=j2d+j_n;\
                       if (i_n>i2d-1) i_n=0;
#define south2west     h_n=hh;j_n=jj-3;i_n=ii+1;\
		       if (j_n<0) j_n=j2d+j_n;\
                       if (i_n>i2d-1) i_n=0;
#define south1east     h_n=hh;j_n=jj-2;i_n=ii-1;\
		       if (j_n<0) j_n=j2d+j_n;\
                       if (i_n<0) i_n=i2d-1;
#define south2east     h_n=hh;j_n=jj-3;i_n=ii-1;\
		       if (j_n<0) j_n=j2d+j_n;\
                       if (i_n<0) i_n=i2d-1;

#define southeast  h_n=hh;i_n=ii-1;j_n=jj-1;\
		   if (i_n<0) i_n=i2d-1;\
		   if (j_n<0) j_n=j2d-1;
#define southeast1  h_n=hh;i_n=ii-2;j_n=jj-2;\
                    if (j_n<0) j_n=j2d+j_n;\
                    if (i_n<0) i_n=i2d+i_n;

/**** extra for 3d local wiring (h_n=hh for 3d) ****/
#define up          h_n=hh+1;j_n=jj;i_n=ii;\
                    if (h_n>h3d-1) h_n=0;
#define up1         h_n=hh+2;j_n=jj;i_n=ii;\
                    if (h_n>h3d-1) h_n=h_n%h3d;
#define down        h_n=hh-1;j_n=jj;i_n=ii;\
                    if (h_n<0) h_n=h3d-1;
#define down1       h_n=hh-2;j_n=jj;i_n=ii;\
                    if (h_n<0) h_n=h3d+h_n;
#define up_north    h_n=hh+1;j_n=jj+1;i_n=ii;\
                    if (j_n>j2d-1) j_n=0;\
                    if (h_n>h3d-1) h_n=0;
#define down_north  h_n=hh-1;j_n=jj+1;i_n=ii;\
                    if (j_n>j2d-1) j_n=0;\
                    if (h_n<0) h_n=h3d-1;          
#define up_west     h_n=hh+1;i_n=ii+1;j_n=jj;\
                    if (i_n>i2d-1) i_n=0;\
                    if (h_n>h3d-1) h_n=0;
#define down_west   h_n=hh-1;i_n=ii+1;j_n=jj;\
                    if (i_n>i2d-1) i_n=0;\
                    if (h_n<0) h_n=h3d-1;
#define up_east     h_n=hh+1;i_n=ii-1;j_n=jj;\
                    if (i_n<0) i_n=i2d-1;\
                    if (h_n>h3d-1) h_n=0;
#define down_east   h_n=hh-1;i_n=ii-1;j_n=jj;\
                    if (i_n<0) i_n=i2d-1;\
                    if (h_n<0) h_n=h3d-1;
#define up_south    h_n=hh+1;j_n=jj-1;i_n=ii;\
                    if (j_n<0) j_n=j2d-1;\
                    if (h_n>h3d-1) h_n=0;
#define down_south  h_n=hh-1;j_n=jj-1;i_n=ii;\
                    if (j_n<0) j_n=j2d-1;\
                    if (h_n<0) h_n=h3d-1;

/*added Sept 2013 for 3d nhoods up to 27 (3x3x3)*/
#define up_northwest  h_n=hh+1;i_n=ii+1;j_n=jj+1;\
                      if (i_n>i2d-1) i_n=0;\
		      if (j_n>j2d-1) j_n=0;\
                      if (h_n>h3d-1) h_n=0;
#define up_northeast  h_n=hh+1;i_n=ii-1;j_n=jj+1;\
		      if (i_n<0) i_n=i2d-1;\
		      if (j_n>j2d-1) j_n=0;\
                      if (h_n>h3d-1) h_n=0;
#define up_northwest  h_n=hh+1;i_n=ii+1;j_n=jj+1;\
		      if (i_n>i2d-1) i_n=0;\
		      if (j_n>j2d-1) j_n=0;\
                      if (h_n>h3d-1) h_n=0;
#define up_southeast  h_n=hh+1;i_n=ii-1;j_n=jj-1;\
		      if (i_n<0) i_n=i2d-1;\
		      if (j_n<0) j_n=j2d-1;\
                      if (h_n>h3d-1) h_n=0;
#define up_southwest  h_n=hh+1;i_n=ii+1;j_n=jj-1;\
		      if (i_n>i2d-1) i_n=0;\
		      if (j_n<0) j_n=j2d-1;\
                      if (h_n>h3d-1) h_n=0; 
#define up_northwest  h_n=hh+1;i_n=ii+1;j_n=jj+1;\
                      if (i_n>i2d-1) i_n=0;\
		      if (j_n>j2d-1) j_n=0;\
                      if (h_n>h3d-1) h_n=0;

#define down_northeast  h_n=hh-1;i_n=ii-1;j_n=jj+1;\
		        if (i_n<0) i_n=i2d-1;\
		        if (j_n>j2d-1) j_n=0;\
                        if (h_n<0) h_n=h3d-1;
#define down_northwest  h_n=hh-1;i_n=ii+1;j_n=jj+1;\
		        if (i_n>i2d-1) i_n=0;\
		        if (j_n>j2d-1) j_n=0;\
                        if (h_n<0) h_n=h3d-1;
#define down_southeast  h_n=hh-1;i_n=ii-1;j_n=jj-1;\
		        if (i_n<0) i_n=i2d-1;\
		        if (j_n<0) j_n=j2d-1;\
                        if (h_n<0) h_n=h3d-1;
#define down_southwest  h_n=hh-1;i_n=ii+1;j_n=jj-1;\
		        if (i_n>i2d-1) i_n=0;\
		        if (j_n<0) j_n=j2d-1;\
                        if (h_n<0) h_n=h3d-1; 

/**********************select wiring options, Oct 93 **************/
void select_wiring_options(){
  signed int xbox;
  char acceptallw;     /*=1, accept all wiring defaults*/
  char force_sq_hex=0;
/*
char    defaultwiring,  0-no defaults, 1-regular 1d 2-2 3-3d
	acceptallw,  	1 accept wiring defaults 
        oned            1d CA
	twod       	2d  CA
        treed           2d CA
	whatwire,   	type of wiring..
                        regular 3d=6
	                hypercube=5
			load wiring=4
			hand wire=3
			regular 2d=2
			regular 1d=1
			random=0
	nonlocal,   	regular 1d CA with homogenious  nhood, nonlocal=0
			else nonlocal=1 (including regular 2d)
	fixmidwire, 	cell wired to itself =1
			not  "      "        =2
			no restriction       =0
	distinct,   	no duplicate wiring
        same_wiring;    apply same random wiring template everywhere
	loc_twod_fonly  1-local 2d forward space-time patterns only, else-0 (redundant)
	zonesize;   size of wiring zone, if no restriction = lineL

*/

   selectw1:
    hex2d=0;
    hyper_prob=100; /*global variable*/
    acceptallw=0;
    oned=1; /*defaut network is 1d*/
    twod=threed=regular2d=regular2d_tgrid=regular3d=0;
    defaultwiring=0;
    loc_twod_fonly=0;
    nonlocal=0;
    compress_1d_local=0;
    hex2d=0;
    regular2d_tgrid=0;
    force_sq_hex=0;
    is[1]=0;
    
    sprintf(textb[0],"WIRING: special-s load-l rnd-r");    
    sprintf(textb[1],"local: 3d-3, 2d-2(hex+x square+s), 1d-def:");
    xbox=draw_prompt_box(2);
    outtext(textb[0]);
    moveto(xbox,gety+CHeight);
    outtext(textb[1]);
    input_string(2,0);
    erase_prompt_box(2);

    if (is[0]=='q') return;

    if (is[0]=='l'){
       /*load wiring*/
       whatwire=4;
       nonlocal=1;
       compress_1d_local=0;
       return;
    }
    else if (is[0]=='2'){
	defaultwiring=2;
        oned=0;
        twod=2;
        regular2d=1;
	if (nhood==3 || nhood==4 || nhood==6 || nhood==7 || nhood==10 || nhood==15 ||
                       nhood==18 || nhood==19 || nhood==22){
           regular2d_tgrid=1;
           hex2d=1;
        }
        if (is[1]=='x'){ 
           regular2d_tgrid=1;
           hex2d=1;
           force_sq_hex='x';
           is[1]=0; 
        }
        else if (is[1]=='s'){ 
           regular2d_tgrid=0;
           hex2d=0;
           force_sq_hex='s';
           is[1]=0; 
        }
	acceptallw=1;
    }
    else if (is[0]=='3'){
	defaultwiring=3;
        oned=0;
        threed=3;
        regular3d=1;
	acceptallw=1;
    }
    
    if (is[0]=='2' || is[0]=='3'){
      rangeL=startL=endL=0; /*disable range if set*/          
      if (!basinfield){
           /*this option (to set the nhood on-the-fly, 
             instead of a  wiring array) is removed*/
	   /*sprintf(textb[0],"forwards only (uses less memory, slower)-y:");
	   draw_prompt_box(1);
	   outtext(textb[0]);
	   input_string(1,0);
	   erase_prompt_box(1);
	   if (is[0]=='q') goto selectw1;
	   if (is[0]=='y') loc_twod_fonly=1;*/
       }
    }
    else if (is[0]=='r') acceptallw=1;
    else if (is[0]=='s'); /*do nout*/
    else {
	defaultwiring=1;
	acceptallw=1;
    }

   selectw2:    
    if (acceptallw==0){
        oned=twod=threed=0;
        force_sq_hex=0;	
	draw_prompt_box(1);
	if (nhood_mixed==0 && ((float)nhood==(float)log2(lineL)
			  || (float)(nhood)==(float)log2(lineL)+1)){
            sprintf(textb[1],"hypercube-h ");
	    outtext(textb[1]);	               
	}
        
	sprintf(textb[0],"3d-3, 2d-2(hex+x square+s), 1d-def: ");	
	outtext(textb[0]);
	input_string(2,0);

	if (is[0]=='q') goto selectw1;   
	else if (is[0]=='2'){
              twod=2;
              if (is[1]=='x'){ 
                 regular2d_tgrid=1;
                 hex2d=1;
                 force_sq_hex='x';
                 is[1]=0; 
              }
              else if (is[1]=='s'){ 
                 regular2d_tgrid=0;
                 hex2d=0;
                 force_sq_hex='s';
                 is[1]=0; 
              }
              else if (is[1]==0) oned=0;
        }
        else if (is[0]=='3'){ 
              threed=3;
              oned=0;
        }
	else if (is[0]=='h'){
	   hyper_prob=100;
	   sprintf(textb[0],"degrade hypercube: set %% prob (def 100):");
           draw_prompt_box(1);
	   outtext(textb[0]);	
           input_string(2,0);
	   if (is[0]==13); /*do nothing*/
	   else if (atoi(is)>=0 && atoi(is)<=100){
	       hyper_prob=atoi(is);
	   }	    
           whatwire=5;
           nonlocal=1;
           oned=1;
	   erase_prompt_box(1);
           rangeL=startL=endL=0; /*disable range if set*/ 
	   goto skip;
	}
        else oned=1;
        if (oned!=1) rangeL=startL=endL=0; /*disable range if set*/ 
    }

   selectw3:
    
    twod_local=0;
    if (defaultwiring==1) whatwire=1;
    else if (defaultwiring==2){
	whatwire=2;
        twod_local=1;
	nonlocal=1;
	compress_1d_local=0;
	twod=2;
    }
    else if (defaultwiring==3){
	whatwire=6;
	nonlocal=1;
	compress_1d_local=0;
	threed=3;
    }
    else {
	whatwire=0;
	nonlocal=1;
	compress_1d_local=0;
    }
    if (acceptallw==0){
	sprintf(textb[0],"hand wire-h,");	
        if (threed) sprintf(textb[1],"local 3d-3, 2d-2(hex+x square+s), 1d-1, ");
        else if (twod) sprintf(textb[1],"local 2d-2(hex+x square+s), 1d-1, ");
        else sprintf(textb[1],"local 1d-1, ");
	sprintf(textb[2],"random-def:");
	xbox=draw_prompt_box(2);
	outtext(textb[0]);
	moveto(xbox,gety+CHeight);
	outtext(textb[1]);
	outtext(textb[2]);
	input_string(1,0);
	erase_prompt_box(2);
 
	if (is[0]=='q') goto selectw2;
	if (is[0]=='h') whatwire=3; /*hand wire*/
	else if ((twod && is[0]=='2') || (threed && is[0]=='3')){
	   if (twod){
	      whatwire=2; /*2d local wiring*/
              regular2d=1;
              force_sq_hex=0;
              if (nhood==6 || nhood==7 || nhood==10 || nhood==15 ||
                             nhood==18 || nhood==19 || nhood==22){
                 regular2d_tgrid=1;
                 hex2d=1;
              }
              if (is[1]=='x'){ 
                 regular2d_tgrid=1;
                 hex2d=1;
                 force_sq_hex='x';
                 is[1]=0; 
              }
              else if (is[1]=='s'){ 
                 regular2d_tgrid=0;
                 hex2d=0;
                 force_sq_hex='s';
                 is[1]=0; 
              }
           }
           else if (threed) whatwire=6; /*3d local wiring*/
              
	   if (!basinfield){
              /*this option (to set the nhood on-the-fly, 
                instead of a  wiring array) is removed*/  
	      /*sprintf(textb[0],
		"forwards only (uses less memory, slower) enter-y:");
	      draw_prompt_box(1);
	      outtext(textb[0]);
	      input_string(1,0);
	      erase_prompt_box(1);
	      if (is[0]=='q') goto selectw3;
	      else if (is[0]=='y') loc_twod_fonly=1;*/
	   }
	}
	else if (is[0]=='1'){
		whatwire=1; /*1-D local wiring*/
		nonlocal=0;
	}
    }

    if (twod || threed){
      unsigned int tempdim,temp_Max_ushort,temp_Maxu;

      temp_Max_ushort=Max_ushort;
      temp_Maxu=Maxu; 
      if (basinfield){	   
	   Max_ushort=maxL_lu; /*basic 32/64 bit n=31, exLimit=1 n=35*/
	   Maxu=maxL_lu;

           if (threed){
	      if (basinfield){
                  i2d=3;
                  if (i2d > (unsigned int)pow( (double)Max_ushort,1/3.0))
		       i2d=(unsigned int)pow( (double)Max_ushort,1/3.0);
              }  
              else i2d=9;
           }
           else{ //if 2d 
	      if (basinfield){
                 i2d=4;
                 if (i2d > (unsigned int)sqrt( (double)Max_ushort))
                           i2d=(unsigned int)sqrt( (double)Max_ushort);
              }
              else i2d=40;
           }
      } 
      else{
  	  if (exLimit==0) Maxu=Maxu/512;
	  if (threed) i2d=9;
          else i2d=40;
      }

      start_twod:
       rangeL=startL=endL=0; /*disable range if set*/ 
       xbox=draw_prompt_box(2);
       if (twod){
	 if (basinfield){
            sprintf(textb[0],"2d: safe square edges<=%d, nLimit=%d", 
		    (unsigned int)sqrt( (double)Max_ushort),maxL_lu);
	 }
         else{ 
	   sprintf(textb[0],"2d: square edges, safe<=%d max=%d", //max-edge=65535", 
		  (unsigned int)sqrt( (double)Max_ushort),
		  (unsigned int)sqrt( (double)Maxu));
         }
          outtext(textb[0]);
          setcolor(lightred);
          outtext("  incr with caution!");
          setcolor(white);
          moveto(xbox,gety+CHeight);
          sprintf(textb[0],"enter i (def %d):",i2d);
       }
       else if (threed){	  
          /*note for UNIX cbrt(x) works, but not for DOS*/
          if (basinfield){
             sprintf(textb[0],"3d: safe cube edges<=%d, nLimit=%d", 
                  (unsigned int)pow( (double)Max_ushort,1/3.0)-1,maxL_lu);
	  }
          else{
	    sprintf(textb[0],"3d: cube edges, safe<=%d max=%d", //max-edge=65535",
		  (unsigned int)pow( (double)Max_ushort,1/3.0),
		  (unsigned int)pow( (double)Maxu,1/3.0));
          }
          outtext(textb[0]);
          setcolor(lightred);
          outtext("  incr with caution!");
          setcolor(white);
          moveto(xbox,gety+CHeight);
          sprintf(textb[0],"enter i (def %d):",i2d);
       }
       outtext(textb[0]);
       input_string(5,0);
       if (is[0]=='q'){
	   Max_ushort=temp_Max_ushort;
           Maxu=temp_Maxu;
           goto selectw1;
       }    
       if (is[0]!=13 || is[0]==0) i2d=atoi(is);
       if (i2d*i2d>Maxu) tempdim=Maxu/i2d;
       else tempdim=i2d;
       if (tempdim==0) tempdim=2;
       sprintf(textb[0]," j (def %d):",tempdim);
       outtext(textb[0]);
       input_string(5,0);
       if (is[0]=='q'){
	  Max_ushort=temp_Max_ushort;
          Maxu=temp_Maxu;
          goto selectw3;
       }   
       if (is[0]!=13 || is[0]==0) j2d=atoi(is);
       else j2d=tempdim;

       /*for "small" networks, axes must be <= 254 (1 byte) otherwise file problems
         in mixed wiring 255 is reserved for "notwired"
	 255x256 not allowed, 256x256 ok because this is a "big" network*/       
       if (i2d*j2d <= 65534 && (i2d>255 || j2d>255)){ /*65534=Max_ushort-1*/
          sprintf(textb[0],
                "%dx%d & n<=65534 file conflict! change i,j cont-ret:",i2d,j2d);
          draw_prompt_box(1);
	  outtext(textb[0]);
	  input_string(1,0);
	  goto start_twod;
       }

       /*for "big" networks, axes must be < 65535 (2 bytes) otherwise file problems*/  
       if (i2d>65535 || j2d>65535){ /*65534=Max_ushort-1*/
          sprintf(textb[0],
                "%dx%d 2d edge max 65535 exceeded! change i,j  cont-ret:",i2d,j2d);
          draw_prompt_box(1);
	  outtext(textb[0]);
	  input_string(1,0);
	  goto start_twod;
       }

       if (i2d*j2d>Maxu){
	  sprintf(textb[0],"%dx%d too big! max size=%d cont-ret:",
				    i2d,j2d,Maxu);
	  //moveto(xbox,gety+CHeight);
          draw_prompt_box(1);
	  outtext(textb[0]);
	  input_string(1,0);
	  goto start_twod;
       }
       if (threed){
	  /*fprintf(stderr,"\n%d %d %d =%d > Maxu=%u",i2d,i2d,j2d,
	       i2d*i2d*j2d,Maxu);*/
	  if (i2d*i2d*j2d>Maxu) /*largest cube sides was 40, now much bigger*/ 
	                  tempdim=Maxu/(i2d*j2d);
	  else tempdim=i2d;
          if (tempdim==0) tempdim=1;
          sprintf(textb[0]," h (def %d):",tempdim);
          outtext(textb[0]);
          input_string(5,0);
          if (is[0]=='q'){
	     Max_ushort=temp_Max_ushort;
             Maxu=temp_Maxu;
             goto selectw3;
          }
          if (is[0]!=13 || is[0]==0) h3d=atoi(is);
          else h3d=tempdim;

          /*for "small" networks, axes must be <= 254 (1 byte) otherwise file problems
         in mixed wiring 255 is reserved for "notwired"
	 255x256 not allowed, 256x256 ok because this is a "big" network*/       
         if (i2d*j2d*h3d <= 65534 && (i2d>255 || j2d>255 || h3d>255)){ /*65534=Max_ushort-1*/
            sprintf(textb[0],
		  "%dx%dx%d & n<=65534 file conflict! change i,j,h cont-ret:",i2d,j2d,h3d);
            draw_prompt_box(1);
	    outtext(textb[0]);
	    input_string(1,0);
	    goto start_twod;
         }

         /*for "big" networks, axes must be < 65535 (2 bytes) otherwise file problems*/  
       if (i2d>65535 || j2d>65535 || h3d>65535){ /*65534=Max_ushort-1*/
          sprintf(textb[0],
		  "%dx%dx%d 3d edge max 65535 exceeded! change i,j,h  cont-ret:",i2d,j2d,h3d);
          draw_prompt_box(1);
	  outtext(textb[0]);
	  input_string(1,0);
	  goto start_twod;
       }        
       
         if (i2d*j2d*h3d>Maxu){
	     sprintf(textb[0],"%dx%dx%d too big! max size=%d cont-ret:",
				    i2d,j2d,h3d,maxL_lu);
	     //moveto(xbox,gety+CHeight);
             draw_prompt_box(1);
	     outtext(textb[0]);
	     input_string(1,0);
	     goto start_twod;
         }
         i3d=i2d;
         j3d=j2d;
       }
       Max_ushort=temp_Max_ushort;
       Maxu=temp_Maxu;
       
       if (scale*i2d>Maxx/2) scale=(Maxx/2)/i2d;

       if (tot_only==0){ 
          free_mem_rule0();
          free_mem_all_0s_all_1s_rules();
          free_mem_rule0_extra();
	  free_mem_iso(nhood);
       }       
       free(nhoodm);
       free_mem_tcode0();
       /*if (tot_only==1) free_mem_tcode0_extra();*/
       free_mem_CA_states();

       if (threed) lineL=i3d*j3d*h3d;
       else lineL=i2d*j2d; /* twod */

       b_i2d=i2d; /*global variables: to remember original if changed*/
       b_j2d=j2d; /*in basin 2d node (drparax.c*/

       L=lineL-1;
       bytesL=(signed int)ceil(((double)(value_bits*lineL))/8);
       allocate_mem_CA_states();
       erase_prompt_box(2);       

       select_nhood_size(1);
       if (twod){
          if (nhood_mixed==0 && regular2d==1){
             if (nhood==6 || nhood==7 || nhood==10 || nhood==15 ||
                nhood==18 || nhood==19 || nhood==22){
                   regular2d_tgrid=1;
                   hex2d=1;
             }
          }
          if (force_sq_hex=='x'){ 
             regular2d_tgrid=1;
             hex2d=1;
          }
          else if (force_sq_hex=='s'){  
             regular2d_tgrid=0;
             hex2d=0;
          }
       }
       if (tot_only==0){ 
          allocate_mem_rule0(nhood);    
          allocate_mem_all_0s_all_1s_rules(nhood);
          allocate_mem_rule0_extra(nhood);
	  allocate_mem_iso(nhood);
       }
       allocate_mem_tcode0(nhood);       
       /*if (tot_only==1) allocate_mem_tcode0_extra(nhood);*/

       if (is[0]=='q') goto selectw3;
    }
    zonesize=set_max_zonesize();    
    fixmidwire=0;
    if (acceptallw==0 && whatwire==0){     
       bias_random_wiring();
       if (is[0]=='q'){
	  erase_prompt_box(4);
	  goto selectw3;
       }
    }
  skip:; 
}

/*** set zonesize to max (may be ammended to confine random wiring ****/
unsigned int set_max_zonesize(void){
  unsigned int tempzone;
    if (oned) tempzone=lineL;
    else if (twod){
         tempzone=i2d;
	 //if (tempzone>j2d) tempzone=j2d;
         if (j2d>tempzone) tempzone=j2d;
    }
    else if (threed){
         tempzone=i3d;
	 //if (tempzone>j3d) tempzone=j3d;
         if (j3d>tempzone) tempzone=j3d;
         //if (tempzone>h3d) tempzone=h3d; 
         if (h3d>tempzone) tempzone=h3d; 
         
    }
    return(tempzone);    
}

/************* bias random wiring in various ways - new***********/
void bias_random_wiring(void){
 unsigned int z,xbox;
 float tempxtext;
 char layer_range=0;

/*to skip all options*/
#define skip  is[0]=0;\
              goto endFunc
        
       ca_bias=0;
       force_layers_set=0;
       ib=jb=hb=0;
       fixmidwire=0;
       escape_wires=0;
       distinct=0;
       if (threed){
          sup_3d_layers[0]=sup_3d_layers[2]=-1;
          direct_3d_link_layer=-1;
          force_layers_set=0;
       }

       tempxtext=xtext;
       xtext=(float)(Maxx/2 +3)/CWidth;

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

       if (threed) get_prompt_box(8,9);       
       else get_prompt_box(8,6);         
       /*------------------------------------------------*/
      zone:
       /*----*/
       if (threed) xbox=draw_prompt_box(9);       
       else xbox=draw_prompt_box(6);

       {  unsigned int tempzone;

          tempzone=set_max_zonesize();
          /*sprintf(textb[0],
	     "bias random wiring: confine to local zone (max=%d def=%d):", 
		    tempzone,zonesize);*/
          sprintf(textb[0],
              "bias random wiring: confine to local zone (def|max=%d):", 
		                                             zonesize);
          outtext(textb[0]);
          sprintf(textb[0],"%d",lineL);
          input_string(strlen(textb[0]),0);

          if (is[0]=='q') goto endFunc;
          else if (is[0]=='d') {skip;}
          else if (is[0]!=13 && atoi(is)>1 && atoi(is)<=tempzone) 
	                                      zonesize=atoi(is);
          else zonesize=tempzone;
       }
       /*make wiring like local CA*/
       sprintf(textb[0]," CA-c:");
       outtext(textb[0]);
       sprintf(textb[0],"%d",lineL);
       input_string(strlen(textb[0]),0);
       if (is[0]=='q') goto zone;
       else if (is[0]=='d') {skip;}
       else if (is[0]=='c') ca_bias=1;
 
       /*------------------------------------------------*/
      release:
        /*-----*/
       escape_wires=0; /*if mixed wiring, max wires to release = lowest*/ 
        sprintf(textb[0],
         "release some wires from zone (def 0, max %d):", nhood_lb);
        moveto(xbox,gety+CHeight);
        outtext(textb[0]);
        input_string(2,0);
        if (is[0]=='q'){ 
              setpback_x_lines(1);
              goto zone;
        }
        else if (is[0]=='d') {skip;}
        else if (is[0]!=13 && atoi(is)>0 && atoi(is)<=nhood_lb) 
                    escape_wires=(char)atoi(is);

        /*------------------------------------------------*/
       periodic:
        /*------*/
        ib=jb=hb=0;
        moveto(xbox,gety+CHeight);         
        if (oned) outtext("suppress periodic boundary-s: ");
        else  outtext("suppress periodic boundary-s: i:");  
        input_string(1,0);

        if (is[0]=='q'){ 
           setpback_x_lines(1);
           goto release;
        }
        else if (is[0]=='d') {skip;}
        if (is[0]=='s') ib=1;                   
        if (twod || threed){
           outtext("  j:");
           input_string(1,0);
           if (is[0]=='q'){ 
              setpback_x_lines(1);
              goto release;
           }
           else if (is[0]=='d') {skip;}
           if (is[0]=='s') jb=1;
        }
        if (threed){
           outtext("  h:");
           input_string(1,0);
           if (is[0]=='q'){ 
              setpback_x_lines(1);
              goto release;
           }
           else if (is[0]=='d') {skip;}
           if (is[0]=='s') hb=1;
        }                
                   
       /*------------------------------------------------*/
      center_wire:
       /*---------*/
       sprintf(textb[0],
            "exclude all selfwiring-2, selfwire center wire-1:");
       moveto(xbox,gety+CHeight);
       outtext(textb[0]);
       input_string(1,0);
       if (is[0]=='q'){ 
              setpback_x_lines(1);
              goto periodic;
       }
       else if (is[0]=='d') {skip;}      
       if (is[0]=='1') fixmidwire=1;
       else if (is[0]=='2') fixmidwire=2;

       /*------------------------------------------------*/
      distinct_wiring:
       /*-------------*/
       distinct=0;
       if ((rangeL && (unsigned int)nhood<=startL) ||
	     (rangeL==0 && (unsigned int)nhood<=lineL)){
	  sprintf(textb[0],"distinct wiring (no duplication)-n:");
	  moveto(xbox,gety+CHeight);
	  outtext(textb[0]);
	  input_string(1,0);
          if (is[0]=='q'){ 
              setpback_x_lines(1);
              goto center_wire;
          }
          else if (is[0]=='d') {skip;}
	  if (is[0]=='n' && zonesize>=
			(unsigned int)nhood) distinct=1;
       }

       /*------------------------------------------------*/
       if (threed){
          suppress_layers:
          /*-------------*/
          layer_range=0;
          sup_3d_layers[0]=sup_3d_layers[2]=-1;
          moveto(xbox,gety+CHeight);
          sprintf(textb[0],"suppress links to layers (0-%d),",h3d-1);
          outtext(textb[0]);
          for (z=1; z<=4; z+=2){
             layer_range+=1;
             sprintf(textb[0]," range%d low:",layer_range);
             outtext(textb[0]);
             input_string(2,0);
             if (is[0]=='q'){ 
                setpback_x_lines(1);
                goto distinct_wiring;
             }
             else if (is[0]=='d'){ 
                sup_3d_layers[0]=sup_3d_layers[2]=-1;
                skip;
             }
             if (is[0]!=13 && atoi(is)>=0 && atoi(is)<=h3d-1) 
                                      sup_3d_layers[z-1]=atoi(is);
             sup_3d_layers[z]=sup_3d_layers[z-1];
             outtext(" high:");
             input_string(2,0);
             if (is[0]=='q'){ 
                setpback_x_lines(1);
                goto distinct_wiring;
             }
             else if (is[0]=='d'){ 
                sup_3d_layers[0]=sup_3d_layers[2]=-1;
                skip;
             }
             if (is[0]!=13 && atoi(is)>=0 && atoi(is)<=h3d-1) 
                                      sup_3d_layers[z]=atoi(is);
	  }
           
          /*------------------------------------------------*/
          force_link:
          /*-------------*/
          direct_3d_link_layer=-1;
          sprintf(textb[0],"force direct link to a layer, enter (0-%d):",
                                                   h3d-1);
          moveto(xbox,gety+CHeight);
          outtext(textb[0]);
          input_string(1,0);
          if (is[0]=='q'){ 
                setpback_x_lines(1);
                goto suppress_layers;
          }
          else if (is[0]=='d') {skip;}
          if (is[0]!=13 && atoi(is)>=0 && atoi(is)<=h3d-1) 
                                     direct_3d_link_layer=atoi(is);
          /*------------------------------------------------*/
          random_links_layers:
          /*----------------*/
          force_layers_set=0;
          sprintf(textb[0],"force random links to sepecific layers -y:");
          moveto(xbox,gety+CHeight);
          outtext(textb[0]);
          input_string(1,0);
          if (is[0]=='q'){ 
                setpback_x_lines(1);
                goto force_link;
          }
          else if (is[0]=='d') {skip;}
          if (is[0]=='y'){
             force_layers_set=1;
             force_rand_links_layer();
             goto endFunc;
          } 
       }
       /*------------------------------------------------*/
       same_wiring=0;
       moveto(xbox,gety+CHeight);      
       outtext("same wiring everywhere-e:");
       input_string(1,0);
       if (is[0]=='q'){ 
           setpback_x_lines(1);
           if (threed) goto random_links_layers;
           else goto distinct_wiring;
       }
       if (is[0]=='e') same_wiring=1;
       /*------------------------------------------------*/
      endFunc:
       uncover_free_prompt_box(8);
       erase_memory_box(0);
       xtext=tempxtext;
}

/************* bias random wiring in various ways ***********/
void modify_3d_zone(void){
 signed int xbox;

     start:
       xbox=draw_prompt_box(2);
       i_p=-1,i_m=-1,j_p=-1,j_m=-1,h_p=-1,h_m=-1;
       sprintf(textb[0],
	     "confine to local asymetric rad, enter size i_p:");
       outtext(textb[0]);
       input_string(2,0);
       if (is[0]=='q') return;
       if (is[0]!=13) i_p=atoi(is);
       sprintf(textb[0]," i_p:");
       outtext(textb[0]);
       input_string(2,0);
       if (is[0]!=13) i_m=atoi(is);
       if (is[0]=='q') goto start;
       if (is[0]!=13) i_p=atoi(is);       
       if (twod || threed){
          sprintf(textb[0]," j_p:");
          outtext(textb[0]);
          input_string(2,0);
          if (is[0]=='q') goto start;
          if (is[0]!=13) j_p=atoi(is);
          sprintf(textb[0]," j_m:");
          outtext(textb[0]);
          input_string(2,0);
          if (is[0]=='q') goto start;
          if (is[0]!=13) j_p=atoi(is);
       }
       if (threed){
          sprintf(textb[0]," h_p:");
          outtext(textb[0]);
          input_string(2,0);
          if (is[0]=='q') goto start;
          if (is[0]!=13) h_p=atoi(is);
          sprintf(textb[0]," h_m:");
          outtext(textb[0]);
          input_string(2,0);
          if (is[0]=='q') goto start;
          if (is[0]!=13) j_p=atoi(is);
       }           
        
        ib=jb=hb=0;
        moveto(xbox,gety+CHeight);         
        outtext("suppress periodic boundary-s: i:");   
        input_string(1,0);
        if (is[0]=='q') goto start;
        if (is[0]=='s') ib=1;                   
        if (twod || threed){
           outtext("  j:");
           input_string(1,0);
           if (is[0]=='q') goto start;
           if (is[0]=='s') jb=1;
        }
        if (threed){
           outtext("  h:");
           input_string(1,0);
           if (is[0]=='q') goto start;
           if (is[0]=='s') hb=1;
        }        
       else erase_prompt_box(6);
}
/***** force n links at random to layer h ******/
void force_rand_links_layer(void){

 signed int z,links_av;

          /*force_layer first calloced in main()*/
          /*free(force_layer);
          if ((force_layer=(signed int*)calloc(h3d,sizeof(signed int)))
	  ==NULL) outof_memory("force_layer");*/

          if ((force_layer=(signed int *)
	        realloc(force_layer,h3d*sizeof(signed int)))
	            ==NULL) outof_memory("force_layer");

          links_av=nhood;          
          /*moveto(xbox,gety+CHeight);*/ 
          for (z=h3d-1;z>=0;z--){
	  start:
             draw_prompt_box(1);    
             sprintf(textb[0],
                   "k=%d, enter n links to layer %d (%d available):",
                                                      nhood,z,links_av);
             outtext(textb[0]);
             input_string(1,0);
	     if (is[0]=='q'){
                if (z==h3d-1) break;
                else{
                    links_av+=force_layer[z]; 
                    z+=1;
                    goto start;
                }
             }
             if (is[0]!=13 && atoi(is)>=0 && atoi(is)<=links_av){
                force_layer[z]=atoi(is);
                links_av-=force_layer[z];
                if (links_av==0) break;
             }
          }
         
}

/********* check number of bi-directional links   *******************/
void check_bi_links(void){  
   unsigned int zu,poss,tposs;
   signed int wire,twire;
   char **bi_link;
    
          tot_bi_links=0;
	  if ((bi_link=(char**)
                  calloc(lineL,sizeof(char*)))
				  ==NULL) outof_memory("bi_link");
	  for (zu=0;zu<=lineL-1;zu++){
	     if ((bi_link[zu]=(char*)
                       calloc(lineL,sizeof(char)))
				  ==NULL) outof_memory("bi_link[]");
	  }
	  /*check bi-directional links*/ 
	  for (poss=lineL-1;poss!=Maxu;poss--){            
	     for (wire=0;wire<=nhoodm[poss]-1;wire++){	
		tposs= wiring[poss][wire];
                /*fprintf(stderr,"\n wiring[poss][wire]=[%d][%d]=%d",
		  poss,wire,wiring[poss][wire]); */    
		if (tposs!=poss){ 
		   for (twire=0;twire<=nhoodm[tposs]-1;twire++){
		     /*fprintf(stderr,"\n wiring[tposs][twire]=[%d][%d]=%d",
		       tposs,twire,wiring[tposs][twire]);*/
		      if (wiring[tposs][twire]==poss){
		         bi_link[poss][tposs]=1;                         
			 break;
		      }
		   }
		}
	     }          
          }
          for (poss=lineL-1;poss!=Maxu;poss--){
	     for (tposs=lineL-1;tposs!=Maxu;tposs--){
		 if (bi_link[poss][tposs]==1) tot_bi_links+=1;
	     }
	  }
          tot_bi_links/=2;
	  for (zu=0;zu<=lineL-1;zu++) free(bi_link[zu]);
	  free(bi_link);        
}

/*********** wire up random Boolean network, Oct 93 *******************/
void wire_up_network(char net_arch){
 unsigned int poss;   /*cell position L..0*/
       
   /*
   position of cell___          __nhood index, nhood..0
	      L..0    \        /
		       \      /
	       wiring[poss][wire] =
	       wiring position, signed int value L to 0

   */
   
 /*startwiring:*/
   for (poss=lineL-1;poss!=Maxu;poss--) celloutfreq[poss]=0;
   
   if (whatwire==5) hypercube();
  
   /*load wiring*/
   else if (whatwire==4){
     char was_loaded;
      for (poss=lineL-1;poss!=Maxu;poss--) /*to allow smaller size to be loaded*/
		    oneD_local_wire_cell(poss,lineL-1);
      was_loaded=load_save_wrs('l',NULL,1);/*dummy rule, load wiring*/
      if (was_loaded<=0){ /*if cant load*/
         is[0]='q';
         return;
      }
      nhood_lb_ub();
      if (nhood_lb!= nhood_ub) nhood_mixed=1;
      else nhood_mixed=0;      
   }
   /*random wiring*/
   else if (whatwire==0){
      if (same_wiring==1) randomly_wire_cell(0,lineL-1);
      else{
        for (poss=lineL-1;poss!=Maxu;poss--)
			   randomly_wire_cell(poss,lineL-1);
      }
   }
   /*hand wire or revise existing wiring in a matrix*/
   else if (whatwire==3) wiring_matrix(); 
   else if (whatwire==1){    /*1-D local wiring*/
	compress_1d_local=0;
	if (nhood_mixed) nonlocal=1;
	else if (defaultwiring==0){
	   sprintf(textb[0],
	     "treat local 1d as random wiring-1, and compress-2:");
	   draw_prompt_box(1);
	   outtext(textb[0]);
	   input_string(1,0);
	   erase_prompt_box(1);
	   if (is[0]=='q') goto endFunc;
	   if (is[0]=='1' || is[0]=='2') nonlocal=1;
	   if (is[0]=='2') compress_1d_local=1;
	}
	for (poss=lineL-1;poss!=Maxu;poss--)
		    oneD_local_wire_cell(poss,lineL-1);
   }
   else if (whatwire==2) wireup_2d_nhood(i2d-1,j2d-1,0,0);
   
   else if (whatwire==6) wireup_3d_nhood(i3d-1,j3d-1,h3d-1,0,0,0);
   cell_out_freq();

   //if ((defaultwiring==1 || defaultwiring==2) && !nhood_mixed) goto endFunc;
   /*after wiring set, before rules set, show the prompt for the wiring scheme*/   
   if (net_arch==1) show_w_r_scheme();
   
  endFunc:;
}

/******************* make wiring_matrix function Aug 1999 *********/
void wiring_matrix(void){ 
  signed int startx,starty,startx1,
               gridw,bottombox,leftbox,wire,z,xbox;
  char input_with_arrow,gonewgrid,makefontsmall=0,temp_font=0;
  unsigned int poss, tempposs,     /*cell position L..0*/
		 possreached,startindex,previous_start=0;

#     define wm_prompt temp_font=font_d_m_s;\
                  if (temp_font!='d') restore_def_font();\
                   setcolor(white);\
                  sprintf(textb[0],"hand wire/revise: jump-j");\
                  sprintf(textb[1],\
                       "enter wiring positions 0-%d (return on blank/0=random)",lineL-1);\
                  sprintf(textb[2],\
	               "move-arrows more-m layout-l font-f quit-q");\
                  xbox=draw_prompt_box(3);\
                  outtext(textb[0]);\
                  for (z=1;z<=2;z++){\
	             moveto(xbox,gety+CHeight);\
	             outtext(textb[z]);\
                  }\
                  if (temp_font=='s') set_small_font();/*restore current font*/\
                  else if (temp_font=='m') set_medium_font();
      
      get_prompt_box(3,3);
      wm_prompt

      small_font=makefontsmall=0;
      if (nhood_ub>13 && nhood_ub<=17) makefontsmall=1;
      else if (nhood_ub>=18) makefontsmall=2;
      if (lineL<99){
         bottombox=vgay(40)+(lineL+6)*CHeight;
         if (bottombox>Maxy-vgay(37)) bottombox=Maxy-vgay(37);
      }
      else bottombox=Maxy-vgay(37);

      if (wiring[0][0]!=Maxu) cell_out_freq(); /*was wiring allocated*/ 
          
      leftbox=trboxw;
      if ((lineL-1>9999 && nhood_ub>=9) || nhood_ub>9)
                                      leftbox=trboxw-vgax(20);

    startbox:
      if (makefontsmall==1/*medium_font*/){
         set_medium_font();
         small_font=1;
      }
      if (makefontsmall==2/*small_font*/){
         set_small_font();
         small_font=2;
      }
      else if (makefontsmall==0/*default normal_font*/){
         restore_def_font();
         small_font=0;  
      }

     
      temp_font=font_d_m_s; /*keep track of font: d=default, m=medium, s=small*/

      sprintf(textb[0],"%d",lineL);
      gridw=textwidth(textb[0])+vgax(3);
      startx=leftbox+vgax(100);      
   
      /*save area under matrix box*/
      draw_box(6,leftbox,vgay(40),Maxx-1,bottombox,0,0);

     startjump:
      startindex=previous_start;
      if (startindex==0 || startindex==Maxu) startindex=L;
      possreached=print_wiring_scheme(leftbox,makefontsmall,1,startindex,0);
      moveto(startx,vgay(50));
      startx1=startx;
      starty=gety;
      starty+=(CHeight*3)/2;

      for (poss=startindex;poss>=possreached && poss!=Maxu;poss--){	
	 startx1=startx;
	 moveto(startx1,starty);
	 for (wire=nhood_ub-1;wire>=0;wire--){
	   
	   if (wire>nhoodm[poss]-1){
	      startx1+=gridw;
	      moveto(startx1,starty);
	      continue;
	   }
	   newgrid:
	    if (rules_set && rulemix){ /*show rule in bottom box*/
	       if (small_font!=0) restore_def_font();
               if (tot_only==0) show_rule_bottom(nhoodm[poss],0,carule[poss],poss);
               else{
                  if (totalistic==1) show_rule_bottom(nhoodm[poss],0,cacode[poss],poss);
                  else if (totalistic==2) show_rule_bottom(nhoodm[poss],0,v_code[poss],poss);
               }
	       if (small_font==1) set_medium_font();
               if (small_font==2) set_small_font();
	    }
	    
	    setcolor(lightred);
	    moveto(startx1,starty);

            if (small_font==0) rectangle(startx1-vgax(2),starty+1,
			    startx1+gridw-vgax(2),starty+CHeight+1);
            else if (small_font==1) rectangle(startx1-vgax(2),starty,
			    startx1+gridw-vgax(2),starty+CHeight);
	    else if (small_font==2) rectangle(startx1-vgax(2),starty-1,
			    startx1+gridw-vgax(2),starty+CHeight-1);

	    if (wiring[poss][wire]!=Maxu){
	       setcolor(white);
	       sprintf(textb[0],"%d",wiring[poss][wire]);
	       outtext(textb[0]);
	       moveto(startx1,starty);
	    }
	    setcolor(yellow);
	    /*to allow arrows to end input as well as return*/
	    is[20]=input_with_arrow=gonewgrid=0;

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

	    if (is[0]=='m'){ /*next chunk or start again*/
	       previous_start=possreached-1;
               /*fprintf(stderr,"\n m:previous_start=%d possreached=%d poss%d",
		 previous_start,poss);*/
               goto startjump;
            }
	    else if (is[0]=='q'){
	       possreached=0;
	       goto endwhatwire3;
	    }
	    else if (is[0]=='j'){ /*jump to new cell poss*/
		  /*allocate unallocated wires to cell 0*/
		  for (poss=startindex;
			 poss>=possreached && poss!=Maxu;poss--){
		     for (wire=nhoodm[poss]-1;wire>=0;wire--){
			if (wiring[poss][wire]==Maxu)
			      wiring[poss][wire]=0;
		     }
		  }
                  temp_font=font_d_m_s; /*keep track of font: d=default, m=medium, s=small*/
                  if (temp_font!='d') restore_def_font();/*restore default for prompts*/
                  setcolor(white);
		  sprintf(textb[0],"jump to index (%d-0):",lineL-1);
                  
		  erase_prompt_box(3);
		  draw_prompt_box(1);
		  outtext(textb[0]);
		  sprintf(textb[0],"%d",lineL-1);
		  input_string(strlen(textb[0]),0);

            
		  if (isdigit(is[0]) && atoi(is)>=0 && atoi(is)<=lineL-1){
                     previous_start=atoi(is);
                  }
                  else if (is[0]=='j'){
                     previous_start=L;
                  }
		  setfillstyle(SOLID_FILL,black);
		  bar(leftbox,vgay(40),Maxx-2,bottombox);
		  startindex=poss;
                  if (temp_font=='s') set_small_font();/*restore current font*/
                  else if (temp_font=='m') set_medium_font();

                  wm_prompt
		  goto startjump;
	    }
            else if (is[0]=='l'){
               signed int boxw;

               temp_font=font_d_m_s; /*keep track of font: d=default, m=medium, s=small*/
               if (temp_font!='d') restore_def_font();/*restore default for prompts*/

               erase_prompt_box(3);
               setcolor(white);
               sprintf(textb[0],"change window width (%d-%d now=%d):",
                                              Maxx-2,Maxx/4,Maxx-leftbox);
	       erase_prompt_box(3);
	       draw_prompt_box(1);
	       outtext(textb[0]);
	       input_string(4,1);
               wm_prompt

               if (atoi(is)>=Maxx/4 && atoi(is)<=Maxx){
                  sprintf(textb[9],"%s","boximage[6]");
		  putimage(leftbox,vgay(40),boximage[6],COPY_PUT,textb[9]);
		  freeimage(boximage[6]);
                  boxw=atoi(is);
                  leftbox=Maxx-boxw;
                  if (temp_font=='s') set_small_font();/*restore current font*/
                  else if (temp_font=='m') set_medium_font();
                  goto startbox;
               }               
            }
            else if (is[0]=='f'){ /*tog fonts def-medium-small-def*/
                  if (makefontsmall==0) makefontsmall=1;
	          else if (makefontsmall==1) makefontsmall=2;
                  else if (makefontsmall==2) makefontsmall=0;
                  sprintf(textb[9],"%s","boximage[6]");
                  putimage(leftbox,vgay(40),boximage[6],COPY_PUT,textb[9]);                  
                  freeimage(boximage[6]);
                  goto startbox;
            }
	    setcolor(lightcyan);
	    
	    if (small_font==0) rectangle(startx1-vgax(2),starty+1,
			    startx1+gridw-vgax(2),starty+CHeight+1);
            else if (small_font==1) rectangle(startx1-vgax(2),starty,
			    startx1+gridw-vgax(2),starty+CHeight);
	    else if (small_font==2) rectangle(startx1-vgax(2),starty-1,
			    startx1+gridw-vgax(2),starty+CHeight-1);
            temp_font=font_d_m_s;
	      
	    tempposs=atoi(is);
	    /*arrows*/
	    if (is[20]==LeftArrow||is[20]==RightArrow||
		  is[20]==UpArrow||is[20]==DownArrow) input_with_arrow=1;
	    if (is[0]==LeftArrow||is[0]==RightArrow||
			  is[0]==UpArrow||is[0]==DownArrow) goto skip1;

	    if (is[0]!=13 || input_with_arrow==1){
	       if (tempposs!=Maxu && tempposs<=lineL-1)
				      wiring[poss][wire]=tempposs;
	    }
	    else if (input_with_arrow==0){
	       if (wiring[poss][wire]==Maxu || wiring[poss][wire]==0)
					 wiring[poss][wire]=myrand()%lineL;
	    }
	    setfillstyle(SOLID_FILL,black);
	    
	    if (small_font==0) bar(startx1-1,starty+vgax(2),startx1+gridw-vgax(3),
					    starty+CHeight);
            else if (small_font==1) bar(startx1-vgax(1),starty+vgax(1),startx1+gridw-vgax(2),
                                            starty+CHeight-vgax(1)); 
	    else if (small_font==2) bar(startx1-vgax(1),starty,startx1+gridw-vgax(1),
                                            starty+CHeight-vgax(2));
	    
	    if (wiring[poss][wire]!=Maxu)
		    sprintf(textb[0],"%d",wiring[poss][wire]);
	    setcolor(yellow);
	    moveto(startx1,starty);
	    if (wiring[poss][wire]!=Maxu)
				   outtext(textb[0]);

	    if (input_with_arrow==1) is[0]=is[20];

	   skip1:
	    switch(is[0]){
	       /*arrows:128+  75=left,77=right,72=up,80=down */
	       case LeftArrow: /*left*/
		  wire+=1;                
		  if (wire<=nhoodm[poss]-1){
		     startx1-=gridw;
		     moveto(startx1,starty);
		     gonewgrid=1;
		  }
		  else{
                     poss+=1;
                     if (poss==lineL){
                        wire-=1;
                        poss-=1; /*if at start, dont change*/ 
                        gonewgrid=1;
                        break;
                     }    
                     wire=0;		     
                     if (poss<lineL && poss<=startindex){
			starty-=(CHeight);
                        startx1=startx+gridw*(nhood_ub-1);
			moveto(startx1,starty);
			gonewgrid=1;                        
		     }                                
                     else{ /*up one row*/
                        previous_start=poss;
		        goto startjump;
                     }
		  }
		  break;
	       case RightArrow: /*right*/
		  wire-=1;
		  if (wire>=0){
		     startx1+=gridw;
		     moveto(startx1,starty);
		     gonewgrid=1;
		  }
		  else wire+=1;
		  break;
	       case UpArrow: /*up*/
		  poss+=1;
		  if (poss<lineL &&
                       poss<=startindex && wire<=nhoodm[poss]-1){
		     starty-=(CHeight);
		     moveto(startx1,starty);
		     gonewgrid=1;
		  }
                  else if (poss<lineL && poss<=startindex){
                    wire=0;
                    starty-=(CHeight);
                    startx1=startx+gridw*(nhood_ub-1);
		    moveto(startx1,starty);
                    gonewgrid=1;
                  }
                  else if (poss==lineL){
                     poss-=1; /*if at start, dont change*/ 
                     gonewgrid=1;
                  } 
                  else{ /*up one row*/
                     previous_start=poss;
		     goto startjump;
                  }
                  break;    
	       case DownArrow: /*down*/
		  poss-=1;
		  if (poss>=possreached && poss!=Maxu
				     && wire<=nhoodm[poss]-1){
		     starty+=(CHeight);
		     moveto(startx1,starty);
		     gonewgrid=1;
		  }
                  else{
                     previous_start=possreached-1;
                     goto startjump;
                  }
		  break;                  
	    }
	    if (gonewgrid==1) goto newgrid;
	    startx1+=gridw;
	 }
	 starty+=(CHeight);
         previous_start=poss-1; /*for later pages in postScript*/
      } /***next poss ****/

      endwhatwire3:
      if (possreached>0){
	/*allocate unallocated wires to cell 0*/
	 for (poss=startindex;poss>=possreached;poss--){
	    for (wire=nhoodm[poss]-1;wire>=0;wire--){
	       if (wiring[poss][wire]==Maxu)
			      wiring[poss][wire]=0;
	    }
	 }
	 startindex=possreached-1;
	 goto startjump;
      }
      
      else{
	 /*allocate unallocated wires to cell 0*/
	 for (poss=lineL-1;poss!=Maxu;poss--){
	    for (wire=nhoodm[poss]-1;wire>=0;wire--){
	       if (wiring[poss][wire]==Maxu)
			      wiring[poss][wire]=0;
	    }
	 }
      }
      cell_out_freq();
      sprintf(textb[9],"%s","boximage[6]");
      putimage(leftbox,vgay(40),boximage[6],COPY_PUT,textb[9]);
      freeimage(boximage[6]);      
      uncover_free_prompt_box(3);
      setcolor(white); 
      was_changed=1; /*if network graphic was visited, assume
                         net was changed, dont mutate next time*/
      if (font_d_m_s != 'd') restore_def_font();
}

/*********wire the network as hypercube, made sep function Aug 1999 *****/
void hypercube(void){

 char *tempString,this_bytesL,temp_value;
 signed int thiswire,wire;
 unsigned int poss;   /*cell position L..0*/

       /*hypercube nhood=log2(lineL)*/
       /*for this to work for v>2, treat as if binary: v=2*/
       this_bytesL=(signed int)ceil(((double)lineL)/8);
       if ((tempString=(char*)calloc(this_bytesL,sizeof(char)))
                            ==NULL) outof_memory("tempString");
      starthyp:
       if (hyper_prob<100){
	  nhood_mixed=1; /*set network with mixed k*/
          nhood_ub=nhood;
       }
       wires_cut=0; /*global variable, count of pruned wires*/ 
 
       for (poss=lineL-1;poss!=Maxu;poss--){      
	   thiswire=-1;
	   /*thiswirecut=0;*/
	   for (wire=0;wire<=nhood-1;wire++){
	      if (hyper_prob<100){
		float tempf;
		tempf=(float)(myrand() % 100001)/100000;
                if (tempf >  (float)hyper_prob/100){                   
		   nhoodm[poss]-=1;
		   /*keep at least 1 wire, will be made same
		    as no wires by setting rule=2 */
		   if (nhoodm[poss]==0){
		      nhoodm[poss]=1;
		      wiring[poss][0]=poss;
		   }
		   wires_cut+=1;		  
		   continue;
		}
              }
              /*wire vertex to itself*/
              if (nhood==(signed int)log2(lineL)+1 && wire==nhood-1)
                                           wiring[poss][thiswire+1]=poss;
              else{
	         /*set hypercube wiring*/
	         dec_to_bit_line(tempString,(unsigned long)poss,
			                 (signed int)nhood);
	         /*flip bit*/
	         set_bit(tempString,wire,abs(get_bit(tempString,wire)-1));

	         thiswire+=1;
                  /*for this to work for v>2, treat as if binary v=2*/
                 temp_value=value_range;
                 value_range=2;
                 wiring[poss][thiswire]=
		      (unsigned int)dec_equiv(tempString,nhood-1);
                 value_range=temp_value;
	      }
	   }           
       }
       /*print_wiring_scheme(0,0,0,lineL-1,0);*/
          
       if (hyper_prob<100){
	 signed int xbox;
	 unsigned char tempcolor;
         unsigned int max_bi;   
	  check_bi_links();   
	  if (lineL==4) max_bi=4;
	  else if (lineL==8) max_bi=12;
	  else if (lineL==16) max_bi=24;/*?*/
	   
          xbox=draw_prompt_box(3);
          sprintf(textb[0],
	    "part hcube: %%wire-prob=%d act=%.1f bi=%d/%d=%.1f%%",
	    hyper_prob,100.0-(100.0*(float)wires_cut/(nhood*lineL)),
		  tot_bi_links,max_bi,
		    100.0*(float)tot_bi_links/max_bi); 
          outtext(textb[0]);   
          moveto(xbox,gety+CHeight);
	  outtext("nhood mix=");
          for (poss=lineL-1;poss!=Maxu;poss--){      
             sprintf(textb[0],"%1x",nhoodm[poss]);
             if (nhoodm[poss]>9){
	        tempcolor=getcolor();
	        setcolor(yellow);
	        outtext(textb[0]);
	        setcolor(tempcolor);
	     }
	     outtext(textb[0]);
          }         
          sprintf(textb[0],"reset-r save-s cont-ret:");
          moveto(xbox,gety+CHeight);
          outtext(textb[0]);
	  input_string(1,0);

	  if (is[0]=='r'){
	     for (poss=lineL-1;poss!=Maxu;poss--) nhoodm[poss]=nhood;
	     hyper_prob=100;
	     sprintf(textb[1]," set %% prob (def 100): ");
	     outtext(textb[1]);	
             input_string(2,0);
	     if (is[0]==13); /*do nothing*/
	     else if (atoi(is)>=0 && atoi(is)<=100){
	        hyper_prob=atoi(is);
	     }	
             erase_prompt_box(3);
             goto starthyp;
          }
	  else if (is[0]=='s'){
             load_save_nhoodmix('s');
             if (is[0]=='q') goto starthyp;
          }
	  nhood_mixed=1;
	  erase_prompt_box(3);
       }       
       free(tempString);
}

/***** re-calculate cell output frequency & self-links *************/
void cell_out_freq(void){
 unsigned int poss;
 signed int wire;

   tot_wires=tot_self_links=0;
   for (poss=lineL-1;poss!=Maxu;poss--) celloutfreq[poss]=0;
   for (poss=lineL-1;poss!=Maxu;poss--){
     for (wire=nhoodm[poss]-1;wire>=0;wire--){
         tot_wires+=1; /*check total wires*/
         /*check self links*/
	 if (wiring[poss][wire]==poss) tot_self_links+=1;
	 if (wiring[poss][wire]!=Maxu)
		       celloutfreq[wiring[poss][wire]]+=1;
     }
   }
   if (lineL<=2500)
         check_bi_links();
}

/************ 1-D localy wire given cell, incl restrictions Nov 93 *********/
void oneD_local_wire_cell(unsigned int poss,unsigned int maxL){
 signed int wire,temp;

    /*periodic boundary conditions*/
    /*fprintf(stderr,"\n%d:",poss);*/
    if (maxL<nhoodm[poss]/2){ /*i.e. for nhood=9 lineL=3 to work*/
      for (wire=nhoodm[poss]-1;wire>=0;wire--){
	 temp=maxL+1+poss-(nhoodm[poss]/2)+wire;
	 if (temp<0) temp+=maxL+1;
	 wiring[poss][wire]=abs(temp)%(maxL+1);
      }
    }
    else{
       for (wire=nhoodm[poss]-1;wire>=0;wire--){
	  wiring[poss][wire]=
		   (maxL+1+poss-(nhoodm[poss]/2)+wire)%(maxL+1);
          /*fprintf(stderr,
                " %d",(maxL+1+poss-(nhoodm[poss]/2)+wire)%(maxL+1));*/
       }
    }
}

/************ randomly wire given cell, inc restrictions Oct 93 ************/
void randomly_wire_cell_Kbias(unsigned long tot_wires,
             unsigned int poss,unsigned int maxL){
  
  unsigned long track=0;
  unsigned int pick,zu;
  signed int wire;

  for (wire=0; wire<=nhoodm[poss]-1; wire++){
     pick=rand()%tot_wires;
     track=0;
     /*fprintf(stderr,"\npick=%lu\n",pick);*/
     for (zu=0;zu<=lineL-1;zu++){
       track+=nhoodm[zu];
       /*fprintf(stderr,"track=%lu ",track);*/
       if (track>=pick){ 
          wiring[poss][wire]=zu;
          break;
       }
     }
  }

}
/************ randomly wire given cell, inc restrictions Oct 93 ************/
void randomly_wire_cell(unsigned int poss,unsigned int maxL){

 signed long thisposs;
 char *escape,escape_wires_temp;
 char  rewire=0, retry, /*number of tries to get wiring as specified*/
       try, trytimes;   /*to avoid an infinate loop*/
                               
 signed int z,i,j,h,ii,jj,hh,
              ti,tj,th,        	 
              wire,temp,i_wire,j_wire,h_wire,
              *same_ii,*same_jj,*same_hh,
              *layer_tot;               

 unsigned int zposs;

   if (force_layers_set){ /*keep track of no of wires set at diff levels 3d*/
      if ((layer_tot=(signed int*)calloc(h3d,sizeof(signed int)))
				   ==NULL) outof_memory("layer_tot");
   }
   if (same_wiring==1){
      if ((same_ii=(signed int*)calloc(nhood,sizeof(signed int)))
				    ==NULL) outof_memory("same_ii");
      if (twod || threed){
          if ((same_jj=(signed int*)calloc(nhood,sizeof(signed int)))
				    ==NULL) outof_memory("same_jj");
      }
      if (threed){
          if ((same_hh=(signed int*)calloc(nhood,sizeof(signed int)))
				    ==NULL) outof_memory("same_hh");
      }
   }
     
   thisposs=poss;
     
   /*assign escape wires at random*/
   if (escape_wires>0){
     char temp, escape_set=0;
      if (nhood_mixed) escape_wires_temp= 
                    (char)(nhoodm[poss]*(float)escape_wires/nhood);
      else escape_wires_temp=escape_wires;     
      if (escape_wires_temp==0) escape_wires_temp=1;     
      if ((escape=(char*)calloc(nhood,sizeof(char)))
		 		   ==NULL) outof_memory("escape");
      while (escape_set<escape_wires_temp){
         for (wire=nhoodm[poss]-1;wire>=0;wire--){
            temp=(char)((myrand()%100) / 50);
            if (temp==1){ 
               escape[wire]=1;
               escape_set+=1;
            }
            if (escape_set==escape_wires_temp) break;
         }
      }
   }
   //fprintf(stderr,"\n poss=%d nhoodm[%d]=%d\n",poss,poss,nhoodm[poss]); //?? debug 
   for (wire=nhoodm[poss]-1;wire>=0;wire--){
      /*wire anywhere*/
      if (escape_wires>0 && escape[wire]==1)
                     zonewiring=myrand()%lineL;       
      /*confine random wiring to local periodic zone*/      
      else if (oned){
          trytimes=50;
          try=0;
       redo_one:;
          retry=0;
          try+=1;
          if (ca_bias && try==1) { /*wire as 1d CA first try only*/
             if (maxL<nhoodm[thisposs]/2){ /*i.e. for nhood=9 lineL=3 to work*/ 
	        /*temp=maxL+1+thisposs-(nhoodm[thisposs]/2)+wire;*/
                temp=maxL+1-(nhoodm[thisposs]/2)+wire;
	        if (temp<0) temp+=maxL+1;
	        ii=abs(temp)%(maxL+1);
      
             }
             /*else ii=(maxL+1+thisposs-(nhoodm[thisposs]/2)+wire)%(maxL+1);*/
             else ii=(maxL+1-(nhoodm[thisposs]/2)+wire)%(maxL+1);    
          }
	  else ii=(myrand()%zonesize)-zonesize/2;
          
          zonewiring=thisposs+ii;
          rewire=0;
          rewire=center_distinct(wire,thisposs,poss);
          /*try this trytimes times only - then accept*/
          if ((rewire==1) ||          
                 (ib==1 && (zonewiring<0 || zonewiring>maxL))) retry=1;
          if (try<=trytimes && retry==1) goto redo_one;

          /*if (try>trytimes/2) 
                 fprintf(stderr,"poss=%d try=%d\n",poss,try);*/

          //fprintf(stderr," ii=%d zonewiring=%ld ",ii,zonewiring);
          if (zonewiring<0) zonewiring= maxL+1-abs(zonewiring);       
	  if (zonewiring>maxL)  zonewiring= zonewiring-maxL-1;
          if (same_wiring==1) same_ii[wire]=ii; 
          //fprintf(stderr," %d",wire);
          //if (same_wiring==1) fprintf(stderr,"(%d)",same_ii[wire]);
      }
      else if (twod){
         trytimes=50;
	 i=thisposs%i2d;  /*co-ords of cell*/
	 j=thisposs/i2d;
         
         try=0;
       redo_two:;
         retry=0;
         try+=1;
         if (ca_bias && try==1){/*local 2d*/
             pndood_2or3(2,thisposs,wire); 
             zonewiring=poss_n;              
         }
         else{ //restrict rnd reach within each dimension, if required -Nov2016
	    if (zonesize<=i2d) ii=(myrand()%zonesize)-zonesize/2;
            else ii=(myrand()%i2d)-i2d/2;
            if (zonesize<=j2d) jj=(myrand()%zonesize)-zonesize/2;
            else jj=(myrand()%j2d)-j2d/2;
            ti=i2d+i+ii;         	 
            tj=j2d+j+jj;
            if (ib==1){
               if (ti<i2d || ti>2*i2d-1) retry=1;            
            }
            if (jb==1){
               if (tj<j2d || tj>2*j2d-1) retry=1;            
            }        
            if (try<=trytimes && retry==1) goto redo_two;
            else retry=0; /*try still counting*/

            i_wire=ti%i2d;         	 
            j_wire=tj%j2d;

            rewire=0;
            zonewiring=i2d*j_wire+i_wire;
         }

         rewire=center_distinct(wire,thisposs,poss);
         if (rewire==1) retry=1;
         if (try<=trytimes && retry==1) goto redo_two;  
         else try=retry=0;
         /*if (try>trytimes/4) 
             fprintf(stderr,"poss=%d try=%d\n",poss,try);*/

         if (same_wiring==1){
            same_ii[wire]=ii;
            same_jj[wire]=jj;
         }
      }
      else if (threed){
         trytimes=50;           
 	 i=thisposs%i3d;  /*co-ords of cell*/
	 j=thisposs%(i3d*j3d)/i3d;
         h=thisposs/(i3d*j3d);
         try=0;
       redo_three:;
         retry=0;
         try+=1;
         if (ca_bias && try==1){/*local 3d*/
             pndood_2or3(3,thisposs,wire); 
             zonewiring=poss_n;
             i_wire=zonewiring%i3d;  /*co-ords of cell*/
	     j_wire=zonewiring%(i3d*j3d)/i3d;
             h_wire=zonewiring/(i3d*j3d);              
         }
         else{
	    if (zonesize<=i3d) ii=(myrand()%zonesize)-zonesize/2;
            else ii=(myrand()%i3d)-i3d/2;
            if (zonesize<=j3d) jj=(myrand()%zonesize)-zonesize/2;
            else jj=(myrand()%j3d)-j3d/2;
            if (zonesize<=h3d) hh=(myrand()%zonesize)-zonesize/2;
            else jj=(myrand()%h3d)-h3d/2;
         
            ti=i3d+i+ii;         	 
            tj=j3d+j+jj;
            th=h3d+h+hh;
         
            /*suppress periodic boundary conditions*/
            if (ib==1){
               if (ti<i3d || ti>2*i3d-1) retry=1;
            }
            if (jb==1){
               if (tj<j3d || tj>2*j3d-1) retry=1;
            }
            if (hb==1){
               if (th<h3d || th>2*h3d-1) retry=1;           
            }
            if (try<=trytimes && retry==1) goto redo_three;
            else retry=0; /*try still counting*/
         
            i_wire=ti%i3d;         	 
            j_wire=tj%j3d;
            h_wire=th%h3d;

            rewire=0;
            zonewiring=(i3d*j3d*h_wire) + (i3d*j_wire) + i_wire;
         }
         rewire=center_distinct(wire,thisposs,poss);         
         if (rewire==1) retry=1;
         if (try<=trytimes && retry==1) goto redo_three;
         else retry=0;  /*try still counting*/           
         /*if (try>trytimes/4) 
                 fprintf(stderr,"poss=%d try=%d\n",poss,try);*/

         /*suppress wiring to 2 ranges of layers h*/
         if (sup_3d_layers[0]!=-1){           	   
            try=0;
            trytimes=50;
            while(((h_wire>=sup_3d_layers[0] && 
                   h_wire<=sup_3d_layers[1]) ||
                   (h_wire>=sup_3d_layers[2] && 
                   h_wire<=sup_3d_layers[3]))
                   && try<trytimes){
                   try+=1;
                   h_wire=(myrand()%h3d);
                   if (try>trytimes) break; 
            }
            /*if (try>trytimes/4) 
	       fprintf(stderr,"poss=%d try=%d\n",poss,try);*/ 
            trytimes=try=0;            
	    zonewiring=(i3d*j3d*h_wire) + (i3d*j_wire) + i_wire;
         }
         /*force random links to sepecific layers*/ 
         if (force_layers_set){
            for (z=h3d-1;z>=0;z--){
	       if (layer_tot[z]<force_layer[z]){
                  h_wire=z;
                  layer_tot[z]+=1;
                  break;
	       }
            }
            zonewiring=(i3d*j3d*h_wire) + (i3d*j_wire) + i_wire;
	 }
	 
         /*force 0 wire to coressponding cell in layer h*/
         if (direct_3d_link_layer!=-1){
	    if (wire==0){
               i_wire=i;
               j_wire=j;
               h_wire=direct_3d_link_layer;
            }
            zonewiring=(i3d*j3d*h_wire) + (i3d*j_wire) + i_wire;
         }

         if (same_wiring==1){
            same_ii[wire]=ii;
            same_jj[wire]=jj;
            same_hh[wire]=hh;
         }
      }
      wiring[thisposs][wire]=zonewiring;
   } 
      
   if (same_wiring==1){ /*duplicate wiring template everywhere*/
      for (zposs=0;zposs<=lineL-1;zposs++){
	 //fprintf(stderr,"\n zposs=%d:",zposs);
         for (wire=nhoodm[zposs]-1;wire>=0;wire--){
	     if (oned){
                signed int zonewiring1d; 
                ii=same_ii[wire];
                zonewiring1d= zposs+ii;
                //fprintf(stderr,"%d(%d %d",wire,ii,zonewiring1d);
                if (zonewiring1d<0) zonewiring1d= maxL+1-abs(zonewiring1d);
	        if (zonewiring1d>maxL)  zonewiring1d= zonewiring1d-maxL-1;
                //fprintf(stderr,"=%d) ",zonewiring1d);
                wiring[zposs][wire]=zonewiring1d;
             }     
             else if (twod){
                ii=same_ii[wire];
                jj=same_jj[wire];
                i=zposs%i2d;  /*co-ords of cell*/
	        j=zposs/i2d;	                	 
                i_wire=(i2d+i+ii)%i2d;         	 
                j_wire=(j2d+j+jj)%j2d; 
                zonewiring=i2d*j_wire+i_wire;
                wiring[zposs][wire]=zonewiring;
             }
             else if (threed){
                ii=same_ii[wire];
                jj=same_jj[wire];
                hh=same_hh[wire];
                i=zposs%i3d;  /*co-ords of cell*/
	        j=zposs%(i3d*j3d)/i3d;
                h=zposs/(i3d*j3d); 
                i_wire=(i3d+i+ii)%i3d;         	 
                j_wire=(j3d+j+jj)%j3d;
                h_wire=(h3d+h+hh)%h3d;
                zonewiring=(i3d*j3d*h_wire) + (i3d*j_wire) + i_wire;
                wiring[zposs][wire]=zonewiring;   
             }
	     //wiring[zposs][wire]=zonewiring;
	  }
       }       
       free(same_ii);
       if (twod || threed) free(same_jj);
       if (threed) free(same_hh);
    }

    same_wiring=0;
    if (escape_wires>0) free(escape);
    if (force_layers_set) free(layer_tot);    
}
/******** more wiring options center_distinct *******/
char center_distinct(signed int wire,
                   signed long thisposs,unsigned int poss){
  char rewire=0;
  unsigned int thiszonesize=0,z;

      /*force cell to wire centre of pseudo nhood to itself*/
      if (fixmidwire==1){
	if (wire==nhoodm[poss]/2) zonewiring=thisposs;       
      }
      /*exclude cell wiring to itself*/      
      else if (fixmidwire==2){
	 if (zonewiring==thisposs) rewire=1;
      }      
      /*dissallow duplicate wiring*/
      if (distinct==1){
	 if (fixmidwire==2) thiszonesize=zonesize-1;
	 if (thiszonesize>=(unsigned int)nhood){
	     for (z=nhood-1;z>wire;z--){
               if (zonewiring==wiring[poss][z]){
                    rewire=1;
                    break;
	        }
             }
	  }
      }
      return(rewire);     
}
/***************** print wiring scheme, Oct 93 *************************/
unsigned int print_wiring_scheme(signed int leftbox,char makefontsmall,
              char parts,unsigned int startindex,char print_xterm){
  signed int startx,starty,startx1,bottombox,gridw,tempx,tempy,tempx1,tempy1,
     wire,barlength;
 unsigned int poss,previous_start=0;
 char independent=0,this_postscript=0,filename_this_PS[13];
 signed int fid_temp_PS;
 char temp_basin_postScript,temp_font=0; 
   

   get_prompt_box(10,1); /*get area under prompt_box*/

   if (leftbox==0) independent=1; /*independent of  wiring_matrix()? */
   if (independent==1){
      if (nhood_ub>13 && nhood_ub<=17) makefontsmall=1;
      else if (nhood_ub>=18) makefontsmall=2;
   }
   fid_temp_PS=fid_PS;
   temp_basin_postScript=basin_postScript;

 startbox:
   if (makefontsmall==1/*medium_font*/){
      set_medium_font();
      small_font=1;
   }
   if (makefontsmall==2/*small_font*/){
      set_small_font();
      small_font=2;
   }
   else if (makefontsmall==0/*default normal_font*/){
      restore_def_font();
      small_font=0;      
   }

   temp_font=font_d_m_s; /*keep track of font: d=default, m=medium, s=small*/

   if (lineL<99){
      bottombox=vgay(40)+(lineL+6)*CHeight;
      if (bottombox>Maxy-vgay(37)) bottombox=Maxy-vgay(37);
   }
   else bottombox=Maxy-vgay(37);
   if (wiring[0][0]!=Maxu) cell_out_freq();
   
   if (leftbox==0){
      leftbox=trboxw;
      if ((lineL-1>9999 && nhood_ub>=9) || nhood_ub>9)
                                      leftbox=trboxw-vgax(20);     
   }

   sprintf(textb[0],"%d",lineL);
   gridw=textwidth(textb[0])+vgax(3);
    
   startx=leftbox+vgax(100);
   if (independent==1){
      /*save area under matrix box*/
      draw_box(6,leftbox,vgay(40),Maxx-1,bottombox,0,0);   
   }
   else{
      setfillstyle(SOLID_FILL,black);
      bar(leftbox,vgay(40),Maxx-2,bottombox);
   }
   setcolor(lightred);
   rectangle(leftbox,vgay(40),Maxx-2,bottombox);
   if (this_postscript){ /*draw outline for postscript*/
      color_ps(this_postscript-1,getcolor());/*color or gray*/
      rect_outline_ps(leftbox,vgay(40)-2*CHeight,Maxx-2-leftbox,bottombox-vgay(40));
   }
   moveto(startx,vgay(50));
   startx1=startx;
   starty=gety;
 
   /*show nhood_ub index*/
   if (print_xterm==1) fprintf(stderr,"\n         ");
   setcolor(lightred);
   for (wire=nhood_ub-1;wire>=0;wire--){
      sprintf(textb[1],"%d.",wire);
      moveto(startx1,starty);
      outtext(textb[1]);
      if (print_xterm==1) fprintf(stderr,"%s  ",textb[1]);
      if (this_postscript){          
	 color_ps(this_postscript-1,getcolor());/*color or gray*/
         nodetext_ps(3,getcolor(),textb[1],startx1,starty);
      }          
      startx1+=gridw;
   }
   moverel(gridw,0);
   tempx=tempx1=getx;
   tempy=tempy1=gety;
   if (rulemix || nhood_mixed){
      if (totalistic==0 && tot_only==0){
         if (rules_set){
            if (nhood<=3 && value_range==2) sprintf(textb[1],"rcode(hex/dec)");
	    else sprintf(textb[1],"rcode(hex)");
         }
         else sprintf(textb[1],"rcode not set");
      }
      else{
	 if (totalistic==1 ){
            if (rules_set) sprintf(textb[1],"tcode(hex)");
            else sprintf(textb[1],"tcode not set");
	 }
         if (totalistic==2){
            if (rules_set) sprintf(textb[1],"kcode(hex)");
            else sprintf(textb[1],"kcode not set");
	 }
      }
      outtext(textb[1]);
      if (this_postscript){
          color_ps(this_postscript-1,getcolor());/*color or gray*/
          nodetext_ps(3,getcolor(),textb[1],tempx,tempy);
      } 
      if (print_xterm==1) fprintf(stderr,"  %s",textb[1]);
   }
   starty+=(CHeight*3)/2;
   moveto(startx1,starty);
   
   if (independent==1) startindex=previous_start;
   if (startindex==0 || startindex==Maxu) startindex=L;
   for (poss=startindex;poss!=Maxu;poss--){  
      if (print_xterm==1) fprintf(stderr,"\n");
      startx1=startx;
      if (wiring[0][0]!=Maxu){ /*if wiring was allocated - should be*/
	 /*histogram of cell output wire frequency*/
	 moveto(startx1-vgax(55),starty);
         tempx=getx;          
         tempy=gety;
	 setfillstyle(SOLID_FILL,green);
	 barlength=celloutfreq[poss];
	 if (barlength>getx-leftbox) barlength=getx-leftbox;       
         bar(getx-barlength,gety+CHeight/4,getx,gety+CHeight-CHeight/4);

         if (this_postscript){
            color_ps(this_postscript-1,green);           
            rect_fill_ps(tempx-barlength,tempy-CHeight*.65,barlength,CHeight*.65);
         }
	 moveto(startx1-vgax(50),starty);
	 setcolor(brown);
	 sprintf(textb[1],"%d",celloutfreq[poss]);
	 outtext(textb[1]);
         if (this_postscript){
            color_ps(this_postscript-1,getcolor());/*color or gray*/
            nodetext_ps(3,getcolor(),textb[1],startx1-vgax(50),starty);
         } 
         if (print_xterm==1) fprintf(stderr,"%s",textb[1]);
      }
      setcolor(lightred);
      sprintf(textb[1],"  %d:",poss);
      
      moveto(startx1-textwidth(textb[1]),starty);
      outtext(textb[1]);
      if (this_postscript){
         sprintf(textb[1],"%d:",poss);
         color_ps(this_postscript-1,getcolor());/*color or gray*/
         nodetext_ps(3,getcolor(),textb[1],startx1-textwidth(textb[1]),starty);
      } 
      if (print_xterm==1) fprintf(stderr," %s",textb[1]);
      setcolor(white);
      startx1=startx;
      moveto(startx1,starty);
      for (wire=nhood_ub-1;wire>=0;wire--){
	 if (wire>nhoodm[poss]-1){
	    startx1+=gridw;
	    moveto(startx1,starty);
            if (print_xterm==1) fprintf(stderr,"   -");
	    continue;
	 }
	 if (wiring[poss][wire]==Maxu){
	    setcolor(lightcyan);
	    rectangle(startx1-2,starty+1,startx1+gridw-2,
					    starty+CHeight+1);
	    setcolor(white);
	 }
	 else{
	    sprintf(textb[1],"%d",wiring[poss][wire]);
	    outtext(textb[1]);
            if (this_postscript){
               color_ps(this_postscript-1,getcolor());/*color or gray*/
               nodetext_ps(3,getcolor(),textb[1],startx1,starty);
            } 
            if (print_xterm==1) fprintf(stderr,"   %s",textb[1]);
	 }

	 startx1+=gridw;
	 moveto(startx1,starty);
      }
      if (rulemix && rules_set){
        char printer;
	 moveto(getx+CWidth,gety);
         
         if (print_xterm==1){
	     printer=6; /*print on screen and to xterm*/
             fprintf(stderr,"     ");
         }
         else if (this_postscript) printer=8; /*saves hex in bigbuf*/
         else printer=5;/*print on screen only -- in wiring matrix*/
         if (tot_only==0){
           signed int tx;
	    //print_current_bitstring_hexbytes(16,1,carule[poss],nhoodm[poss],Maxx,lightcyan,printer);
            print_current_bitstring_hexbytes(1,1,carule[poss],nhoodm[poss],Maxx,lightcyan,printer);
            tx=getx+CWidth*3;
            if (nhood<=3 && value_range==2){
	      signed int tablemax;
                tablemax= (signed int)pow(2,(double)nhoodm[poss])-1;
	        //sprintf(textb[1],"   %3lu",dec_equiv(carule[poss],tablemax));
                sprintf(textb[1],"  %lu",dec_equiv(carule[poss],tablemax));
                moveto(tx,gety);
	        outtext(textb[1]);
                if (this_postscript){
                   moveto(tx,gety);
                   color_ps(this_postscript-1,getcolor());/*color or gray*/
                   nodetext_ps(3,getcolor(),textb[1],getx,gety);
                } 
                if (print_xterm==1) fprintf(stderr,"  %s",textb[1]);
	    } 
            
         }
         else if (tot_only==1){
            if (totalistic==1)
	      //print_current_bitstring_hexbytes(16,2,cacode[poss],nhoodm[poss],Maxx,lightcyan,printer);
              print_current_bitstring_hexbytes(1,2,cacode[poss],nhoodm[poss],Maxx,lightcyan,printer);
            else if (totalistic==2)
	      //print_current_bitstring_hexbytes(16,3,v_code[poss],nhoodm[poss],Maxx,lightcyan,printer);
              print_current_bitstring_hexbytes(1,3,v_code[poss],nhoodm[poss],Maxx,lightcyan,printer);
         }
         if (this_postscript){
            color_ps(this_postscript-1,lightcyan);/*color or gray*/
            nodetext_ps(3,getcolor(),bigbuf,tempx1,starty);
         }   
      }
      starty+=CHeight;
      if (starty>bottombox-CHeight*3 || poss==0){
	 if (parts){
             basin_postScript=temp_basin_postScript;
             uncover_free_prompt_box(10);/*from get_prompt_box(10,1)*/ 
             return(poss); /*if coming from wiring_matrix()*/
         }
	 else{
            if (this_postscript) close(fid_PS);
            this_postscript=0;

#           if __WATCOM__
	      startagain:
	       if (poss==0) sprintf(textb[0],
	          "print-p PScrip-P layout-l font-f jump-j(%d-0) quit-q:",lineL-1);

	       else sprintf(textb[0],
	          "more-ret print-p PScrip-P layout-l font-f jump-j(%d-0) quit-q:",
	                                                  lineL-1);
#            elif __UNIX__
               if (poss==0) sprintf(textb[0],
                   "PScrip-P layout-l font-f jump-j(%d-0) quit-q:",lineL-1);

	       else sprintf(textb[0],
                    "more-ret PScrip-P layout-l font-f jump-j(%d-0) quit-q:",
	                                                  lineL-1);
#           endif

            temp_font=font_d_m_s; /*keep track of font: d=default, m=medium, s=small*/
            if (temp_font!='d') restore_def_font();/*restore default for prompts*/

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

            if (is[0]=='P' && independent==1){ /*independent ??*/
	        print_xterm=0;/*needs to be turned off*/
	        draw_prompt_box(1);
                outtext("postScript: greyscale-P color(def)-p:");
                input_string(1,0);
                
                if (is[0]=='p'|| is[0]=='P'){
		   /*disable basin_postScript - will be restored*/
		   basin_postScript=0;
                   if (is[0]=='P') this_postscript=2;
                   else this_postscript=1;
                   /*filename for graph_postScript ascii file*/
                   file_ret_w=select_filename("SAVE","PostScript file","*.ps","my_mxPS");
	           if (file_ret_w=='q') goto abort_ps;
	           memmove(filename_this_PS,filename,13);
                   /*delete previous*/
                   fid_PS=myopen(filename_this_PS,1,0);
                   vret=write(fid_PS, "",0);
                   close(fid_PS);
                                      
                   /*start new*/
                   fid_PS=myopen(filename_this_PS,1,1);                
                   if (fid_PS==-1){
                       file_error(filename_this_PS);
                       close(fid_PS); 
                       this_postscript=0;
                       goto abort_ps;
                   }
                   psize_ps=pointsize;
                   /*reduce postScript to medium font*/
		   if (small_font==1) psize_ps=ceil((double)pointsize*.8);
                   /*reduce postScript small font*/
                   else if (small_font==2) psize_ps=ceil((double)pointsize*.6);

                   sprintf(textb[0],"%%!PS-Adobe-3.0 EPSF-3.0\n");
                   vret=write(fid_PS,textb[0],strlen(textb[0]));
                   sprintf(textb[0],"%%%%BoundingBox: %d %d %d %d\n",
		      leftbox-2, getmaxy()-bottombox-vgay(20),
                                            Maxx, getmaxy()-vgay(30));
                   vret=write(fid_PS,textb[0],strlen(textb[0]));
                   sprintf(textb[0],"");

                   if (small_font==0) prepare_basinPS(3,2); /*2 for bold default font*/                   
                   else prepare_basinPS(3,1); /*write/define initial postScipt stuff*/
		  abort_ps:
                   sprintf(textb[9],"%s","boximage[6]");
                   putimage(leftbox,vgay(40),boximage[6],COPY_PUT,textb[9]);
                   freeimage(boximage[6]);
                   /*generate the postscript file while redrawing*/
                   basin_postScript=1;/*to use basin text*/
                   if (temp_font=='s') set_small_font();/*restore current font*/
                   else if (temp_font=='m') set_medium_font();                   
                   goto startbox;
		}
	    }
            

            if (is[0]=='l' && independent==1){
               signed int boxw;
               setcolor(white);
	       sprintf(textb[0],"change window width (%d-%d now=%d):",
                                              Maxx-2,Maxx/4,Maxx-leftbox);
	       draw_prompt_box(1);
	       outtext(textb[0]);
	       input_string(4,1);
               if (atoi(is)>=Maxx/4 && atoi(is)<=Maxx){
                  sprintf(textb[9],"%s","boximage[6]");
                  putimage(leftbox,vgay(40),boximage[6],COPY_PUT,textb[9]);
                  freeimage(boximage[6]);
                  boxw=atoi(is);
                  leftbox=Maxx-boxw;
                  if (temp_font=='s') set_small_font();/*restore current font*/
                  else if (temp_font=='m') set_medium_font();
                  goto startbox;
               }
            }

            if (is[0]=='f' && independent==1){/*tog font between def-medium-small-def*/
	       if (makefontsmall==0) makefontsmall=1;
	       else if (makefontsmall==1) makefontsmall=2;
               else if (makefontsmall==2) makefontsmall=0;
               sprintf(textb[9],"%s","boximage[6]");
               putimage(leftbox,vgay(40),boximage[6],COPY_PUT,textb[9]);
               freeimage(boximage[6]);
               goto startbox;
            }

            if (temp_font=='s') set_small_font();/*restore current font*/
            else if (temp_font=='m') set_medium_font(); 
   
            if (is[0]=='q' || (is[0]==13 && poss==0)) goto endFunc;            
	    if (is[0]==13);/*if there is more -- show the next lot*/
	    else if (is[0]=='p'){
#              if __WATCOM__		
                   printimage('P',0,0,leftbox,vgay(40),Maxx,bottombox);
                   goto startagain;
#              endif
	    }
            /*jump to new index*/
	    else if (isdigit(is[0]) && atoi(is)>=0 && atoi(is)<=lineL-1) poss=atoi(is)+1;
            else if (is[0]=='j'){
                previous_start=L;
                goto startbox;
            }
            previous_start=poss-1; /*for later pages in postScript*/

	    setfillstyle(SOLID_FILL,black);
	    bar(leftbox,vgay(52)+CHeight,Maxx-2,bottombox);
	    setcolor(lightred);
	    rectangle(leftbox,vgay(40),Maxx-2,bottombox);
	    starty=vgay(50)+(CHeight*3)/2;

            	   
	 }
      }
   } /*next poss: for (poss=startindex;poss!=Maxu;poss--)*/
   print_xterm=0;
  endFunc:
   if (independent==1){
      sprintf(textb[9],"%s","boximage[6]");
      putimage(leftbox,vgay(40),boximage[6],COPY_PUT,textb[9]);
      freeimage(boximage[6]);
   }
   else{
      setfillstyle(SOLID_FILL,black);
      bar(leftbox,vgay(40),Maxx-2,bottombox);
   }
     
   fid_PS=fid_temp_PS;
   basin_postScript=temp_basin_postScript;
   /*restore default font if not returning to wiring matrix
    - otherwise keep current font*/
   if (temp_font!='d' && independent==1) restore_def_font();   
   uncover_free_prompt_box(10);/*from get_prompt_box(10,1)*/ 
   return(0);
}
/************* print wiring scheme, Oct 93 *************************/
void print_wiring_cell(signed int startx,
		   signed int starty, unsigned int poss){
 signed int startx1,wire,tempposs;
 char gonewgrid,input_with_arrow;
 unsigned char tempcolor;
   
   tempcolor=getcolor();
   moveto(startx,starty);
   startx1=startx;
   /*show nhood index*/
   setcolor(lightred);
   for (wire=nhoodm[poss]-1;wire>=0;wire--){
      sprintf(textb[0],"%d___",wire);
      moveto(startx1,starty);
      outtext(textb[0]);
      startx1+=vgax(22);
   }
   starty+=(CHeight*3)/2;
   moveto(startx1,starty);
   startx1=startx;
   setcolor(white);
   moveto(startx1,starty);
   for (wire=nhoodm[poss]-1;wire>=0;wire--){
      sprintf(textb[0],"%d",wiring[poss][wire]);
      outtext(textb[0]);
      startx1+=vgax(22);
      moveto(startx1,starty);
   }
   startx1=startx;
   moveto(startx1,starty);
   wire=nhoodm[poss]-1;
   for (wire=nhoodm[poss]-1;wire>=0;wire--){
     newgrid:
      setcolor(lightred);
      moveto(startx1,starty);
      rectangle(startx1-1,starty+1,startx1+CWidth*3,
					    starty+CHeight+1);
      setcolor(white);
      sprintf(textb[0],"%d",wiring[poss][wire]);
      outtext(textb[0]);
      moveto(startx1,starty);
      setcolor(yellow);
      /*to allow arrows to end input as well as return*/
      is[20]=input_with_arrow=gonewgrid=0;
      sprintf(textb[0],"%d",lineL-1);
      input_string(strlen(textb[0]),-1);

      if (is[0]=='q') break;
      setcolor(lightcyan);
      rectangle(startx1-1,starty+1,startx1+CWidth*3,
					    starty+CHeight+1);
      tempposs=atoi(is);
      /*arrows*/
      if (is[20]==LeftArrow||is[20]==RightArrow) input_with_arrow=1;
      if (is[0]==LeftArrow||is[0]==RightArrow) goto skip1;
      if (is[0]==13){
	 is[0]=RightArrow;
	 goto skip1;
      }
      if (is[0]!=13 || input_with_arrow==1){
	 if (tempposs>=0 && tempposs<=lineL-1) wiring[poss][wire]=tempposs;
      }
      setfillstyle(SOLID_FILL,black);
      bar(startx1,starty+2,startx1+CWidth*3-1,
					    starty+CHeight);
      sprintf(textb[0],"%d",wiring[poss][wire]);
      setcolor(yellow);
      moveto(startx1,starty);
      outtext(textb[0]);
      if (input_with_arrow==1) is[0]=is[20];
      else is[0]=RightArrow;
     skip1:
      switch(is[0]){
	 case'q': break;
	 /*arrows:128+  75=left,77=right*/
	 case LeftArrow:
	    wire+=1;
	    if (wire<=nhoodm[poss]-1){
	       startx1-=vgax(22);
	       moveto(startx1,starty);
	    }
	    else{
	       wire=0;
	       startx1+=vgax(22)*(nhoodm[poss]-1);
	       moveto(startx1,starty);
	    }
	    gonewgrid=1;
	    break;
	 case (RightArrow):
	    wire-=1;
	    if (wire>=0){
	       startx1+=vgax(22);
	       moveto(startx1,starty);
	    }
	    else{
	       wire=nhoodm[poss]-1;
	       startx1-=vgax(22)*(nhoodm[poss]-1);
	       moveto(startx1,starty);
	    }
	    gonewgrid=1;
	    break;
      }
      if (gonewgrid==1) goto newgrid;
   }
   setcolor(tempcolor);
}

/************ calculate av. and weighted av. ldz,Z ***********************/
void av_z_para(void){
 unsigned long toutwires=0;
 unsigned int zu;
 signed int xbox;
 float tlratio,tzparam,wtlratio,wtzparam,weight;
 char thisnhood;		    
                    if (tot_only==1) return;
                    if (nhood_mixed) thisnhood=nhood_ub;
                    else thisnhood=nhood;
		    if (lineL*thisnhood>100){
                       draw_prompt_box(1);
		       outtext("computing wt.av:ld  ...WAIT");
		    }
		    cell_out_freq();
		    if (nhood_mixed){
		       for (zu=lineL-1;zu!=Maxu;zu--)                          
                                      toutwires+=nhoodm[zu];
		    }
		    else toutwires+=lineL*nhood;
		    tlratio=tzparam=wtlratio=wtzparam=0;

		    for (zu=lineL-1;zu!=Maxu;zu--){
		       if (value_range==2) z_parameter_all(nhoodm[zu],0,carule[zu]);
                       else z_parameter_all_mvalue(nhoodm[zu],0,carule[zu]);
		       tlratio+=lratio;
		       tzparam+=zparam[0];
		       weight=(float)celloutfreq[zu]/toutwires;
		       wtlratio+=lratio*weight;
		       wtzparam+=zparam[0]*weight;
		    }
		    tlratio=tlratio/lineL;
		    tzparam=tzparam/lineL;
		    if (tzparam>0){
                       xbox=draw_prompt_box(2);
		       sprintf(textb[0],"av:ld-r=%g Z=%g",tlratio,tzparam);
		       outtext(textb[0]);
		       moveto(xbox,gety+CHeight);
		       sprintf(textb[0],"wt.av:ld-r=%g Z=%g cont-ret:",
			                        wtlratio,wtzparam);
		       outtext(textb[0]);
                       input_string(1,0);
                       is[0]=0;
		    }
}

/************ revise rule and/or copy to block  ********************/
void revise_rule_graphic(char g_type,char block_set,char show_block,
      signed int low_ii,signed int low_jj,signed int low_hh,
      signed int high_ii,signed int high_jj,signed int high_hh,
      unsigned int thisposs,unsigned int startposs,unsigned int endposs){
 unsigned int zzu;
 signed int tablebytes,tablemax,codebytes,codemax;
 char nhood_temp;
               
                 nhood_temp=nhoodm[thisposs];
                 if (tot_only==0){
                    tablemax= (signed int)pow(value_range,(double)nhood_temp)-1;
                    tablebytes=(signed int)ceil(value_bits * 
                                             (double)(tablemax+1)/8);
                 }
                 if (totalistic==1) codemax=
                    nhood*(value_range-1); /*max index of tcode table*/
                 else if (totalistic==2) codemax=
                    v_tablecodemax[nhood]; /*max index of kcode table*/
                 codebytes=(signed int) /*bytes for tcode or kcode, min=1*/
                    ceil(value_bits * (double)(codemax+1)/8);
		 revise_rule_or_code(thisposs);
                 if (tot_only==0) show_rule_bottom(nhoodm[thisposs],
				       0,carule[thisposs],thisposs);
                 else{
                    if (totalistic==1) show_rule_bottom(nhoodm[thisposs],0,cacode[thisposs],thisposs);
                    else if (totalistic==2) show_rule_bottom(nhoodm[thisposs],0,v_code[thisposs],thisposs);
                 }  
                 if (block_set && show_block && rulemix){
                    draw_prompt_box(1);
                    if (g_type==2 && threed) sprintf(textb[0],
                        "Copy rule to 3d block %d,%d,%d-%d,%d,%d (%d-%d)-c:",
                            low_ii,low_jj,low_hh,high_ii,high_jj,high_hh,
                                                      startposs,endposs);
                    else if (g_type==2 && twod) sprintf(textb[0],
                        "Copy rule to 2d block %d,%d-%d,%d (%d-%d)-c:",
                            low_ii,low_jj,high_ii,high_jj,startposs,endposs);
                    else sprintf(textb[0],
                        "Copy rule to 1d block %d-%d -c:",startposs,endposs);
                    outtext(textb[0]);
                    input_string(1,0);
                    if (is[0]=='c'){   
                       for (zzu=startposs;zzu<=endposs;zzu++){
                          if (g_type==2 && outside_2d_3d_block(zzu,
                                 low_ii,low_jj,low_hh,
                                 high_ii,high_jj,high_hh)==1) continue;
			  if (nhoodm[zzu]==nhood_temp){
			      if (tot_only==0) memmove(carule[zzu],// ???
                                       carule[thisposs],tablebytes);
			      else{
                                   if (totalistic==1) 
                                      memmove(cacode[zzu],cacode[thisposs],codebytes); 
                                   else if (totalistic==2) 
                                      memmove(v_code[zzu],v_code[thisposs],codebytes);
			     } 
                          }
                       }
                    }
                 }		 
}

/************ cut all input/output links to cell  ********************/
void cut_in_out_links(unsigned int poss){

    signed int z,wire,tablebytes_max,tablemax;
    unsigned int zu,*tempwiring;
               //if (tot_only==1) return;
                    if (tot_only==0)
                          tablemax= (signed int)pow(value_range,(double)nhoodm[poss])-1;
                    else{
                       if (totalistic==1)
                          tablemax=nhoodm[poss]*(value_range-1); /*max index of tcode table*/
                       else if (totalistic==2)
                          tablemax=v_tablecodemax[nhoodm[poss]]; /*max index of kcode table*/
		    }
                    tablebytes_max=(signed int)ceil(value_bits * (double)(tablemax+1)/8);   
                       
                    /*input wires*/
                    /*set all wires to disconnect*/
                    for (wire=nhoodm[poss]-1;wire>=1;wire--)
                                          wiring[poss][wire]=Maxu;
                       
                    nhoodm[poss]=1;/*reset wiring mix array*/
                    wiring[poss][0]=poss;/*self connect*/
                    /*set rcode, tcode or vcode to zero*/
                    if (tot_only==0) memmove(carule[poss],rule_all_0s,tablebytes_max);
		    else{
		       for (z=0;z<=tablemax;z++){
			  if (totalistic==1) set_value(cacode[poss],z,0);
                          else if (totalistic==2) set_value(v_code[poss],z,0);
                       }
		    }
                    /*set k=1 neutral (no change) rule 2 if v=2*/                        
                    for (z=tablemax;z>=0;z--){
		       if (value_range==2){
                          if (tot_only==0){ 
                             set_bit(carule[poss],z,z);
                          }
                          else{
			     if (totalistic==1){ 
                                set_bit(cacode[poss],z,z);
                             }
                             else if (totalistic==2){ 
                                set_bit(v_code[poss],z,z);
                             }
		          }
                       }
                       else{
                          if (tot_only==0) set_value(carule[poss],z,z);
                          else{
			     if (totalistic==1) set_value(cacode[poss],z,z);
                             else if (totalistic==2) set_value(v_code[poss],z,z);
		          }
                       }
                    }
                    /*cut all inputs from cell at poss*/
                    if (tot_only==0){
                       for (zu=0;zu<=lineL-1;zu++){
                         if (zu==poss) continue; /*avoid the cell in question*/
                         /*in case just 1 wire to poss*/ 
			 for (wire=0;wire<=nhoodm[zu]-1;wire++){
			   if (wiring[zu][wire]==poss){
			     if (wire<nhoodm[zu]-1){
                                 /*save old wiring*/  
			         if ((tempwiring=(unsigned int*)
			            calloc(nhoodm[zu],sizeof(unsigned int)))
					==NULL) outof_memory("tempwiring");
			            memmove(tempwiring,wiring[zu],
				       sizeof(unsigned int)*nhoodm[zu]);
			          /*copy wiring - shuffle back by one*/ 
                                  for (z=nhoodm[zu]-1;z>wire;z--)
				       wiring[zu][z-1]=tempwiring[z];
                                  free(tempwiring);
			     }                             
                             /*disconect left wire*/
                             if (nhoodm[zu]>1){
                                wiring[zu][nhoodm[zu]-1]=Maxu; 
                                nhoodm[zu]-=1; /*reduce wiring mix array*/
                                memmove(carule[zu],rule_all_0s,tablebytes_max);
                                tablemax= (signed int)pow(value_range,(double)nhoodm[zu])-1;
                                /*set rand rule*/
                                for (z=tablemax;z>=0;z--){
				   if (value_range==2){ 
                                      set_bit(carule[zu],z,myrand()%2);
                                   }
                                   else set_value(carule[zu],z,myrand()%value_range);
                                }
                             }
                             
                             else{ /*if just one, disconnect*/ 
                                wiring[zu][nhoodm[zu]-1]=zu;
                                memmove(carule[zu],rule_all_0s,tablebytes_max);
                                /*set rule 2*/ 
                                tablemax= (signed int)pow(value_range,(double)nhoodm[zu])-1;
                                for (z=tablemax;z>=0;z--){
			           if (value_range==2){
                                      set_bit(carule[zu],z,z);
                                   }
                                   else set_value(carule[zu],z,z);
                                }
                             }
			   }    
                         }
                       }
		    }
                    nhood_lb_ub();
}

/*************** delete a cell in mixed k RBN, inten network *******************/
void delete_cell(unsigned int poss){
  signed int wire,tablebytes_max;
  unsigned int zu;
                if (tot_only==1) return;
                          cut_in_out_links(poss);
                          /*inten the network by shuffling from the left
                          and cutting out cell at poss*/ 
                          tablebytes_max=(signed int)
                                 ceil(pow(2,(double)nhood)/8);

                          if (poss<lineL-1){
                             for (zu=poss;zu<=lineL-2;zu++){
                                /*copy wiring and shift right if ness*/
                                for (wire=nhood-1;wire>=0;wire--){
				   if (wiring[zu+1][wire]>poss 
				       && wiring[zu+1][wire]!=Maxu)
				    wiring[zu][wire]=wiring[zu+1][wire]-1;
				         
                                   else wiring[zu][wire]=wiring[zu+1][wire];
                                 }		  		      
			         nhoodm[zu]=nhoodm[zu+1]; /*copy wiring mix*/
                                 memmove(carule[zu],carule[zu+1], /*copy rule mix*/
                                             tablebytes_max*sizeof(char));
		             }
                             for (zu=0;zu<=poss-1;zu++){
                                /*copy wiring and shift right if ness*/
                                for (wire=nhood-1;wire>=0;wire--){
				   if (wiring[zu][wire]>poss 
                                         && wiring[zu][wire]!=Maxu)
				       wiring[zu][wire]-=1; 
                                }		  		      
		             }
                          }
		          free(wiring[lineL-1]);
                          free(celloutfreq);
                          free(carule[lineL-1]);
                          free_mem_CA_states();

                          L-=1;
		          lineL=L+1;
                          bytesL=(signed int)
                                       ceil(((double)(value_bits*lineL))/8);
                          if ((wiring=(unsigned int**)
                              realloc(wiring,(lineL)*sizeof(unsigned int*)))
			           ==NULL) outof_memory("**wiring");
                          if ((nhoodm=(char *)
                              realloc(nhoodm,lineL*sizeof(char)))
				   ==NULL) outof_memory("nhoodm");
                          nhood_lb_ub();
                          if ((celloutfreq=(unsigned int*)
                                   calloc(lineL,sizeof(unsigned int)))
					==NULL) outof_memory("celloutfreq");
                          if ((carule=(char**)realloc
                                        (carule,(lineL)*sizeof(char*)))
			                     ==NULL) outof_memory("carule");
		          allocate_mem_CA_states();
                          nhood_lb_ub();
}

/************ revise k for cell or block  ********************/
void reset_k(char showrules,char block_set,char show_block,
	unsigned int poss,unsigned int startposs,unsigned int endposs){ 

 char nhood_temp,newnhood,max_nhood,dim;
 unsigned int *tempwiring,zzu;
 signed int wire,z,tablemax_old, tablemax_new,
              this_startposs,this_endposs;

            if (tot_only==1) return;

                       if (block_set==0 || show_block==0) 
                                      this_startposs=this_endposs=poss;
                       else{ 
                          this_startposs=startposs;
                          this_endposs=endposs;
                       } 
                       erase_prompt_box(6);
                       draw_prompt_box(1);
		       sprintf(textb[0],
			 "reset nhood size k (1-%d):",nhood);
		       outtext(textb[0]);
		       input_string(2,0);
                       if (atoi(is)>=1 && atoi(is)<=nhood){
			   newnhood=atoi(is);
                           for (zzu=this_startposs;zzu<=this_endposs;zzu++){
                              nhood_temp=nhoodm[zzu];
		              nhoodm[zzu]=newnhood;
                              if (nhoodm[zzu]!=nhood_temp) nhood_mixed=1;
                              if (nhood_temp>newnhood){
                                 if (showrules==1){
				    /*set excess rule table bits to 0*/
                                    tablemax_old=(signed int)pow(value_range,
                                                  (double)nhood_temp)-1;
                                    tablemax_new=(signed int)pow(value_range,
                                                  (double)newnhood)-1;
                                    for (z=tablemax_old; z>tablemax_new; z--){
                                       if (value_range==2){
                                          set_bit0(carule[zzu],z);
                                       }
                                       else set_value(carule[zzu],z,0);
                                    }
                                 }
                                 /*set excess wires to disconnect*/
                                 for (wire=nhood_temp-1;wire>=newnhood;wire--)
                                    wiring[zzu][wire]=Maxu;
                              }
                              else if (nhood_temp<newnhood){
		                 /*save old wiring*/  
			         if ((tempwiring=(unsigned int*)
			            calloc(nhood_temp,sizeof(unsigned int)))
					==NULL) outof_memory("tempwiring");
			            memmove(tempwiring,wiring[zzu],
				       sizeof(unsigned int)*nhood_temp);
                                 /*wire new nhood as local*/   
                                 if (threed){
                                    dim=3;
				    wire_3d_local(zzu,wiring[zzu]);
                                 }
                                 else if (twod){
                                    dim=2;
                                    wire_2d_local(zzu,wiring[zzu]);
                                 }
                                 else if (oned){
                                    dim=1;
                                    oneD_local_wire_cell(zzu,lineL-1);
                                 }
                                 if (nhood_temp<=newnhood) 
                                                  max_nhood=nhood_temp;
                                 else max_nhood=newnhood;
                              
                                 /*copy (part or all) 
                                    old wiring if it was nonlocal*/
			         for (wire=max_nhood-1;wire>=0;wire--){
				    nhoodm[zzu]=nhood_temp;
                                    pndood_2or3(dim,zzu,wire);
                                    nhoodm[zzu]=newnhood;
                                    if (tempwiring[wire]!=poss_n)
				       wiring[zzu][wire]=tempwiring[wire];
			         }
			         free(tempwiring);
			      }
		          }
		       }
                       nhood_lb_ub();
}

/************ rewire single cell by hand  ********************/
void rewire_single_cell(unsigned int poss){
 signed int xbox;
                       erase_prompt_box(6);
                       xbox=draw_prompt_box(5);		       
		       sprintf(textb[0],"hand rewire");            
                       outtext("hand rewire: use return or arrows to move");
                       moveto(xbox,gety+CHeight);
		       sprintf(textb[0],
			"enter wiring positions 0-%d, q to complete",lineL-1);
		       outtext(textb[0]);
		       moveto(xbox,gety+CHeight);
		       print_wiring_cell(getx,gety,poss);
}

/************ show wiring layout as 1-d graphic, Dec 93 ********/
void show_graphic_wiring_1d(char w_type,char showrules){
 unsigned int zu,zzu,poss=0,thisposs,minL,posswas,step;
 signed int tablemax,tablebytes,limitbytes,
              z,zz,xbox,textbx,textby;
 float left,top,right,bottom,nhoodlevel,
       cscale,csep,cscale1,csep1,cellheight,
       rightcell,tempx,tempy,tempx2,tempy2,cellx,celly;
 char  drawcells=0,wiring_changed=0,direct_wire=0;
 unsigned int startposs=0,endposs=0;
 char  show_all,block_set=0,show_block=0,block_drawn=0,
       size_was_changed=0,
       learn_sometime=0,sculpt_basin=0; 
       
 float wox,woy; /*variables for wiring circle*/
 float w_cyclerad,w_angle;
 float c_scale;
 char c_line=0,redraw=0;
 signed int fid_temp_PS;
 char temp_basin_postScript; 

 signed int X1,Y1,X2,Y2, /*for mouse*/
            mxtemp=0,mytemp=0; /*for Watcom mouse move*/

 signed int i3,j3,h3,ii,jj,old_ii,old_jj,old_hh,oldposs=0;
 char suppress_links=0,suppress_links_block=0;

 char event_happened=0,test_key,
      inside_rect=0; /*for mouse*/
    
#if __WATCOM__ 
    void *blockimage;
    unsigned long imsize;/*imsize, not xwindows*/
#elif __UNIX__
    Pixmap *blockimage;
#endif
 
   fid_temp_PS=fid_PS;
   temp_basin_postScript=basin_postScript;
   inside_wiring_graphic=1; /*need this to show rules in xterm with 'x' */
   wiring_postscript=0; /*global variable - 
                          needed for draw_save_3d_frame .. draw_axon_plane*/
   top: /*goback here if redraw, or length was reduced with 'd'*/
        /*scale for equivalent 925x694*/
        //cscale=7;
        //csep=3;
        cscale=7*(Maxx+1)/925; /*readjust for hires Dell 3200x1800 (def ddlab 2112x1584)*/
        csep=3*(WinMaxy+1)/694;	
        get_prompt_box(3,6);/*get area under prompt box, 6 lines*/
	
        if (w_type==2){ /*circle layout*/
           w_cyclerad=100+lineL/4;
           if (w_cyclerad>=133) w_cyclerad=133;
           w_cyclerad=vgax(w_cyclerad);

	   bottom=vgay(390);
	   top=bottom-w_cyclerad*2;
	   left=vgax(60);
           right=left+w_cyclerad*2;
 
           /*get area under data box, no outline or background*/
	   draw_box(3,left-vgax(40)+2,bottom+vgay(40)-vgay(17),
			vgax(620),bottom+vgay(40)-2,0,0);
           /*whole box*/           
           draw_box(6,left-vgax(40),top-vgay(50),
			       right+vgax(40),bottom+vgay(40),1,0);
           if (wiring_postscript){
              color_ps(wiring_postscript-1,lightred);
              rect_outline_ps(left-vgax(40),top-vgay(50),
			 abs(left-vgax(40)-(right+vgax(40))),
			      abs(bottom+vgay(40)-(top-vgay(50))));
           }

           wox=left+w_cyclerad;
           woy=bottom-w_cyclerad-vgax(10);

           X1=wox-w_cyclerad*1.2;
           Y1=woy-w_cyclerad*1.2;
           X2=wox+w_cyclerad*1.2;
           Y2=woy+w_cyclerad*1.2;

           c_scale=PI*w_cyclerad/(lineL*1.2); 
           if (c_scale>w_cyclerad/5) c_scale=w_cyclerad/5;
           if (c_scale<3) c_line=1;
                
           w_angle=2*PI/lineL;           
        }        
        
        else if (w_type==1){
	   bottom=vgay(390);
	   top=bottom-vgay(100);
	   left=vgax(60);
	   minL=lineL;
	   if (minL<10) minL=10;
	   right=left+cscale*minL+vgax(200);
	   if (right>Maxx-vgax(60)) right=Maxx-vgax(60);
	   if (right<Maxx*2/3) right=Maxx*2/3;

           X1=left;
           Y1=top-cscale*2;
           X2=left+cscale*lineL;
           if (X2>Maxx-vgax(60)) X2=Maxx-vgax(60);
           Y2=bottom+cscale*2;
           //fprintf(stderr,"\n oned: %d %d %d %d",X1,Y1,X2,Y2);
           /*setcolor(green);
	   rectangle(X1,Y1,X2,Y2);//outline, also mouse border
           setcolor(white);*/

  
#          if __WATCOM__		 
                    imsize=imagesize((signed int)left,
                                  (signed int)(top+cscale-csep+1),
                                    (signed int)right,
                                      (signed int)(bottom-1));
		    if ((blockimage=malloc(imsize))==NULL){
		       draw_prompt_box(1);
		       sprintf(textb[0],
		       "out of memory! blockimage, return-abort");
		       getch();
		       final_quit();
		    }
#          elif __UNIX__
                    /*allocate mem for pixmap pointer (long)*/
                    if ((blockimage = 
                    (Pixmap *)malloc(sizeof(Pixmap *))) == NULL)
		                 outof_memory("Pixmap pointer");
                    *blockimage = 0;
#          endif	
   
           /*whole box*/
	   draw_box(6,left-vgax(40),top-vgay(50),
			       right+vgax(40),bottom+vgay(40),1,0);
           if (wiring_postscript){
              color_ps(wiring_postscript-1,lightred);
              rect_outline_ps(left-vgax(40),top-vgay(50),
			 abs(left-vgax(40)-(right+vgax(40))),
			      abs(bottom+vgay(40)-(top-vgay(50))));
           }
	   if (right>=left+cscale*lineL){ //separate cells
		cscale1=cscale;
		csep1=csep;
		drawcells=1;
	   }
	   else{
	     cscale1=(right-left)/lineL; //continuous cells
		csep1=0;
		drawcells=2;
	   }
	   /*draw top and bottom cells*/
	   for (zz=0;zz<=1;zz++){
	     moveto(left,top+zz*vgay(100));
	     setfillstyle(SOLID_FILL,lightgray);/*darkgray to print*/
	     //fprintf(stderr,"\n%d %.1f",lineL,right-left)/2; //if enough space draw squares else lines
	     for (zu=lineL-1;zu!=Maxu;zu--){
	        if (zz==0){ /*top*/
		    
		    if (lineL>(right-left)/2){ 
                       line(getx,gety,getx,gety+cscale-csep);
                       if (wiring_postscript){
                           color_ps(wiring_postscript-1,white);
                           line_ps(getx,gety,getx,gety+cscale-csep);
                       }
                    }
		    else{
                        bar3d(getx,gety,getx+cscale1-csep1,
					    gety+cscale-csep,0,1);
                        if (wiring_postscript){
                           color_ps(wiring_postscript-1,lightgray);
                           rect_fill_ps(getx,gety,cscale1-csep1,
					cscale-csep);
                           color_ps(wiring_postscript-1,white);
                           rect_outline_ps(getx,gety,cscale1-csep1,
					cscale-csep);
			}
		    }  
	         }
		
	         else{
		    /*outwires adjusted (enlarged with vgax) for highres Dell*/
		    if (nonlocal){ /*bottom cells*/
		       cellheight=vgay(celloutfreq[zu]);		       
		       if (cellheight>vgay(25)) cellheight=vgay(25);
		    }
		    else cellheight=cscale-csep;
		    
		    if (lineL>(right-left)/2){
                        line(getx,gety,getx,gety+cellheight);
			/*for hires Dell 3200x1800 -- unpredictable screen lines without this - ??
		          though line_ps( was ok*/
			while(event_ready()==0) break;
                        if (wiring_postscript){
                           color_ps(wiring_postscript-1,white);
                           line_ps(getx,gety,getx,gety+cellheight);
                        }
                    }
		    else{ 
                        bar3d(getx,gety,getx+cscale1-csep1,
						gety+cellheight,0,1);
                        if (wiring_postscript){
                           color_ps(wiring_postscript-1,lightgray);
                           rect_fill_ps(getx,gety,cscale1-csep1,
					cellheight);
                           color_ps(wiring_postscript-1,white);
                           rect_outline_ps(getx,gety,cscale1-csep1,
					cellheight);
                        }
		    }
	         }
	         if (drawcells==1){ 
                     moverel(cscale,0);
                     if (wiring_postscript) moveto_ps(getx+cscale,0);
                 }
		 else{
                     moveto(left+cscale1*(lineL-zu),gety);
                     if (wiring_postscript) moveto_ps(left+cscale1*(lineL-zu),gety);
                 }
	      }
	   }
 
	   /*add labels to diagram*/
	   if (drawcells==1) rightcell=getx;
	   else rightcell=right;
           moveto(rightcell+vgax(5),top);
           linerel(vgax(15),0);
           if (wiring_postscript) 
	     line_ps(rightcell+vgax(5),top,rightcell+vgax(5)+vgax(15),top);
           moverel(0,-CHeight);
           if (wiring_postscript)
	        nodetext_ps(3,bground,"t0",getx,gety+CHeight*.8);        
	   outtext("t0");          
           moveto(rightcell+vgax(5),bottom);
           linerel(vgax(15),0);
           if (wiring_postscript) 
	     line_ps(rightcell+vgax(5),bottom,rightcell+vgax(5)+vgax(15),bottom);
           if (wiring_postscript)
	        nodetext_ps(3,bground,"t1",getx,gety+CHeight*.8);  
	   outtext("t1");
	   moveto(left,top-cscale-CHeight);
           if (wiring_postscript)
	        nodetext_ps(3,bground,"|",getx,gety+CHeight); 
	   outtext("|");
	   moverel(-textwidth("cell |")/2,-CHeight);	
	   sprintf(textb[3],"cell %d",L);
           if (wiring_postscript)
	        nodetext_ps(3,bground,textb[3],getx+CWidth/2,gety+CHeight); 
	   outtext(textb[3]);
	   moveto(rightcell-cscale1,top-cscale-CHeight);
           if (wiring_postscript)
	        nodetext_ps(3,bground,"|",getx,gety+CHeight); 
	   outtext("|");
	   moverel(-textwidth("cell |")/2,-CHeight);
           if (lineL>8) sprintf(textb[3],"%s","cell 0");
	   else         sprintf(textb[3],"       %s","0");
           if (wiring_postscript)
	        nodetext_ps(3,bground,textb[3],getx+CWidth/4,gety+CHeight); 
           outtext(textb[3]);
	
	   nhoodlevel=bottom-vgay(20);
	   moveto(left+(cscale1-csep1)/2,nhoodlevel);
	}

	step=lineL/10; /*for up and down arrows*/
	if (lineL<20) step=2;
	tempx=getx;
	tempy=gety;

        if (redraw==0) direct_wire=0;/*default: show preudo-nhood for 1d*/
        if (redraw==0 && size_was_changed==0){
	   if (outer_tot==1) poss=0;
           else poss=L/2; /*start in centre*/
        }
        size_was_changed=0;

        draw_1d_graphics_prompt(startposs,endposs,poss,step,
                                            showrules, block_set);
	textbx=getx;
	textby=gety;

	moveto(tempx,tempy); /*nhoodlevel*/
        if (w_type==1)
               cellx=left+(cscale1-csep1)/2+cscale1*(float)(L-poss);
        else{ 
           cellx=getx;
           celly=gety;
        }
        show_all=0;

	while(1){ 
           tablemax=(signed int)pow(value_range,(double)nhoodm[poss])-1;
           tablebytes=(signed int)ceil(
                      value_bits * pow(value_range,(double)nhoodm[poss])/8);
           /*dont print hex if table bigger that v2k5 or equiv*/
           limitbytes=(signed int)ceil(pow(2,(double)5)/8);
	   if (showrules && (rulemix ||
                  (outer_tot==1 && poss<value_range  ) ) ){
	      if (tot_only==0) show_rule_bottom(nhoodm[poss],0,carule[poss],poss);
              else{
                  if (totalistic==1) show_rule_bottom(nhoodm[poss],0,cacode[poss],poss);
                  else if (totalistic==2) show_rule_bottom(nhoodm[poss],0,v_code[poss],poss);
              }
	   }
           
           if (w_type==1){
               draw_box(-1,left-vgax(40),bottom+vgay(40)-vgay(15),
			       right+vgax(40),bottom+vgay(40),1,0);
               if (wiring_postscript){
                  color_ps(wiring_postscript-1,lightred);
                  rect_outline_ps(left-vgax(40),bottom+vgay(40)-vgay(15),
			 abs(left-vgax(40)-(right+vgax(40))),
				  abs(bottom+vgay(40)-vgay(15)-(bottom+vgay(40))));
               }
               setviewport((signed int)(left-vgax(40)),
                            (signed int)(bottom+vgay(40)-vgay(15)),
			     (signed int)(right+vgax(40)),
                              (signed int)(bottom+vgay(40)), 0);
           }
           else{
               draw_box(-1,left-vgax(40)+2,bottom+vgay(40)-vgay(17),
			vgax(620),bottom+vgay(40)-2,1,0);
               if (wiring_postscript){
                  color_ps(wiring_postscript-1,black);
                  rect_fill_ps(left-vgax(40)+2,bottom+vgay(40)-vgay(17),
		       abs(left-vgax(40)+2 -vgax(620)),
			 abs(bottom+vgay(40)-vgay(17) -(bottom+vgay(40)-2)));
                  color_ps(wiring_postscript-1,lightred);
                  rect_outline_ps(left-vgax(40)+2,bottom+vgay(40)-vgay(17),
		       abs(left-vgax(40)+2 -vgax(620)),
			 abs(bottom+vgay(40)-vgay(17) -(bottom+vgay(40)-2)));
               }
               setviewport((signed int)(left-vgax(40)+2),
                            (signed int)(bottom+vgay(40)-vgay(17)),
			     (signed int)(vgax(620)),
                              (signed int)(bottom+vgay(40)-2),0);
           }

           //tempx=getx;
           //tempy=gety;
	   if (!nhood_mixed) sprintf(textb[3]," cell=%d  wiring=",poss);
	   else sprintf(textb[3]," cell=%d maxk=%d k=%d  wiring=",
					      poss,nhood,nhoodm[poss]);
           sprintf(textb[2],"%s",textb[3]);
	   for (z=nhoodm[poss]-1;z>=0;z--){
	      sprintf(textb[3],"%d ",wiring[poss][z]);
              strcat(textb[2],textb[3]);
	   }

	   sprintf(textb[3],"outwires=%d ",celloutfreq[poss]);
           strcat(textb[2],textb[3]);
           strcat(textb[2],"links:");             
           if (nhood_mixed){
              sprintf(textb[3],"total=%lu av-k=%.2f ",
                       tot_wires, (float)tot_wires/lineL);
              strcat(textb[2],textb[3]);
           }
	   if (lineL<=2500){
	      sprintf(textb[3],"bi=%d ",tot_bi_links);
              strcat(textb[2],textb[3]);
	   }
           sprintf(textb[3],"self=%d=%.1f%% ",tot_self_links,
                                 100*(float)tot_self_links/tot_wires);
           strcat(textb[2],textb[3]);
           sprintf(textb[3],""); /*empty textb[3] because its being printed to xterm ??*/

           psize_ps=15;
           if (strlen(textb[2])*CWidth>vgax(620)){
	         set_medium_font(); //CWidth=CWidth_def*.8;
		 psize_ps=12;
           }
           if (strlen(textb[2])*CWidth>vgax(620)){
	         set_small_font(); //CWidth=CWidth_def*.6;
		 psize_ps=9;
           }
           if (wiring_postscript){
                 color_ps(wiring_postscript-1,white);
                 resetfont_ps("Times-Roman", psize_ps);
	         nodetext_ps(3,bground,textb[2],getx,gety+CHeight_def*.9);
           }

	   /* if (wiring_postscript){
                  color_ps(wiring_postscript-1,white);
	          nodetext_ps(3,bground,textb[2],getx,gety+CHeight*.9);
	   }*/
           moveto(getx,gety+ceil( (double)CHeight_def/CHeight) ); /*to center text*/
           outtext(textb[2]);
           restore_def_font();
           if (wiring_postscript) resetfont_ps("Times-Roman", pointsize);

           sprintf(textb[2],""); /*empty textb[2] because its showing in xterm ??*/

           /*no need as rule appears in the bottom rule window*/
	   /*if (rules_set && tablebytes<=limitbytes){
	      if (rulemix ||
                    (outer_tot==1 && poss<value_range)) thisposs=poss;
	      else thisposs=0;
	      sprintf(textb[3],"k%d-rule=(hex)",nhoodm[poss]);
	      outtext(textb[3]);             
	      if (tot_only==0) 
                print_current_bitstring_hexbytes(16,1,carule[thisposs],nhoodm[thisposs],Maxx,white,0);
	   }*/

           setviewport(0, 0, Maxx, Maxy, 0);

           if (w_type==1){
#             if __UNIX__
	         erase_box(left-vgax(35),top+(cscale-csep)+1,
					  right+vgax(35),bottom-2);
#             elif __WATCOM__
	         erase_box(left-vgax(35),top+(cscale-csep)+1,
					  right+vgax(35),bottom-1);
#             endif
           }
           else{  
              erase_box(left-vgax(39),top-vgay(49),
			right+vgax(38),bottom+vgay(40)-vgay(18));
              if (right+vgax(40)>=trboxw)
                   draw_1d_graphics_prompt(startposs,endposs,poss,step,
                                            showrules, block_set);
           }
	   if (show_all){
              unsigned char c_tempcolor;

              c_tempcolor=getcolor();
              if (w_type==2)
                 draw_ring_of_cells(poss,c_scale,c_tempcolor,c_line,
                                            wox,woy,w_angle,w_cyclerad);             
              show_all_in_out_1d(show_all,left,right,bottom,top,
                  textbx,textby,nhoodlevel,cellx,
                       cscale,cscale1,csep,csep1,
                            direct_wire,showrules,poss,
                                w_type,wox,woy,celly,w_angle,w_cyclerad);    
	      show_all=0;
              if (w_type==1){
#                if __UNIX__
	            erase_box(left-vgax(35),top+(cscale-csep)+1,
					  right+vgax(35),bottom-2);
#                elif __WATCOM__
	            erase_box(left-vgax(35),top+(cscale-csep)+1,
					  right+vgax(35),bottom-1);
#                endif
              }
              else{  
                 erase_box(left-vgax(39),top-vgay(49),
			right+vgax(38),bottom+vgay(40)-vgay(18));
                 if (right+vgax(40)>=trboxw)
                   draw_1d_graphics_prompt(startposs,endposs,poss,step,
                                            showrules, block_set);
              }
	   }

           /*draw wiring for defined range, default all cells*/
           if (show_block==1){
	     unsigned int this_startposs,this_endposs;
             unsigned char t_color;

	     if (!(endposs<lineL && endposs>startposs)){
                this_startposs=0;
                this_endposs=lineL-1;                 
              }
              else{
		this_startposs=startposs;
		this_endposs=endposs;
              }
              
              if (block_drawn==0 || w_type==2){
                 t_color=getcolor();
                 setcolor(red);
		 
	         for (zzu=this_startposs;zzu<=this_endposs;zzu++){
                    if (w_type==1){
		       if (right>=left+cscale*lineL)
			   cellx=left+(cscale1-csep1)/2+cscale1*(float)(L-zzu);
		       else cellx=left+cscale1/3+(right-left-cscale1)*(float)(L-zzu)/L;
		       
                       draw_1d_links(bottom,top,nhoodlevel,
			 cellx,cscale,cscale1,csep,1,showrules,zzu,1);
                    }
                    else{
                       cellx=(cos(-(w_angle*zzu))*w_cyclerad)+wox; 
                       celly=-(sin(-(w_angle*zzu))*w_cyclerad)+woy;
                       draw_1d_links_c(wox,woy,cellx,celly,cscale,csep,
                           1,showrules,zzu,w_angle,w_cyclerad,1); 
                    }
                 }
		 
		 
                 setcolor(t_color);
                 if (w_type==1){ 
                    getimage(left,top+cscale-csep+1,right,bottom-1,blockimage);
                    block_drawn=1;
                 } 
	      }
              else if (redraw==0 && block_drawn==1 && w_type==1){
                 sprintf(textb[9],"%s","blockimage!");
                 putimage(left,top+cscale-csep+1,blockimage,COPY_PUT,textb[9]);		 
              }
           }
           /*draw wiring from given cell*/
           if (w_type==1){
              if (right>=left+cscale*lineL)
			   cellx=left+(cscale1-csep1)/2+
					 cscale1*(float)(L-poss);   
	      else cellx=left+cscale1/3+
			     (right-left-cscale1)*(float)(L-poss)/L;

              draw_1d_links(bottom,top,nhoodlevel,
                     cellx,cscale,cscale1,csep,
                            direct_wire,showrules,poss,0);
              moveto(textbx,textby);
           }
           else if (w_type==2){
              unsigned char c_tempcolor;
              c_tempcolor=getcolor();

              cellx=(cos(-(w_angle*poss))*w_cyclerad)+wox;
              celly=-(sin(-(w_angle*poss))*w_cyclerad)+woy; 
 
              draw_1d_links_c(wox,woy,cellx,celly,cscale,csep,
                           direct_wire,showrules,poss,w_angle,w_cyclerad,0);
              /*draw ring of cells*/
              draw_ring_of_cells(poss,c_scale,c_tempcolor,c_line,
                                            wox,woy,w_angle,w_cyclerad);           
              moveto(textbx,textby);
           }
       
           setfillstyle(SOLID_FILL,black);
	   bar(getx,gety,getx+CWidth*2,gety+CHeight);
           redraw=0;

           if (wiring_postscript==1){ /*disable wiring_postscript*/
              close(fid_PS); 
              wiring_postscript=0;
           }
           wiring_changed=0;

	   /*
           while(event_ready()==0){
#             if __UNIX__             
	         usleep(1);     //makes cpu=0, otherwise was 100%
#             endif
           }*/
 
           test_key=0;
           event_happened=0;
           inside_rect=0;

         while(event_happened==0){

#        if __WATCOM__
           mouse_call(7,0,X1,X2); //confine mouse in array
           mouse_call(8,0,Y1,Y2);
	   if (!kbhit()){
                mouse_call(1,0,0,0); /*display mouse*/ 
                mouse_call(3,0,0,0); /*mouse position*/
                mouse_x=globcx;
	        mouse_y=globdx;
                /*check mousemove and show co-ordinates*/
                if (mxtemp!=mouse_x || mytemp!=mouse_y){
                  int ipos,jpos;
                     if (w_type==1){ /*time-steps*/		        
		        /*show co-ordinates in memory box*/
                        ipos=lineL-1-(int)(lineL* ((float)(mouse_x-X1))/(X2-X1));
                        if (ipos<0) ipos=0;
                        sprintf(textb[0],"i=%d",ipos);
                        memory_box(2,textb[0]);
                        mxtemp=mouse_x;
	                mytemp=mouse_y;                       
		     } 
                     else if (w_type==2){ /*circle*/
		      float temp_angle,thisangle,thisfrac,quadprop,xc,yc,quadL;
		         quadL=(float)lineL/4;
                         /*atan return value is in the range [-pi/2, pi/2]*/
                         xc=mouse_x-wox;
                         yc=mouse_y-woy;
                         thisangle=atan(xc/yc); /*atan:watcom, atanf:linux*/ 
                         thisfrac=thisangle/(PI/2);
                         quadprop=quadL*thisfrac;
                                   /*successive quadrants anti-clockwise*/
		         if      (xc>0 && yc>0) ipos=(abs)(quadL - quadprop);//SE
		         else if (xc<0 && yc>0) ipos=(abs)(quadL - quadprop);//SW   
		         else if (xc<0 && yc<0) ipos=(abs)(3*quadL - quadprop);//NW
		         else if (xc>0 && yc<0) ipos=(abs)(3*quadL - quadprop);//NE
                         sprintf(textb[0],"i=%d",ipos);
                         memory_box(2,textb[0]);
                         mxtemp=mouse_x;
	                 mytemp=mouse_y;      
	           }
                }
                mouse_call(5,0,0,0); /*check if left mouse button pressed*/
                if (globbx){
                   event_happened=1;
                   mouse_call(2,0,0,0); //hide mouse
                   if (w_type==1){ /*time-steps*/		      
                         ii=lineL-1-(int)(lineL* (float)(mouse_x-X1)/(X2-X1));
                         if (ii<0) ii=0;
                         oldposs=poss;
                         poss=ii;
                   }
                   else if (w_type==2){ /*time-steps*/
                     float temp_angle,thisangle,thisfrac,quadprop,xc,yc,quadL;
		      quadL=(float)lineL/4;
                          /*atan return value is in the range [-pi/2, pi/2]*/
                          xc=mouse_x-wox;
                          yc=mouse_y-woy;
                          thisangle=atan(xc/yc); /*atan:watcom, atanf:linux*/ 
                          thisfrac=thisangle/(PI/2);
                          quadprop=quadL*thisfrac;
                                /*successive quadrants anti-clockwise*/
		          if      (xc>0 && yc>0) ii=(abs)(quadL - quadprop);//SE
		          else if (xc<0 && yc>0) ii=(abs)(quadL - quadprop);//SW   
		          else if (xc<0 && yc<0) ii=(abs)(3*quadL - quadprop);//NW
		          else if (xc>0 && yc<0) ii=(abs)(3*quadL - quadprop);//NE
                          oldposs=poss;
                          poss=ii;
                   }  
                   /*active cell co-ords shown in prompt window, and data window*/
                   draw_1d_graphics_prompt(startposs,endposs,poss,step,
                                                showrules, block_set);
                   is[0]=0; /*to continue after show_all in/out*/
                   test_key=0;
                   break;                                             
	        }
           } //if (!kbhit()){
	   else { /*key hit*/
               is[0]=keycheck(1);
               test_key=1;
               event_happened=1;
           }
	   	        
#        elif __UNIX__	    
            if (!XCheckMaskEvent(D,
		       KeyPressMask|ButtonPressMask|PointerMotionMask,&Event) /*|| is[0]==15*/){
	       usleep(1);     //reduces cpu to about 20%, otherwise was 100% 
               continue;
            }                       
	    if (Event.type == MotionNotify){
	       int ipos,jpos;  
		 mouse_x=Event.xmotion.x;
		 mouse_y=Event.xmotion.y;
                 if (w_type==1){ /*time-steps*/
		     if (mouse_x>=X1 && mouse_y>=Y1
			       && mouse_x<=X2 && mouse_y<=Y2){
		        XDefineCursor(D,W,leftCursor); //cursor inside array
		        /*show co-ordinates in memory box*/
                        ipos=lineL-1-(int)(lineL* ((float)(mouse_x-X1))/(X2-X1));
                        if (ipos<0) ipos=0;
                        sprintf(textb[0],"i=%d",ipos);
                        memory_box(2,textb[0]);
	           }
                   else{  //cursor outside array
                       XDefineCursor(D,W,rightCursor);
                       erase_memory_box(2);
                   }
		}
                if (w_type==2){ /*circle*/
		  float temp_angle,thisangle,thisfrac,quadprop,xc,yc,quadL;
		    quadL=(float)lineL/4;
                    if (mouse_x>=X1 && mouse_y>=Y1
			       && mouse_x<=X2 && mouse_y<=Y2){
                       XDefineCursor(D,W,leftCursor); //cursor inside array
                       /*atan return value is in the range [-pi/2, pi/2]*/
                       xc=mouse_x-wox;
                       yc=mouse_y-woy;
                       thisangle=atanf(xc/yc); 
                       thisfrac=thisangle/(PI/2);
                       quadprop=quadL*thisfrac;
                                /*successive quadrants anti-clockwise*/
		       if      (xc>0 && yc>0) ipos=(abs)(quadL - quadprop);//SE
		       else if (xc<0 && yc>0) ipos=(abs)(quadL - quadprop);//SW   
		       else if (xc<0 && yc<0) ipos=(abs)(3*quadL - quadprop);//NW
		       else if (xc>0 && yc<0) ipos=(abs)(3*quadL - quadprop);//NE
                       sprintf(textb[0],"i=%d",ipos);
		       //sprintf(textb[0],"i=%d, %.2f, %.2f, %.2f",ipos,thisangle,thisfrac,quadprop);
                       //sprintf(textb[0],"x=%d y=%d",mouse_x,mouse_y);
                       memory_box(2,textb[0]);
	           }
                   else{  //cursor outside array
                       XDefineCursor(D,W,rightCursor);
                       erase_memory_box(2);
                   }
                }
            }

	    if (Event.type==ButtonPress){ /*left or right button*/
                 event_happened=1;
		 mouse_x=Event.xbutton.x;
		 mouse_y=Event.xbutton.y;
                 if (w_type==1){ /*time-steps*/
		    if (mouse_x>=X1 && mouse_y>=Y1
			       && mouse_x<=X2 && mouse_y<=Y2){
                      ii=lineL-1-(int)(lineL* (float)(mouse_x-X1)/(X2-X1));
                      if (ii<0) ii=0;
                      oldposs=poss;
                      poss=ii;
                           //fprintf(stderr,"\nposs=%d oldposs=%d",poss,oldposs);
                    }
                 }
                 if (w_type==2){ /*time-steps*/
                   float temp_angle,thisangle,thisfrac,quadprop,xc,yc,quadL;
		    quadL=(float)lineL/4;
		    if (mouse_x>=X1 && mouse_y>=Y1
			       && mouse_x<=X2 && mouse_y<=Y2){
                       /*atan return value is in the range [-pi/2, pi/2]*/
                       xc=mouse_x-wox;
                       yc=mouse_y-woy;
                       thisangle=atanf(xc/yc); 
                       thisfrac=thisangle/(PI/2);
                       quadprop=quadL*thisfrac;
                                /*successive quadrants anti-clockwise*/
		       if      (xc>0 && yc>0) ii=(abs)(quadL - quadprop);//SE
		       else if (xc<0 && yc>0) ii=(abs)(quadL - quadprop);//SW   
		       else if (xc<0 && yc<0) ii=(abs)(3*quadL - quadprop);//NW
		       else if (xc>0 && yc<0) ii=(abs)(3*quadL - quadprop);//NE
                       oldposs=poss;
                       poss=ii;
                    }
                 }
                 /*active cell co-ords shown in prompt window, and data window*/
                 draw_1d_graphics_prompt(startposs,endposs,poss,step,
                                                showrules, block_set);
                 is[0]=0; /*to continue after show_all in/out*/
                 test_key=0;
                 break;                  
	     }
             else if (Event.type == KeyPress){
                KeySym key;
                /*mapping from keycodes to keysyms -- use xmodmap -pk to see the current mapping*/ 
		//fprintf(stderr,"\nEvent.type == KeyPress");
                XLookupString(&Event.xkey, NULL , 16, &key, NULL);
                   if (key!=0xffe1 && key!= 0xffe2){ /*not (left or right) shift keys*/
		      button='k';      /*to avoid unnecessary overwrite --for capitals, i.e G*/
		      is[0]=keycheck(0);
                      test_key=1;
                      event_happened=1;
                   }              
             }
#        endif
         }//while(event_happened==0){
         erase_memory_box(2);
         event_happened=0;

           if (test_key==1){ /*a key was pressed, not mouse button above*/
	    switch(is[0]){
              case'q':
                  break;
	      case'g':
		 jump_graph_table(0,NULL,'n'); //show network-graph
		 draw_1d_graphics_prompt(startposs,endposs,poss,step,
                                                showrules, block_set);
	         continue;
              case'I': 
		 draw_k_hist(1); /*draw k frequency histogram (inputs)*/
	         is[0]=0;
		 break;
              case'O': 
		 draw_k_hist(2); /*draw output frequency histogram*/
                 is[0]=0;
		 break;
              case'B': 
		 draw_k_hist(3); /*draw in-out frequency histogram*/
                 is[0]=0;
		 break;
              case'f':{          /*load save network files*/
                char was_loaded; /*and show as block in graphic*/
                 erase_prompt_box(6);
                 was_loaded=save_load_print_net();
                 is[0]=0;
                 if (was_loaded){
                    unsigned int ii,jj,hh;
                    if (file_dim==1){
                       startposs=file_starti;
                       endposs=startposs+file_i-1;
                    }
                    else if (file_dim==2){
                       ii=file_starti%i2d;
	               jj=file_starti/i2d;
                       startposs=i2d*jj + ii;
                       endposs=startposs+file_i*file_j -1;
                    }
                    else if (file_dim==3){
                       ii=file_starti%i3d;
	               jj=file_starti%(i3d*j3d)/i3d;
                       hh=file_starti/(i3d*j3d);
                       startposs=(i3d*j3d*hh) + (i3d*jj) + ii;
                       endposs=startposs+file_i*file_j*file_h -1;
                    }
                    nhood_lb_ub();
                    if (nhood_lb!=nhood_ub){ 
                       nhood_mixed=1;
                       /*rulemix=1;*/
                    }
                    block_set=1;
                    show_block=1;
                    block_drawn=0; /*to redraw wiring all cells*/
                    was_changed=1;
                    wiring_changed=1;
		 }
      		 break;
               }              
              case'i': /*show all input genes to given gene*/
		 show_all=1;
		 continue;
              case'o': /*show all output genes to given gene*/
		 show_all=2;
		 continue;
              case'S':
                 if (showrules==1){
                    erase_prompt_box(6);
                    if (rulemix ||
                          (outer_tot==1 && poss<value_range)) thisposs=poss;
		    else thisposs=0;
                    if (tot_only==0) load_save_wrs('s',carule[thisposs],0);
                    else{ 
                       if (totalistic==1) load_save_wrs('s',cacode[thisposs],0);
                       if (totalistic==2) load_save_wrs('s',v_code[thisposs],0);
                    }
                    is[0]=0;
                 }
                 break;
              case'v':
                 if (showrules==1 /*revise rule for single cell or block*/
                      && basin_not_complete==0){ /*not while basin interupted*/
                    erase_prompt_box(6);
                    if (rulemix ||
                          (outer_tot==1 && poss<value_range)) thisposs=poss;
		    else thisposs=0; 
                    revise_rule_graphic(1,block_set,show_block,
                         0,0,0,0,0,0,thisposs,startposs,endposs);
                    is[0]=0;
                 }
		 break;
	      case't': /*transform_rule*/
		if (basin_not_complete==1 /*not while basin interupted*/
                       || showrules==0 || tot_only==1) break;
		 erase_prompt_box(6);
		 if (rulemix) thisposs=poss;
		 else thisposs=0;
		 tempx2=getx;
		 tempy2=gety;
		 transform_rule(thisposs);
		 moveto(tempx2,tempy2);
		 is[0]=0;
		 break;
              case'D':
                 if (showrules==0) break;
                 erase_prompt_box(6);
                 if (tot_only==0 && totalistic==0) 
                               draw_Derrida_plot(carule);
                 else{
		    if (totalistic==1) draw_Derrida_plot(cacode);
                    else if (totalistic==2) draw_Derrida_plot(v_code);
	         }
                 is[0]=0;
		 break; 
              case'z': /*calculate av. and weighted av. ldz,Z*/
		 if (tot_only==1 || showrules==0 || rulemix==0) break;
                 erase_prompt_box(6);
                 if (rulemix && showrules==1) av_z_para();
		 break;	      
	     case'l': case'L':{ /*l=highlight_only L=Learn*/
                char highlight_only=0;
		 if (showrules==0 || tot_only==1 /*|| rulemix==0*/
                         || basin_not_complete==1) break;/*not while basin interupted*/
	         if (is[0]=='l') highlight_only=1;
	         sculpt_basin=0;
                 sprintf(textb[9],"%s","boximage_prompt[3]");
                 putimage(trboxw,2,boximage_prompt[3],COPY_PUT,textb[9]);
                 draw_box(19,left-vgax(40),top-vgay(50),
			    right+vgax(40),bottom+vgay(40),0,-1);
                 sprintf(textb[9],"%s","boximage[6]");
                 putimage(left-vgax(40),top-vgay(50),boximage[6],COPY_PUT,textb[9]);
		 learn_sometime=sculpt_basin_field(highlight_only);
                 sculpt_basin=1;
		 was_changed=1;
                 if (nonlocal==1) wiring_changed=1;
                 sprintf(textb[9],"%s","boximage[19]");
		 putimage(left-vgax(40),top-vgay(50),boximage[19],COPY_PUT,textb[9]);
                 freeimage(boximage[19]);
		 is[0]=0;
		 break;
              }
	      case'u':{ /*untangle all wiring, transform rules accordingly*/
		 char *catemp,*ca_tickoff,*nhoodbits,*swap_nhoodbits;
                 signed int t_bytes;
                 unsigned int startu,endu,tablemax;

                 if (basin_not_complete==1) goto end_unt;/*not while basin interupted*/
		 /*if (!nonlocal) break;*/
                 nonlocal=1;
	         erase_prompt_box(6);
                 draw_prompt_box(1);
                 if (block_set && show_block) sprintf(textb[0],
		   "untangle 1d wiring:  block %d-%d -b, all-a, single cell-(def):",
                                                          startposs,endposs);
                 else sprintf(textb[0],
                    "untangle 1d wiring: all-a, single cell-(def):");
		 outtext(textb[0]);
		 input_string(1,0);
                 if (is[0]=='q') goto end_unt;
                 else if ((is[0]=='b' && block_set==1 && show_block) 
                                               || is[0]=='a'); /*do nothing*/
                 else is[0]='c';
                 /* if TFO-mode (tot_only==1) the rule need not be changed */
                 if (rulemix && showrules && tot_only==0){	
		   signed int nhood_bytes; 
		    /*bytes in max ruletable*/
                    tablemax= (signed int)pow(value_range,(double)nhood)-1;
                    t_bytes=(signed int)ceil(value_bits * (double)(tablemax+1)/8);
                    if ((catemp=(char *)calloc(t_bytes,sizeof(char)))
				  ==NULL) outof_memory("catemp");
                    if ((ca_tickoff=(char *)calloc(t_bytes,sizeof(char)))
				  ==NULL) outof_memory("ca_tickoff"); 
                    nhood_bytes=ceil((double)(nhood*value_bits)/8);    
                    if ((nhoodbits=(char *)calloc(nhood_bytes,sizeof(char)))
				  ==NULL) outof_memory("nhoodbits");
                    if ((swap_nhoodbits=(char *)calloc(nhood_bytes,sizeof(char)))
				  ==NULL) outof_memory("swap_nhoodbits");
                 }
                 if (is[0]=='a'){
                    startu=0;
                    endu=lineL-1;
                 }
                 else if (is[0]=='b'){
                    startu=startposs;
                    endu=endposs;
                 }
                 else {
                    startu=poss;
                    endu=poss;
                 }
                 for (zu=startu; zu<=endu; zu++) untangle_wiring(zu,showrules,
			             catemp,ca_tickoff,nhoodbits,swap_nhoodbits);
	         
	         if (rulemix && showrules && tot_only==0){	
                    free(catemp);
                    free(ca_tickoff);
                    free(nhoodbits);
                    free(swap_nhoodbits);
                 } 
                 was_changed=1;
                 wiring_changed=1;
                 block_drawn=0;
	      end_unt:
                 is[0]=0;    
                 break; 
	      }
	      case'a': /*toggle showing 1 cell or block*/ 
                        show_block=abs(show_block-1);
                        break;     
              case'b':{
                       unsigned int low_v,high_v,temp_v,max_v;
                       char range_type=0;

                       erase_prompt_box(6);
                       block_set=range_type=0;
                       xbox=draw_prompt_box(4);		       
                       sprintf(textb[0],"1d block-1, all-a, no block and single cell-def:");
                       outtext(textb[0]);
                       input_string(1,0);
                       if (is[0]=='q' || is[0]==13){
                          show_block=0;
			  if (is[0]==13){/*cancel block -- 'g' toggles all wiring*/
			     endposs=lineL-1;
			     startposs=0;
			     block_set=0;
			  }
                          goto quit_b;
	               }
                       else if (is[0]=='a'){
                          block_set=1;
                          show_block=1;
                          range_type=1;
                          startposs=0;
                          endposs=lineL-1;
                          goto quit_b;
                       }
                       else if (is[0]!=13 && atoi(is)==1) range_type=atoi(is);
                                                
                       if (range_type==1) max_v=lineL-1;                                 
	               low_v=poss;
                       high_v=oldposs;    
                       sprintf(textb[0],
	                   "%dd block (0-%d), first(def %d):",
                                      range_type,max_v,low_v);
                       
                       moveto(xbox,gety+CHeight);
                       outtext(textb[0]);
                       input_string(5,0);
                       if (is[0]=='q') goto quit_b;
                       else if (is[0]!=13 && atoi(is)>=0 && atoi(is)<=max_v)
                                   low_v=atoi(is);
                       sprintf(textb[0],"  second(def %d):",high_v);
                        outtext(textb[0]);
                       input_string(4,0);
                       if (is[0]=='q') goto quit_b;
                       else if (is[0]!=13 && atoi(is)>=0 && atoi(is)<=max_v) 
                                   high_v=atoi(is);
                       if (low_v==high_v ) goto quit_b; 
                       if (high_v<low_v){ /*swap i if necessary*/
			        temp_v=high_v;
                                high_v=low_v;
                                low_v=temp_v;
                       }
                       
                       block_set=1;
                       show_block=1;
                       if (range_type==1){
                          startposs=low_v;
                          endposs=high_v;
                       }
		      quit_b:
                       erase_prompt_box(4);
                       block_drawn=0; /*to redraw wiring all cells*/
                       is[0]=0;  
		       break;
               }
	       case'k': /*revise k for single cell or 1d block*/
                       if (basin_not_complete==1 /*not while basin interupted*/  
                            || tot_only==1) break; 
		       if (showrules==1 && rulemix==0) break;
                       reset_k(showrules,block_set,show_block,
                                            poss,startposs,endposs);
                       block_drawn=0;
                       was_changed=1;
                       if (nonlocal==1) wiring_changed=1;
                       is[0]=0;
		       break;
       		case'K':{ /*kill: cut all input and/or output links to cell, make rule neutral*/
                       if (basin_not_complete==1 /*not while basin interupted*/
			   /*|| tot_only==1*/) break;
		       if (showrules==1 && rulemix==0) break;
                       if (nonlocal==0 || showrules==0) break;
                       if (show_block==1){
			     for (zzu=startposs;zzu<=endposs;zzu++) 
                                      cut_in_out_links(zzu);      
                       }
                       else cut_in_out_links(poss);
                       block_drawn=0;
                       was_changed=1;
                       wiring_changed=1;
                       is[0]=0;
		       break; 
		}
                case'd':{ /*kill as above, and delete cell, reduce size of net*/
                       if (basin_not_complete==1 /*not while basin interupted*/
                            || tot_only==1 || lineL<3 || poss==0) break;
                       if (showrules==1 && rulemix==0) break;
                       if (secondpart==1 || nonlocal==0 || 
                                 oned==0 || lineL==1 || showrules==0) break;
                       delete_cell(poss);
                       size_was_changed=1;
                       wiring_changed=1;
                       block_drawn=0;
                       was_changed=1;
                       wiring_changed=1;
                       is[0]=0; /*exit the 1d graphic*/
                       if (poss>0) poss-=1;
		       break; 
                }
		case'h': /*rewire single cell by hand*/
                       if (basin_not_complete==1) break;/*not while basin interupted*/
                       rewire_single_cell(poss);
                       was_changed=1;
                       wiring_changed=1;
                       is[0]=0;
		       break;
		case'r': /*random wiring for single cell or 1d block*/
                       if (basin_not_complete==1) break;/*not while basin interupted*/
                       if (block_set==0 || show_block==0) 
                                   randomly_wire_cell(poss,lineL-1);
                       else {
                          for (zzu=startposs;zzu<=endposs;zzu++)
		                  randomly_wire_cell(zzu,lineL-1);
                       }
                       cell_out_freq();
                       was_changed=1;
                       wiring_changed=1;
                       block_drawn=0; 
		       break;
                case'w':  /*random wiring outside block*/
                       if (basin_not_complete==1 ||
                           (startposs==0 && endposs==lineL-1))
                                 break;/*not while basin interupted,
                                         or block same as netsize*/
		       if (show_block==1){
			  for (zzu=0;zzu<=lineL-1;zzu++){
                            if (zzu>=startposs && zzu<=endposs) continue;
                            else randomly_wire_cell(zzu,lineL-1);
                          }
                          cell_out_freq();
                          was_changed=1;
                          wiring_changed=1;
                          block_drawn=0;
                       } 
		       break;
                case'R':{ /*random wiring for single cell or 1d block,
                              biased by k distribution*/
                       unsigned long tot_wires=0;
                       unsigned int zub;
                       if (basin_not_complete==1) break;/*not while basin interupted*/
                       for (zub=0;zub<=lineL-1;zub++) tot_wires+=nhoodm[zub];
                       
                       if (block_set==0 || show_block==0) 
                             randomly_wire_cell_Kbias(tot_wires,poss,lineL-1);
                       else {
                          for (zzu=startposs;zzu<=endposs;zzu++)
		             randomly_wire_cell_Kbias(tot_wires,zzu,lineL-1);
                       }
                       cell_out_freq();
                       was_changed=1;
                       wiring_changed=1;
                       block_drawn=0; 
		       break;       
                }
		case's': /*bias wiring for single cell
                               or 1d block*/
                       if (basin_not_complete==1) break;/*not while basin interupted*/
                       zonesize=set_max_zonesize(); 
		       /*fixmidwire=0;*/
                       bias_random_wiring();
                       if (is[0]!='q') cell_out_freq();
                       is[0]=0;
                       was_changed=1;
                       wiring_changed=1; 
		       break;
		 case'1':
                       if (basin_not_complete==1) break;/*not while basin interupted*/
                       if (block_set==0 || show_block==0) 
                                  oneD_local_wire_cell(poss,lineL-1);
                       else{
                          for (zzu=startposs;zzu<=endposs;zzu++)
		                  oneD_local_wire_cell(zzu,lineL-1);
                       }	      
                       cell_out_freq();
                       block_drawn=0;
                       was_changed=1;
                       wiring_changed=1;
		       break;
                 case'2':
                       if (basin_not_complete==1) break;/*not while basin interupted*/
                       if (twod==0) break;
                       if (block_set==0 || show_block==0) 
                                  wire_2d_local(poss,wiring[poss]);
                       else{
                          for (zzu=startposs;zzu<=endposs;zzu++)
		                  wire_2d_local(poss,wiring[poss]);
                       }	      
                       cell_out_freq();
                       block_drawn=0;
                       was_changed=1;
                       wiring_changed=1;
		       break;
                 case'3':
                       if (basin_not_complete==1) break;/*not while basin interupted*/
                       if (threed==0) break;
                       if (block_set==0 || show_block==0) 
                                  wire_3d_local(poss,wiring[poss]);
                       else{
                          for (zzu=startposs;zzu<=endposs;zzu++)
		                  wire_3d_local(poss,wiring[poss]);
                       }	      
                       cell_out_freq();
                       block_drawn=0;
                       was_changed=1;
                       wiring_changed=1;
		       break;	               
                 case LeftArrow:    
			 poss+=1;           
			 if (poss>L) poss=0;         			   
			 break;
	         case 8:    /*backspace*/
			 poss+=1;           
			 if (poss>L) poss=0;         			    
			 break;
		 case RightArrow:
			 poss-=1;
			 if (poss==Maxu) poss=L;
			 break;
		 case UpArrow:
			 poss+=step;
			 if (poss>L) poss=0;			    
			 break;
                 case DownArrow:
			 posswas=poss;
			 posswas-=step;
			 if (posswas>poss) poss=L;
			 else poss-=step;		  
			 break;	 
		 case'j':
                         poss=jump1d();		        
                         break;
                 case 'p':
			 direct_wire=abs(direct_wire-1);
                         break;
                 case 'T': /*to redraw the whole thing exactly as is*/
		         block_drawn=0;		   
		         redraw=1;
                         break;
                 case 'P': /*to redraw the whole thing exactly as is 
                             and save vector PostScript*/
		         block_drawn=0;		   
		         redraw=1;
                         erase_prompt_box(6);
                         draw_prompt_box(1);
                         outtext("save wiring graphic to PostScript: greyscale-P color-p:"); 
                         input_string(1,0);
                         if (is[0]=='p'|| is[0]=='P'){
                            
                            if (is[0]=='p') wiring_postscript=1;
                            else if (is[0]=='P') wiring_postscript=2;
                            file_ret_w=select_filename("SAVE","PostScript file","*.ps","my_wgPS");
                            if (file_ret_w=='q'){
			       wiring_postscript=0;
                               break;
                            }
	                    memmove(filename_wiring_PS,filename,13);
                            /*delete previous*/
                            fid_PS=myopen(filename_wiring_PS,1,0);
                            vret=write(fid_PS, "",0);
                            close(fid_PS);
                            /*start new*/
                            fid_PS=myopen(filename_wiring_PS,1,1);
                            if (fid_PS==-1){ 
                                  file_error(filename_wiring_PS);
                                  close(fid_PS); 
                                  wiring_postscript=0;
                                  break;  
                             }
                             psize_ps=pointsize;
                             prepare_basinPS(2,2); /*write/define postScipt for wiring*/
			 }   
                         break;                        
	    }/*end switch(is[0]){*/
           }/*if (test_key==1){*/

           /*show REVISED top right prompts (or in case covered)*/
           draw_1d_graphics_prompt(startposs,endposs,poss,step,
                                                showrules, block_set);
	   if (wiring_changed==1){  /*redraw output frequency cells*/
	      nonlocal=1;
	      regular3d=regular2d=regular2d_tgrid=
                       compress_1d_local=dontcompress=0;
	      cell_out_freq();
              if (w_type==1){
	         moveto(left,top+vgay(100));
	         setfillstyle(SOLID_FILL,black);  /*erase frequency cells*/
	         bar(getx,gety,rightcell,gety+vgax(25)-1);
	         setfillstyle(SOLID_FILL,lightgray);
	         for (zu=lineL-1;zu!=Maxu;zu--){                    
		    //cellheight=celloutfreq[zu];
		    cellheight=vgay(celloutfreq[zu]);
		    //if (cellheight>vgay(25)) cellheight=25;
		    if (cellheight>vgay(25)) cellheight=vgay(25);
		    if (lineL>(right-left)/2){
		      line(getx,gety,getx,gety+cellheight);
                      /*for hires Dell 3200x1800 -- unpredictable screen lines without this - ??
		                though line_ps( was ok*/
		      while(event_ready()==0) break;
		    }
		    else bar3d(getx,gety,getx+cscale1-csep1,
						  gety+cellheight,0,1);
		    if (drawcells==1) moverel(cscale,0);
		    else moveto(left+cscale1*(lineL-zu),gety);
                 }
	      }
	   }  
	   wiring_changed=was_changed=0;
	   if (redraw==1 || 
                size_was_changed==1 || is[0]=='q' || is[0]==13) break;
	}

        sprintf(textb[9],"%s","boximage[6]");
	putimage(left-vgax(40),top-vgay(50),boximage[6],COPY_PUT,textb[9]);
	freeimage(boximage[6]);
        if (w_type==2){
            sprintf(textb[9],"%s","boximage[3]"); 
            putimage(left-vgax(40)+2,bottom+vgay(40)-vgay(17),
                                             boximage[3],COPY_PUT,textb[9]);
            freeimage(boximage[3]);
        }        
        uncover_free_prompt_box(3);
        if (w_type==1){
#          if __WATCOM__
	      freeimage(blockimage);
#          elif __UNIX__
              free(blockimage);
#          endif
        }    
        if (redraw==1 || size_was_changed==1) goto top;     
        was_changed=1; /*if network graphic was visited, assume
                         net was changed, dont mutate next time*/
        inside_wiring_graphic=0;
        fid_PS=fid_temp_PS;
        basin_postScript=temp_basin_postScript;
}

/************ draw ring of cells, Oct 1999  **************/
void draw_ring_of_cells(unsigned int poss,
                       float c_scale,char c_tempcolor,char c_line,
                           float wox, float woy,
                              float w_angle, float w_cyclerad){
  unsigned int zw,tempx,tempy;
  unsigned char fillcolor;
     
              for (zw=lineL-1;zw!=Maxu;zw--){	     
	         moveto( (cos(-(w_angle*zw))*w_cyclerad)+wox,
                    -(sin(-(w_angle*zw))*w_cyclerad)+woy);
                 
                 tempx=getx;
                 tempy=gety;
                 if (wiring_postscript) moveto_ps(tempx,tempy);

	         if (c_line==0){
		     if (zw==poss) fillcolor=red;
                     else fillcolor=lightgray;
                     setfillstyle(SOLID_FILL,fillcolor); 
                     pieslice(1,getx,gety,0,360,(signed int)c_scale);
                     if (wiring_postscript){
                        color_ps(wiring_postscript-1,fillcolor);
                        circle_fill_ps(tempx,tempy,(double)c_scale);/*filled circle*/
                        color_ps(wiring_postscript-1,white);
                        circle_ps(tempx,tempy,(double)c_scale);/*outline*/
                     }
                     if (c_scale>=CHeight*.7){
                        setcolor(black);                       
                        moveto(getx-CWidth/2,gety-CHeight/2);
                        tempx=getx;
                        tempy=gety;
                        sprintf(textb[1],"%d",zw);       
                         if (wiring_postscript){
                           color_ps(wiring_postscript-1,black);
                           nodetext_ps(3,bground,textb[1],tempx,tempy+CHeight*.75);     
                        }
                        outtext(textb[1]);                       
                     }
                     moveto( (cos(-(w_angle*zw))*(w_cyclerad+c_scale+vgax(3)))+wox,
                           -(sin(-(w_angle*zw))*(w_cyclerad+c_scale+vgax(3)))+woy);
                     tempx=getx;
                     tempy=gety;
                 }
                 else{ 
                     linerel(cos(-(w_angle*zw))*vgax(3),
                           -sin(-(w_angle*zw))*vgax(3));
                     if (wiring_postscript){
                         color_ps(wiring_postscript-1,white);
                         line_ps(tempx,tempy,
                               tempx+(signed int)(cos(-(w_angle*zw))*vgax(3)),
                                           tempy+(signed int)(-sin(-(w_angle*zw))*vgax(3)));
                     }
                     moverel(cos(-(w_angle*zw))*vgax(3),
                           -sin(-(w_angle*zw))*vgax(3));
                     tempx=getx;
                     tempy=gety;
                 }
		 /*outwires in circle layout adjusted (enlarged with vgax) for highres Dell*/
                 setcolor(lightred);              
                 linerel(cos(-(w_angle*zw))*vgax(celloutfreq[zw]),
			 -sin(-(w_angle*zw))*vgax(celloutfreq[zw]));
                 if (wiring_postscript){
                    color_ps(wiring_postscript-1,lightred);
                    line_ps(tempx,tempy,
			 tempx+(signed int)(cos(-(w_angle*zw))*vgax(celloutfreq[zw])),
			 tempy+(signed int)(-sin(-(w_angle*zw))*vgax(celloutfreq[zw])));
                 }
                 setcolor(c_tempcolor);

              }
}
/************ graphics prompt for 1d mode function  Aug 1999  **************/
void draw_1d_graphics_prompt(unsigned int startposs,
                                unsigned int endposs,
			        unsigned int poss,
                                unsigned int step,
                                char showrules, char block_set){
  signed int xbox;
  char thisdim;
  unsigned char tempcolor;

        tempcolor=getcolor();
        setcolor(white);

        if (oned){ 
           thisdim=1;
           sprintf(textb[1],"n=%d",lineL);
        }
        else if (twod){
           thisdim=2;
           sprintf(textb[1],"%dx%d",i2d,j2d);
        }
        else if (threed){
            thisdim=3;
            sprintf(textb[1],"%dx%dx%d",i3d,j3d,h3d);
        }

        xbox=draw_prompt_box(6);
        if (showrules) sprintf(textb[0],
	     "%dd (%s) wiring/rules: move-arrows jump-j/mouse-click",thisdim,textb[1]);
        else sprintf(textb[0],
	     "%dd (%s) wiring only: move-arrows jump-j/mouse-click",thisdim,textb[1]);
        outtext(textb[0]);
	moveto(xbox,gety+CHeight);
        sprintf(textb[0], //redraw-T removed, cant see why needed
              "one cell: right/left arrows, %d cells: up/down arrows, PScript-P",step);
        outtext(textb[0]);
        moveto(xbox,gety+CHeight);
        if (block_set) sprintf(textb[0],"block-b tog:block-a pseudo-p, ");
	else sprintf(textb[0],"block-b tog:all-a pseudo-p ");
	outtext(textb[0]);
        outtext("in/out-i/o");
       
        if (showrules){
           if (basin_not_complete==1){ /*not while basin interupted*/
              setcolor(lightred);  
              if (rulemix && showrules==1 && tot_only==0)  outtext(" avZ-z");
              setcolor(white);
           }
           else{
              setcolor(lightred);
              if (direction=='f' && limitcheck==0) sprintf(textb[1]," learn-L");
              else sprintf(textb[1]," hilght/lrn-l/L");
           
              if (rulemix && showrules==1 && tot_only==0){ 
                     sprintf(textb[0]," avZ-z%s",textb[1]);
		     outtext(textb[0]);
	      }	     
	      else if (showrules==1 && tot_only==0){ 
                     sprintf(textb[0]," %s",textb[1]);
		     outtext(textb[0]);
              }
              setcolor(white);
           }
	}
           
	moveto(xbox,gety+CHeight);      
        if (basin_not_complete==1) sprintf(textb[0],"");
        else{
           if (block_set){  
              sprintf(textb[0],"rewire 1d block %d-%d:",startposs,endposs);
           }
           else sprintf(textb[0],"rewire 1d cell %d: ",poss);
        }
        outtext(textb[0]);
   
        if (basin_not_complete==1);/*not while basin interupted*/
        else{
           if (threed) outtext(" untange-u hand-h rnd-r/w/R special-s local:1d-1 3d-3");
           else if (twod) outtext(" untange-u hand-h rnd-r/w/R special-s local:1d-1 2d-2");
           else outtext(" untange-u hand-h rnd-r/w/R special-s local:1d-1");
        }

        moveto(xbox,gety+CHeight);
        if (showrules==1 && rulemix==0); /*do nothing*/
        /*else if (tot_only==1);*/ /*do nothing*/       
        else if (basin_not_complete==0){ /*not while basin interupted*/
	   outtext("graph-g ");
           setcolor(green);
           if (tot_only==0){
              sprintf(textb[0],"change k=%d(max %d)-k ",nhoodm[poss],nhood);
              outtext(textb[0]);
           }
           if (nonlocal==1 && showrules==1) outtext("kill-K ");
           if (tot_only==0){ 
              if (oned && secondpart==0 && nonlocal==1
                    && lineL>1 && showrules==1) outtext("del-d ");
           }
           setcolor(white); 
	}
        
	if (showrules){
	   outtext("graph-g ");
           setcolor(lightred);
	   if (basin_not_complete==1) outtext("rule: Save-S, Derrida-D");
           else{
              if (tot_only==0) outtext("rule: Save/rev/trans-S/v/t Derrida-D");
	      else outtext("rule: Save/rev-S/v Derrida-D");
           }
           setcolor(white);
        }
        moveto(xbox,gety+CHeight);
        outtext("file/data-f ");
        outtext("hist:In(k)/Out/Both-I/O/B, reset-q cont-ret");
        setcolor(tempcolor);
}

/************** jump to index in 1d wiring graphic ******************/
signed int jump1d(void){
     signed int poss;
                         moveto(getx-CWidth,gety);
			 setfillstyle(SOLID_FILL,black);
			 bar(getx,gety+2,
			   getx+CWidth,gety+CHeight+2);
			 get_prompt_box(7,4);
			 sprintf(textb[0],"jump index (%d-0):",lineL-1);
			 erase_prompt_box(4);
			 draw_prompt_box(1); 
			 outtext(textb[0]);
			 sprintf(textb[0],"%d",lineL-1);
			 input_string(strlen(textb[0]),1);
			 if (is[0]!=13 && atoi(is)>=0 && atoi(is)<=lineL-1)
			                               poss=atoi(is); 
			 is[0]=0;                         
                         uncover_free_prompt_box(7);
                         return(poss);
}

/************** show all input or output links to cell ******************/
void show_all_in_out_1d(char show_all,float left,float right,
    float bottom,float top,signed int textbx,signed int textby,
         float nhoodlevel,float cellx,float cscale,
           float cscale1,float csep,float csep1,
		 char direct_wire,char showrules,unsigned int poss,
                    char w_type,float wox, float woy,
                      float celly,float w_angle,float w_cyclerad){

  char *this_sweep,*linknet,*genedone,linkfound,
                  temp_direct_wire,t_scale,t_sep,show_steps=0;
  unsigned char linkcolor;
  float t_right,t_cellx,t_celly,wiredtox,wiredtoy;
  signed int z,t_step=1,tempx,tempy,t_i2d,t_j2d;
  unsigned int startposs,zu,zu1,tot_so_far=0,tot_before=0;

     /*set 2d rep of inputs*/
     t_i2d=i2d; /*conserve original values of i2d,j2d)*/
     t_j2d=j2d;

     set_i2dxj2d();
     /*fprintf(stderr,"\n%d x %d",i2d, j2d);*/
     
     t_scale=scale;
     t_sep=sep;
     if (j2d<=12) scale=3;
     else if (j2d<=18) scale=2;
     else if (j2d<=36) scale=1;
     sep=0;		         
     t_right=left+lineL*cscale1;
     temp_direct_wire=direct_wire;
     direct_wire=1;
     linkcolor=lightred; 
                 
     if ((linknet=(char*)calloc(bytesL,sizeof(char)))
				    ==NULL) outof_memory("linknet");
     if ((genedone=(char*)calloc(bytesL,sizeof(char)))
				==NULL) outof_memory("genedone");
     if ((this_sweep=(char*)calloc(bytesL,sizeof(char)))
				==NULL) outof_memory("this_sweep");
             
      /*mark all input genes to startpos*/
      startposs=poss;
	     
      if (show_all==1){ /*show inputs*/
         if (w_type==1){
            draw_1d_links(bottom,top,nhoodlevel,
                         cellx,cscale,cscale1,csep,
                              direct_wire,showrules,startposs,0);
            moveto(cellx-CWidth/2,top-CHeight);
         }
         else draw_1d_links_c(wox,woy,cellx,celly,cscale,csep,
                           direct_wire,showrules,startposs,w_angle,w_cyclerad,0);

         for (z=nhoodm[startposs]-1;z>=0;z--)
                 set_bit1(linknet,wiring[startposs][z]);
         tot_so_far=nhoodm[startposs];
      }
      else if (show_all==2){ /*show outputs*/
         moveto(cellx-CWidth/2,top-CHeight); 
         for (zu=L;zu!=Maxu;zu--){           
	    for (z=nhoodm[zu]-1;z>=0;z--){   
	       if (wiring[zu][z]==startposs){
                   if (w_type==1){               
                      wiredtox=left+(cscale1-csep1)/3+
		        (t_right-left-cscale1)*(double)(L-zu)/L;
                      line(cellx,top+(cscale-csep),wiredtox,bottom);
                   }
                   else{
                      wiredtox=(cos(-(w_angle*zu))*w_cyclerad)+wox;
                      wiredtoy=-(sin(-(w_angle*zu))*w_cyclerad)+woy;
                      line(cellx,celly,wiredtox,wiredtoy);
                   }
                   set_bit1(linknet,zu); 
               }
	    }
         }
         for (zu=L;zu!=Maxu;zu--){                   
            if (get_bit(linknet,zu)==1) tot_so_far+=1;
         }
      }
      /*draw 2d rep*/
      if (j2d<=36){
         tempx=getx;
         tempy=gety;                  
         moveto(right+vgax(40)-scale*i2d-3,top-vgay(50)+3);
         print_current_state_twod(linknet,lightred,0);            
         moveto(tempx,tempy);
      }
      draw_box(-1,left-vgax(40)+2,top-vgay(50)+2,
                        left+vgax(150),top-vgay(50)+CHeight*1.5,1,0);
      if (show_all==1) sprintf(textb[1],"inputs");
      if (show_all==2) sprintf(textb[1],"outputs");     
      sprintf(textb[0],"step 1, %s=%d/%d, step-s all-def:",
                                     textb[1],tot_so_far,lineL);
      outtext(textb[0]);
      input_string(1,0);
      if (is[0]=='q') goto endFunc;
      if (is[0]=='s') show_steps=1;
   
      while(1){          
         linkfound=0;
         setcolor(linkcolor);  
         for (zu=L;zu!=Maxu;zu--){                               
            if (get_bit(genedone,zu)==0 && get_bit(linknet,zu)==1){
	       linkfound=1;
	       set_bit1(genedone,zu);
               if (show_all==1){  /*inputs*/      
                  if (w_type==1) t_cellx=left+(cscale1-csep1)/3+
			     (t_right-left-cscale1)*(float)(L-zu)/L;
                  else{
                     t_cellx=(cos(-(w_angle*zu))*w_cyclerad)+wox;
                     t_celly=-(sin(-(w_angle*zu))*w_cyclerad)+woy;
                  }
                  for (z=nhoodm[zu]-1;z>=0;z--){
		     if (w_type==1){
		       wiredtox=t_cellx+cscale1*((double)zu-wiring[zu][z]);
                        line(cellx,bottom,wiredtox,top+(cscale-csep));
                     }
                     else line(cellx,celly,t_cellx,t_celly);

                     set_bit1(this_sweep,wiring[zu][z]);                  
	          }
               }
               else if (show_all==2){  /*outputs*/             
                  for (zu1=L;zu1!=Maxu;zu1--){ 
	             for (z=nhoodm[zu1]-1;z>=0;z--){
		        /*fprintf(stderr," %d ",wiring[zu1][z]);*/   
	                if (wiring[zu1][z]==zu){
                           if (w_type==1){ 
                              wiredtox=left+(cscale1-csep1)/3+
		                (t_right-left-cscale1)*(double)(L-zu1)/L;
                              line(cellx,top+(cscale-csep),wiredtox,bottom);
                           }
                           else{
                              wiredtox=(cos(-(w_angle*zu1))*w_cyclerad)+wox;
                              wiredtoy=-(sin(-(w_angle*zu1))*w_cyclerad)+woy;
                              line(cellx,celly,wiredtox,wiredtoy);
                           }
                           set_bit1(this_sweep,zu1); 
                        }
	             }
                     /*fprintf(stderr,"\n");*/
                  }
               }
	    }
            else{
	         /*fprintf(stderr,"-,");*/
                 continue;
            }
         }

         /*fprintf(stderr,"\n");*/
         for (zu=L;zu!=Maxu;zu--){
            if (get_bit(this_sweep,zu)==1){ 
               set_bit1(linknet,zu);
               set_bit(this_sweep,zu,0);
            }
         }
         tot_before=tot_so_far;
         tot_so_far=0;
         for (zu=L;zu!=Maxu;zu--){                   
            if (get_bit(linknet,zu)==1) tot_so_far+=1;
         }
         if (linkfound==1 && tot_before<tot_so_far) t_step+=1;               
         if (show_steps==1 || linkfound==0 || tot_before==tot_so_far){
            /*draw 2d rep*/
            if (j2d<=36){
               tempx=getx;
               tempy=gety;            	      
	       moveto(right+vgax(40)-scale*i2d-3,top-vgay(50)+3);
	       print_current_state_twod(linknet,lightred,0);            
               moveto(tempx,tempy);
            }
            draw_box(-1,left-vgax(40)+2,top-vgay(50)+2,
                        left+vgax(150),top-vgay(50)+CHeight*1.5,1,0);
            setcolor(white);
            if (show_all==1) sprintf(textb[1],"inputs");
            if (show_all==2) sprintf(textb[1],"outputs");                
            sprintf(textb[0],"step %d, %s=%d/%d=%.1f%%",
                  t_step,textb[1],tot_so_far,
                              lineL,100.0*((float)tot_so_far/lineL));
            outtext(textb[0]);
          
            if (linkfound==0 || tot_before==tot_so_far){
               outtext(" complete");
               input_string(1,0);
               break;
            }
            else{ 	       
               outtext(" cont-ret:");
               input_string(1,0);
               if (is[0]=='q') goto endFunc;
            }
            
         }
         /*give set of wires a different color*/
         if (linkcolor==lightred)       linkcolor=magenta;
         else if (linkcolor==magenta)   linkcolor=brown;
         else if (linkcolor==brown)     linkcolor=yellow;
         else if (linkcolor==yellow)    linkcolor=green; 
         else if (linkcolor==green)     linkcolor=lightcyan;
         else if (linkcolor==lightcyan) linkcolor=lightred;        
	 setcolor(linkcolor);	                  
      }
    endFunc:
      moveto(textbx,textby);              
      poss=startposs;
      setcolor(white);
      free(linknet);
      free(genedone);
      free(this_sweep);              
      direct_wire=temp_direct_wire;           
      if (w_type==1) erase_box(left-vgax(40)+2,top-vgay(50)+2,
                        left+vgax(150),top-vgay(50)+CHeight*1.5);
      /*erase draw 2d rep*/
      if (j2d<=36) erase_box(right+vgax(40)-scale*i2d-4,top-vgay(50)+2,
                right+vgax(40)-3,top-vgay(50)+3+scale*j2d);
      scale=t_scale;
      sep=t_sep;
      i2d=t_i2d;
      j2d=t_j2d;
}

/*************************  draw 1d links, timesteps **************************/  
void draw_1d_links(float bottom,float top,float nhoodlevel,
              float cellx,float cscale,
               float cscale1,float csep,
                char direct_wire,char showrules,unsigned int poss, 
                    char just_block){

   float wiredtox;
   unsigned int tempx1,tempy1,ruleposs;
   signed int z,zz,thiscsep;
   char disconnect,fillcolor;

              if (rulemix) ruleposs=poss;
	      else ruleposs=0;

	      thiscsep=0;
	      if ((signed int)csep>0)
		    thiscsep=(signed int)csep-1;
	      if (nhoodm[poss]%2==1)
	         moveto(cellx+thiscsep
                    -((cscale)*nhoodm[poss])/2,nhoodlevel);
	      else
	         moveto(cellx+thiscsep
                    -((cscale)*(nhoodm[poss]-1))/2,nhoodlevel);
              if (bground=='w') fillcolor=blue;
              if (bground=='b') fillcolor=yellow;
	      setfillstyle(SOLID_FILL,fillcolor);

	      for (z=nhoodm[poss]-1;z>=0;z--){ 
	         /*draw pseudo-cells*/
		if (direct_wire==0){                 
                    if (wiring_postscript){
		       color_ps(wiring_postscript-1,fillcolor);
                       rect_fill_ps(getx,gety,
                          (signed int)(cscale-csep),(signed int)(cscale-csep));
                       color_ps(wiring_postscript-1,white);
                       rect_outline_ps(getx,gety,
		       (signed int)(cscale-csep),(signed int)(cscale-csep));     
	            }    
		    bar3d(getx,gety,getx+cscale-csep,
                                        gety+cscale-csep,0,1);
                    
		 }
	         tempx1=getx;
	         tempy1=gety;
	         /*line from bottom cell to pseudo-cell*/
                 if (direct_wire==0){
                    if (wiring_postscript)
		        line_ps((signed int)cellx,(signed int)bottom,
                                 getx+(signed int)((cscale-csep)/2),
				 (signed int)(nhoodlevel+cscale-csep));
	            line(cellx,bottom,getx+(cscale-csep)/2,
				      nhoodlevel+cscale-csep);
                 }   
                 //wiredtox=cellx+cscale1*((double)poss-wiring[poss][z]);
		 wiredtox=cellx+cscale1*((float)poss-wiring[poss][z]);
                
                 /*check if cell is connected*/
                 disconnect=0;
                 if (tot_only==0 && showrules==1 && nhoodm[poss]==1 &&     
		     wiring[poss][z]==poss){
                    for (zz=nhoodm[poss]-1;zz>=0;zz--){
		       if (get_value(carule[ruleposs],zz) == zz) disconnect=1;
                       else {
                          disconnect=0;
                          break;
                       }
                    } 
                 } 
                 if (disconnect==1); /*dont draw link*/
             
	         /*line from pseudo-cell to top cell*/
		 /*if cell is not connected*/     
		 /*if (showrules==1 && nhoodm[poss]==1 &&     
		      wiring[poss][z]==poss &&
		      dec_equiv(carule[ruleposs],1)==2);*//*do nothing*//*$$$*/
                 
                 
		 else{
                    if (wiring_postscript){
                       if (just_block==0) color_ps(wiring_postscript-1,white);
                       else color_ps(wiring_postscript-1,red);
                    }
		    if (direct_wire==0){
		      if (wiring_postscript) 
                           line_ps(getx+(signed int)((cscale-csep)/2),
                                 (signed int)nhoodlevel,(signed int)wiredtox,
				     (signed int)(top+(cscale-csep)));
                       line(getx+(cscale-csep)/2,nhoodlevel,wiredtox,
				     top+(cscale-csep));
		    } 
	            else{
                       if (wiring_postscript)
                            line_ps((signed int)cellx,(signed int)bottom,
                              (signed int)wiredtox,(signed int)(top+(cscale-csep)));		       
                       line(cellx,bottom,wiredtox,top+(cscale-csep));
		       /*for hires Dell 3200x1800 -- unpredictable screen lines without this - ??
		          though line_ps( was ok*/
		       while(event_ready()==0) break;
		    }
                 }
	         moveto(tempx1,tempy1);
	         if (direct_wire==0) moverel(cscale,0);
	      }	      
}

/*************************  draw 1d links, circle **************************/  
void draw_1d_links_c(float wox, float woy,
           float cellx,float celly,
               float cscale,float csep,
                  char direct_wire,char showrules,unsigned int poss,
                    float w_angle, float w_cyclerad,char just_block){

   float wiredtox,wiredtoy;
   unsigned int /*tempx1,tempy1,*/ruleposs;
   signed int z,tempx,tempy;
   float wi_angle;
   char fillcolor;
   float ncscale,ncsep; /*to draw nhood circles*/

      /*angle between inputs to psuedo nhood*/
      wi_angle=2* atan((double)(cscale/(w_cyclerad/5)))/
					      pow((double)nhood,.5);

       ncscale=cscale*925/(Maxx+1); /*readjust for hires Dell 3200x1800 (def ddlab 2112x1584)*/
       ncsep=csep*694/(WinMaxy+1);
       
              if (rulemix) ruleposs=poss;
	      else ruleposs=0;
              if (bground=='w') fillcolor=blue; /*yellow balls, black outline*/
              else fillcolor=yellow; /*lightblue balls, yellow outline*/
	      setfillstyle(SOLID_FILL,fillcolor);
	      for (z=nhoodm[poss]-1;z>=0;z--){ 
	         /*draw pseudo-cells*/
                 if (direct_wire==0){
		    /*bar3d(getx,gety,getx+cscale-csep,
		          gety+cscale-csep,0,1);*/                   
                    moveto( (cos(-(w_angle*poss - 
                         wi_angle*(nhoodm[poss]-1)/2 + wi_angle*z ))
                                         *w_cyclerad*.75)+wox,
                    -(sin(-(w_angle*poss -
                         wi_angle*(nhoodm[poss]-1)/2 + wi_angle*z ))
                                        *w_cyclerad*.75)+woy);
                    tempx=getx;
                    tempy=gety;
                    if (wiring_postscript){
                        line_ps(cellx,celly,tempx,tempy);
                        color_ps(wiring_postscript-1,fillcolor);
                        circle_fill_ps(tempx,tempy,(double)vgax(ncscale-ncsep));/*filled circle*/
                        color_ps(wiring_postscript-1,white);
                        circle_ps(tempx,tempy,(double)vgax(ncscale-ncsep));/*outline*/
                     }

                    /*line from cell to pseudo-cell*/
                    line(cellx,celly,getx,gety);                   
                    pieslice(1,getx,gety,0,360,vgax(ncscale-ncsep));
                    
                 }
                 
                 wiredtox=(cos(-(w_angle*wiring[poss][z]))*w_cyclerad)+wox;
                 wiredtoy=-(sin(-(w_angle*wiring[poss][z]))*w_cyclerad)+woy; 
	         /*line from pseudo-cell to top cell*/
		 /*if cell is not connected*/     
		 if (tot_only==0 && showrules==1 && nhoodm[poss]==1 &&     
		       wiring[poss][z]==poss &&
		           dec_equiv(carule[ruleposs],1)==2);/*do nothing*//*$$$*/ 
		 else{
                    if (wiring_postscript){
                       if (just_block==0) color_ps(wiring_postscript-1,white);
                       else color_ps(wiring_postscript-1,red);
                    }
		    if (direct_wire==0){
                       line(getx,gety,wiredtox,wiredtoy);
                       if (wiring_postscript) line_ps(tempx,tempy,wiredtox,wiredtoy);
                    }
                    else{
                       line(cellx,celly,wiredtox,wiredtoy);
                       if (wiring_postscript) line_ps(cellx,celly,wiredtox,wiredtoy);
                    }
		 }
	      }	      
}

/******** untangle wiring and transform rules accordingly  ****************/
void untangle_wiring(unsigned int poss, char showrules,
	     char *catemp, char *ca_tickoff,
                  char *nhoodbits, char *swap_nhoodbits){
  char unsorted, tangle_found;
  unsigned int z1,temp_poss,dec_swap;
  signed int z,t_bytes,tablemax,nhood_bytes;

     /*if (tot_only==1) return;*/
     if (rulemix && showrules && tot_only==0){	
        /*max index of ruletable*/
        tablemax= (signed int)pow(value_range,(double)nhoodm[poss])-1;
        /*bytes in ruletable*/
        t_bytes=(signed int)ceil(value_bits * (double)(tablemax+1)/8);
        memmove(catemp,carule[poss],t_bytes);
        nhood_bytes=(signed int)ceil((double)(nhood*value_bits)/8); 
     }
     unsorted=1;		         
     while(unsorted==1){
	tangle_found=0;
	for (z=nhoodm[poss]-2;z>=0;z--){
	   /*swap wires connections*/
	   if (wiring[poss][z+1] < wiring[poss][z]){	      
	      tangle_found=1;
	      temp_poss=wiring[poss][z];
	      wiring[poss][z]=wiring[poss][z+1];
	      wiring[poss][z+1]=temp_poss;
	      /*--------------------------------*/
	      if (rulemix && showrules && tot_only==0){		 
	         /*transform rule for equiv dynamics*/
		 for (z1=0;z1<=t_bytes;z1++) ca_tickoff[z1]=0;
	         for (z1=0;z1<=tablemax;z1++){
		    if (get_bit(ca_tickoff,z1)==1) continue;
                    set_bit(ca_tickoff,z1,1);
                    if (value_range==2){		       
	               dec_to_bit_line(nhoodbits,
			     (unsigned long)z1,(signed int)nhoodm[poss]);
                       if (get_bit(nhoodbits,z+1)!=get_bit(nhoodbits,z)){
		          /*swap nhood bits*/
		          memmove(swap_nhoodbits,nhoodbits,nhood_bytes);
		          set_bit(swap_nhoodbits,z+1,get_bit(nhoodbits,z));
		          set_bit(swap_nhoodbits,z,get_bit(nhoodbits,z+1));
		    
		          dec_swap=(unsigned int)
			     dec_equiv(swap_nhoodbits,nhoodm[poss]-1);
                          set_bit(catemp,z1,get_bit(carule[poss],dec_swap));
		          set_bit(catemp,dec_swap,get_bit(carule[poss],z1));
		          set_bit(ca_tickoff,dec_swap,1);
		       }
                    }
                    else{
                       dec_to_value_line(nhoodbits,
			     (unsigned long)z1,(signed int)nhoodm[poss]);
                       if (get_value(nhoodbits,z+1)!=get_value(nhoodbits,z)){
		          /*swap nhood bits*/
		          memmove(swap_nhoodbits,nhoodbits,nhood_bytes);
		          set_value(swap_nhoodbits,z+1,get_value(nhoodbits,z));
		          set_value(swap_nhoodbits,z,get_value(nhoodbits,z+1));
		    
		          dec_swap=(unsigned int)
			     dec_equiv(swap_nhoodbits,nhoodm[poss]-1);
                          set_value(catemp,z1,get_value(carule[poss],dec_swap));
		          set_value(catemp,dec_swap,get_value(carule[poss],z1));
		          set_bit(ca_tickoff,dec_swap,1);
		       }
                    }
	         }
	         memmove(carule[poss],catemp,t_bytes);
	      }
	      /*----------------------------------*/
	   }
	}
	if (tangle_found==0) unsorted=0;
     }
}              
/************************* draw 3d frame**************************/
void draw_save_3d_frame(float fscale, 
      signed int sboxx, signed int sboxy, char draw_3d_grid){ 

   float axo_cell_h,aa;

             setfillstyle(SOLID_FILL,black);
             bar(sboxx,sboxy,
             sboxx+i3d*fscale+j3d*sin(PI/4)*fscale,
             sboxy+h3d*fscale+j3d*sin(PI/4)*fscale+1);

             d_mode=4;
             /*draw frame*/      
             axo_cell_h=sin(PI/4)*fscale;
	     aa=axo_cell_h*j3d;    
             
             moveto(sboxx,sboxy+aa);
             draw_axon_plane(fscale,gety,draw_3d_grid);
}

/********** show wiring layout as 2-d graphic, Dec 93 ******************/
void show_graphic_wiring_2d_3d(char showrules){
  unsigned int poss=0,oldposs=0;
 signed int z,zz,xbox,tempx,tempy,textbx,textby,pixcolor,
   tablebytes,limitbytes,
   ii,jj,tempi,tempj,
   temp_ii,temp_jj,temp_hh,   
   old_ii,old_jj,old_hh, /*for setting a block with the mouse*/   
   i3,j3,h3,ccel_x,ccel_y, /*for 3d wiring*/
   fheight_max; /*max height of 3d cage*/
 float left=0,top=0,topbox=0,right=0,bottom=0,this_bottom,start_bottom,
   cscale=0,csep=0,cellx=0,celly=0,maxside=0,
   fscale;/*for 3d was char*/
 char oned_as_twod=0,csep_zero_force=0;
 unsigned int thisposs;
 float tempx2,tempy2;
 char direct_wire=0,show_pindex=0, suppress_links=0,suppress_links_block=0,
      scale_changed=0,v_changed=0,
      block_set=0,show_block=0,block_edges=1,learn_sometime=0,sculpt_basin=0;
 unsigned int startposs=0,endposs=0,zzu,count_rows;/*for 3d box*/
 signed int sboxx,sboxy,low_ii,low_jj,low_hh,high_ii,high_jj,high_hh;
 unsigned char tempcolor,outcolor;
 double hex_vmove;
 signed int fid_temp_PS;
 char temp_basin_postScript,show_prompt,draw_3d_grid;

 signed int X1,Y1,X2,Y2, /*for mouse*/
            mxtemp=0,mytemp=0; /*for Watcom mouse move*/
 char event_happened=0,test_key,
      inside_rect=0; /*for mouse*/

        show_prompt=1; /*toggled with 'W' to not show*/
        draw_3d_grid=1; /*grid lines toggled with 'T' to not show if <5 pixels, */
        fid_temp_PS=fid_PS;
        temp_basin_postScript=basin_postScript;
        inside_wiring_graphic=1;/*need this to show rules in xterm with 'x' */
        suppress_links_block=3;/*initially show just cells (was just links), if block set*/
        wiring_postscript=0; /*global variable - 
                              needed for draw_save_3d_frame .. draw_axon_plane*/
	/*arrows:128+  75=left,77=right,72=up,80=down*/
        ca_bias=0; /*in case this was set in bias_random_wiring()*/
	tempi=i2d;
	tempj=j2d;

	if (oned && nonlocal==1) direct_wire=1;
        if (twod){     
          if (threed==0 && regular2d_tgrid==1) 
                        hex2d=1; /*2d hex layout*/
          if (nhood==6 || nhood==7 || nhood==10 || nhood==15 ||
                         nhood==18 || nhood==19 || nhood==22) {
             if  (regular2d_tgrid==0) direct_wire=1;
	  }
          else if (regular2d==0) direct_wire=1;
        }
        if (threed && regular3d==0) direct_wire=1;

	if (oned) set_i2dxj2d();  /*To represent 1d and 3d networks in 2d */
	else if (threed){
	   i2d=i3d;
	   j2d=j3d*h3d;
	}

	if (i2d>=j2d)  maxside=i2d;
	else maxside=j2d;

	/*set the scale same as seed*/
	if (i2d<=30 && j2d<=30) cscale=vgax(7);
	else{
	   if (threed) cscale=floor((float)(Maxy*.8)/maxside);
	   else cscale=floor((float)(Maxy*.5)/maxside);
	}
	if (cscale<1) cscale=1;

	start_bottom=vgay(390);
        this_bottom=bottom=start_bottom;

	if (threed){
           /*capture active screen to restore if q or return*/
           draw_box(20,0,0,Maxx,start_bottom+vgay(40)-2,0,-1);
           draw_box(-1,0,0,Maxx,start_bottom+vgay(40)-2,0,black);/*blank out*/

	   fscale=vgax(8); /*initial cell scale of 3d frame*/
	   fheight_max=vgay(390)-CHeight*5;
	   while (h3d*fscale + j3d*sin(PI/4)*fscale > fheight_max){
	      fscale-=1;
	   }
	}
        get_prompt_box(3,6); /*get area under prompt box, 6 lines*/

        /*-------------goto cycles back to here----------------*/
       start:
        //to toggle between no gap and gap between cells, makes plane grid for block
        if (csep_zero_force==1) csep=0;
        else{
	   if (cscale>=vgax(7)) csep=vgax(3);
	   else if (cscale>=3) csep=2;
	   else csep=1;
           if (cscale<=1) csep=0;
	}
        
	if (v_changed==1){
	   bottom=this_bottom;
	   v_changed=0;
	}
	top=bottom-(j2d+1)*cscale;
	/*top of grid*/
	if (top<0) top=0;
	topbox=top-vgay(50); /*top of window*/
	if (topbox<0) topbox=0;
        if (topbox>Maxx) topbox=Maxx;
	left=vgax(42);
	right=left+(i2d+1)*cscale;
        if (right>Maxx) right=Maxx; /*right of window*/
      

        /*get area under data box, no outline or background*/
	draw_box(3,left-vgax(40)+2,start_bottom+vgay(40)-vgay(17),
			vgax(620),start_bottom+vgay(40)-2,0,-1);

        /*2d box 1*/
        draw_box(7,left-vgax(40),topbox,
		 right+vgax(37),start_bottom+vgay(40),0,black);//was right+vgax(38)

        if (twod){
           setcolor(yellow);
           rectangle(left-vgax(40),topbox,
		  right+vgax(34)-vgax(4),start_bottom+vgay(40));//new
           setcolor(white);
        }

        X1=left;
        Y1=bottom-(j2d+1)*cscale; //top is limited, if (top<0) top=0;
        if (regular2d_tgrid==1) Y1=bottom-(j2d+1)
				  *(signed int)ceil((cscale*cos(PI/6)));/*for hex grid*/
        X2=left+(i2d+1)*cscale; //right is limited, if (right>Maxx) right=Maxx;
        Y2=bottom;
        /*setcolor(green);
	  rectangle(X1,Y1,X2,Y2);//tight outline around dots, also mouse border
        setcolor(white);*/

        if (twod && wiring_postscript){
              color_ps(wiring_postscript-1,lightred);
              rect_outline_ps(left-vgax(40),topbox,
			      abs(left-vgax(40)-(right+vgax(38))),
			      abs(start_bottom+vgay(40)-topbox));
        }

	/* create a nominal box for 3d*/
	if (threed) draw_box(17,0,0,1,1,0,-1);
	/*keep net graphics inside box*/
	setviewport(   (signed int) (left-vgax(40)),
		       (signed int) topbox,
		       (signed int) (right+vgax(38)), //38 was 18 not bigger than Maxx?
		       (signed int) (start_bottom+vgax(18)),1);
	/*2-d grid*/
        count_rows=-1;
        if (hex2d==1 && cscale>=1) hex_vmove=(signed int)ceil((cscale*cos(PI/6)));
	else hex_vmove=cscale;
	for (zz=j2d-1;zz>=0;zz--){
	   count_rows++;
	   for (z=i2d-1;z>=0;z--){
	      if (zz==j2d-1 || zz==0 || z==i2d-1 || z==0) pixcolor=white;
	      else pixcolor=lightcyan;
	      moveto(right-(z+1)*cscale+((cscale-csep)/2),
		     bottom-(zz+1)*hex_vmove+((hex_vmove-csep)/2));

              /*if (getx<-cscale || getx>Maxx+cscale ||
		gety<-cscale || gety>start_bottom+vgax(18)+cscale) continue;*/

              if (hex2d==1  && cscale>=1 && count_rows%2==1) /*hex layout*/
		              moveto(getx+cscale/2,gety);
	      if (threed && zz%j3d==0 && (z+1)%i2d==0 && zz!=0){
		  /*draw lines to mark 2d levels*/
		  tempx=getx;
		  tempy=gety;
		  tempcolor=getcolor();
		  setcolor(lightred);

		  moveto(right+(cscale-csep)/2,gety);
		  
                  if (wiring_postscript){
                           color_ps(wiring_postscript-1,lightred);
                           line_ps(getx,gety,getx+vgax(5),gety);
                  }
                  lineto(getx+vgax(5),gety);
		  moveto(getx+vgax(2),gety-CHeight*.7);


                  //revize this to reduce scale of level numbers??
		  sprintf(textb[1],"%d",zz/j3d);

                  if (wiring_postscript) 
		     nodetext_ps(3,bground,textb[1],getx,gety+CHeight*.8); 
		  outtext(textb[1]);
		  moveto(tempx,tempy);
		  setcolor(tempcolor);
	      }
	      if (cscale>=4){
                  if (wiring_postscript){
                           color_ps(wiring_postscript-1,pixcolor);
                           smallspot_ps(getx,gety,1);
                  } 
                  putpixel(getx,gety,pixcolor);
              }
	      else if (pixcolor==white){                  
                  if (wiring_postscript){
                           color_ps(wiring_postscript-1,pixcolor);
                           smallspot_ps(getx,gety,1);
                  }
                  putpixel(getx,gety,pixcolor);
              }
	   }
	}
	/*add co-ords to grid*/
	moveto(right-i2d*cscale+(cscale-csep)/2,
		     bottom-j2d*hex_vmove+( hex_vmove-csep)/2);
        if (wiring_postscript){
             color_ps(wiring_postscript-1,getcolor());
             line_ps(getx,gety-vgay(10),getx,gety-vgay(5));
        }
	line(getx,gety-vgay(10),getx,gety-vgay(5));

	if (oned || twod) sprintf(textb[1],"%d",i2d-1);
	else if (threed) sprintf(textb[1],"%d",i3d-1);
	moveto(getx-textwidth(textb[1])/2,gety-vgay(12)-CHeight);
        if (wiring_postscript)
	               nodetext_ps(3,bground,textb[1],getx,gety+CHeight*.8);
	outtext(textb[1]);
	moveto(right-i2d*cscale+(cscale-csep)/2,
		     bottom-j2d*hex_vmove+(hex_vmove-csep)/2);
        if (wiring_postscript)
             line_ps(getx-vgax(10),gety,getx-vgax(5),gety);
	line(getx-vgax(10),gety,getx-vgax(5),gety);
	if (oned ||twod) sprintf(textb[1],"%d",j2d-1);
	else if (threed) sprintf(textb[1],"%d",j3d-1);
	moveto(getx-textwidth(textb[1])-vgax(11),
				     gety-(float)CHeight*.7);
        if (wiring_postscript)
	               nodetext_ps(3,bground,textb[1],getx,gety+CHeight*.8);
	outtext(textb[1]);

	moveto(right-cscale+((cscale-csep)/2),
		     bottom- hex_vmove+(( hex_vmove-csep)/2));
        if (hex2d==1  && cscale>=1 && count_rows%2==1) /*hex layout*/
		              moveto(getx+cscale/2,gety);
        if (wiring_postscript)
             line_ps(getx+vgax(5),gety,getx+vgax(10),gety);
	line(getx+vgax(5),gety,getx+vgax(10),gety);
	moveto(getx+vgax(12),gety-(float)CHeight*.7);
        if (wiring_postscript)
	               nodetext_ps(3,bground,"0",getx,gety+CHeight*.8);
	outtext("0");
        
	moveto(right-cscale+((cscale-csep)/2),
		     bottom-hex_vmove+(( hex_vmove-csep)/2));
        if (hex2d==1  && cscale>=1 && count_rows%2==1) /*hex layout*/
		              moveto(getx+cscale/2,gety);
	line(getx,gety+vgax(5),getx,gety+vgax(10));
        if (wiring_postscript)
             line_ps(getx,gety+vgax(5),getx,gety+vgax(10));
	moveto(getx-CWidth*.5,gety+vgay(10));
        if (wiring_postscript)
	               nodetext_ps(3,bground,"0",getx,gety+CHeight*.8);
	outtext("0");

	
	/*restore viewport*/
	//setviewport(0,0,Maxx,Maxy,1);
        setviewport(0,0,Maxx,(signed int)(start_bottom+vgay(40)-vgay(17)),1);

	/*draw 3d cell wiring*/
	if (threed==3){
	      sboxx=right+vgax(38);
	      sboxy=start_bottom-h3d*fscale-j3d*sin(PI/4)*fscale;
	      draw_save_3d_frame(fscale,sboxx,sboxy,draw_3d_grid);
              freeimage(boximage[17]);
              draw_box(17,right,0,Maxx,start_bottom,0,-1);/*3d area*/
	}
	/*2d box 2*/
	draw_box(6,left,top,right+cscale/2,start_bottom,0,0);
	if (scale_changed==0){
	  unsigned int tx,ty,tz;          
           /*start in centre*/
	   if (oned) poss=lineL/2;
           else if (twod){
	      tx=i2d/2;
	      ty=j2d/2;
              poss=i2d*ty+tx;
	   }
           else if (threed){
	      tx=i3d/2;
	      ty=j3d/2;
	      tz=h3d/2;
              poss=i3d*j3d*tz + i3d*ty + tx;
	   }
           if (outer_tot==1) poss=0; //why?? 
	}
	scale_changed=0;
        ii=poss%i2d;
	jj=poss/i2d;

        /*prompt box*/
        if (show_prompt==1) draw_2d_3d_graphics_prompt(startposs,endposs,poss,
		    showrules,block_set,suppress_links,suppress_links_block);
	textbx=getx;
	textby=gety;

	/*circle/square outline color*/
        outcolor=white; //works for both white and black background

	while(1){
            tablebytes=(signed int)ceil(
                      value_bits * pow(value_range,(double)nhoodm[poss])/8);
            /*dont print hex if table bigger that v2k5 or equiv*/
            limitbytes=(signed int)ceil(pow(2,(double)5)/8);
	    cellx=right-(ii+1)*cscale;
	    celly=bottom-(jj+1)*cscale;
	    moveto(cellx,celly);
	    poss=i2d*jj+ii;      
	    if (showrules && (rulemix ||
                    (outer_tot==1 && poss<value_range))  ){	
	       if (tot_only==0) show_rule_bottom(nhoodm[poss],0,carule[poss],poss);
               else{
                  if (totalistic==1) show_rule_bottom(nhoodm[poss],0,cacode[poss],poss);
                  else if (totalistic==2) show_rule_bottom(nhoodm[poss],0,v_code[poss],poss);
               }
	    }
	    
	    /*show data, confine in box in case too long*/
	    setviewport((signed int)(left-vgax(40)+2),
			(signed int)(start_bottom+vgay(40)-vgay(17)),
			vgax(620),
			(signed int)(start_bottom+vgay(40)-2),1);
	    draw_box(-1,left-vgax(40)+2,start_bottom+vgay(40)-vgay(17),
		        vgax(620),start_bottom+vgay(40)-2,1,black);

            if (wiring_postscript){
                  color_ps(wiring_postscript-1,black);
                  rect_fill_ps((left-vgax(40))+2,start_bottom+vgay(40)-vgay(17),
		    abs((left-vgax(40)+2)-vgax(620)),
		       abs((start_bottom+vgay(40)-vgay(17))-(start_bottom+vgay(40)-3)));
                  color_ps(wiring_postscript-1,lightred);
                  rect_outline_ps((left-vgax(40))+2,start_bottom+vgay(40)-vgay(17),
		    abs((left-vgax(40)+2)-vgax(620)),
		       abs((start_bottom+vgay(40)-vgay(17))-(start_bottom+vgay(40)-3)));
            }
            if (wiring_postscript) color_ps(wiring_postscript-1,white);
            
            tempx=getx;
            tempy=gety;
            sprintf(textb[0],"textb[%d]",z);
     
	    if (oned) printf(textb[3]," 1d cell=%d",poss);
	    else if (twod) sprintf(textb[3], "2d cell=%d,%d=%d",ii,jj,poss);
	    else if (threed){
		temp_ii=poss%i3d;
		temp_jj=poss%(i3d*j3d)/i3d;
		temp_hh=poss/(i3d*j3d);
		sprintf(textb[3]," 3d cell=%d,%d,%d=%d",temp_ii,temp_jj,temp_hh,poss);
	    }

            sprintf(textb[2],"%s",textb[3]);

	    if (!nhood_mixed) sprintf(textb[3]," wiring=");
	    else sprintf(textb[3]," maxk=%d k=%d wiring=",
	                                         nhood,nhoodm[poss]);

            /*-----strcat seg fault for big networks, textb[0,1,2] size increased---*/
            strcat(textb[2],textb[3]);
	    for (z=nhoodm[poss]-1;z>=0;z--){
               thisposs=wiring[poss][z];
               if (oned){
                   sprintf(textb[3],"%d ",thisposs);
                   strcat(textb[2],textb[3]);
               }
               else if (twod){
                  temp_ii=thisposs%i2d;
	          temp_jj=thisposs/i2d;
                  sprintf(textb[3],"%d,%d ",temp_ii,temp_jj);
                  strcat(textb[2],textb[3]);
               }
               else if (threed){
                  temp_ii=thisposs%i3d;
	          temp_jj=thisposs%(i3d*j3d)/i3d;
                  temp_hh=thisposs/(i3d*j3d);                  
                  sprintf(textb[3],"%d,%d,%d-",temp_ii,temp_jj,temp_hh);
                  strcat(textb[2],textb[3]);
               }
	    }
            
	    sprintf(textb[3],"outwires=%d ",celloutfreq[poss]);    
            strcat(textb[2],textb[3]);
            strcat(textb[2],"links:");
            if (nhood_mixed){
               sprintf(textb[3],"total=%lu av-k=%.2f ",
                       tot_wires, (float)tot_wires/lineL);
               strcat(textb[2],textb[3]);
            }
	    if (lineL<=2500){
	       sprintf(textb[3],"bi=%d ",tot_bi_links);
               strcat(textb[2],textb[3]);
	    }
            sprintf(textb[3],"self=%d=%.1f%% ",tot_self_links,
                                 100*(float)tot_self_links/tot_wires);
                        strcat(textb[2],textb[3]);
            sprintf(textb[3],""); /*empty textb[3] because its being printed to xterm ??*/

            psize_ps=15;
            if (strlen(textb[2])*CWidth>vgax(620)){
	         set_medium_font(); //CWidth=CWidth_def*.8;
		 psize_ps=12;
            }
            if (strlen(textb[2])*CWidth>vgax(620)){
	         set_small_font(); //CWidth=CWidth_def*.6;
		 psize_ps=9;
            }
            if (wiring_postscript){
                 resetfont_ps("Times-Roman", psize_ps);
	         nodetext_ps(3,bground,textb[2],getx,gety+CHeight_def*.9);
            }
            moveto(getx,gety+ceil( (double)CHeight_def/CHeight) ); /*to center text*/
	    outtext(textb[2]);
            restore_def_font();
            if (wiring_postscript) resetfont_ps("Times-Roman", pointsize);

            sprintf(textb[2],""); /*empty textb[2] because its showing in xterm ??*/
            /*--------------------------------------------------------------------------*/

            /*no need as rule appears in the bottom rule window*/
	    /*if (rules_set && tablebytes<=limitbytes){
	      if (rulemix ||
                      (outer_tot==1 && poss<value_range)) thisposs=poss;
	      else thisposs=0;
	      sprintf(textb[1],"k%d-rule=(hex)",nhoodm[poss]);
	      outtext(textb[1]);
	      if (tot_only==0) 
                print_current_bitstring_hexbytes(16,1,carule[thisposs],nhoodm[thisposs],Maxx,white,0);
	    }*/

            /*restore viewport*/
	    //setviewport(0,0,Maxx,Maxy,1);
            setviewport(0,0,Maxx,(signed int)(start_bottom+vgay(40)-vgay(17)),1);

            /*2d array*/
            sprintf(textb[9],"%s","boximage[6]");
	    putimage(left,top,boximage[6],COPY_PUT,textb[9]);
            
            if (threed){
                 /*refresh 3d frame*/
                 sprintf(textb[9],"%s","boximage[17]");
                 putimage(right,0,boximage[17],COPY_PUT,textb[9]);

                 if (show_prompt==1)/*prompt box*/
                    draw_2d_3d_graphics_prompt(startposs,endposs,poss, 
		         showrules,block_set,suppress_links,suppress_links_block);
                
	         textbx=getx;
	         textby=gety;

                 /*convert to 3d co-ords*/
                 i3=poss%i3d;
	         j3=poss%(i3d*j3d)/i3d;
                 h3=poss/(i3d*j3d);
                 /*define central 3d cell location*/
                 ccel_x=
		   right+vgax(38)+i3d*fscale+j3d*sin(PI/4)*fscale
                    -i3*fscale-j3*sin(PI/4)*fscale-fscale;
                 ccel_y= start_bottom-j3d*sin(PI/4)*fscale
                         -h3*fscale+j3*sin(PI/4)*fscale;
                 /*draw 3d x-hairs*/
                 setcolor(lightred);
                 line(ccel_x,ccel_y,ccel_x+i3*fscale+fscale/2,ccel_y);/*i*/              
                 if (wiring_postscript){
                      color_ps(wiring_postscript-1,getcolor());
                      line_ps(ccel_x,ccel_y,ccel_x+i3*fscale+fscale/2,ccel_y);
                 }
                 line(ccel_x,ccel_y,ccel_x-(j3d-j3)*sin(PI/4)*fscale+fscale/2,
                                    ccel_y+(j3d-j3)*sin(PI/4)*fscale-fscale/2);/*j*/
                 if (wiring_postscript) line_ps(ccel_x ,ccel_y,
                                       ccel_x-(j3d-j3)*sin(PI/4)*fscale+fscale/2, 
                                       ccel_y+(j3d-j3)*sin(PI/4)*fscale-fscale/2);
                 line(ccel_x,ccel_y,ccel_x,ccel_y-(h3d-h3)*fscale +fscale/2);/*h*/
                 if (wiring_postscript){  
                       line_ps(ccel_x,ccel_y,ccel_x,ccel_y-(h3d-h3)*fscale +fscale/2);   
                       color_ps(wiring_postscript-1,white);
                 }      
                 setcolor(white);  
            }
            tempcolor=getcolor();
            if (show_block==1){
              unsigned int this_startposs=0,this_endposs=0;
              char all_block=0;
	       if (block_set==0){
                   this_startposs=0;
                   this_endposs=lineL-1;
                   all_block=1;
                   block_set=1;
               }
               else{
		   this_startposs=startposs;
		   this_endposs=endposs;
               }

               if (oned){
                    for (zzu=this_startposs;zzu<=this_endposs;zzu++){
                       draw_2d_3d_links(zzu,
                          right, start_bottom, bottom,
                            cscale, csep,
			       fscale, 1, show_pindex,suppress_links_block,
                                 outcolor,block_set);
		    }
	       }

               else if (twod){                 
                    for (zzu=this_startposs;zzu<=this_endposs;zzu++){

                       if (all_block==0){
			  if (file_dim==1){ /*block after loading file 1d or conv 1d*/
			    if (zzu>endposs || zzu<startposs) continue;
                          }
                          else if (outside_2d_3d_block(zzu,   //outside block
                                 low_ii,low_jj,low_hh,
                                 high_ii,high_jj,high_hh)==1) continue;
                          /*hollow out 2d block*/
                          else if (block_edges==1){
			     if (outside_2d_3d_block(zzu,   //not outside inner block
                                 low_ii+1,low_jj+1,low_hh+1,
                                 high_ii-1,high_jj-1,high_hh-1)==0) continue;
                          }			  
                       }

                       draw_2d_3d_links(zzu,
                          right, start_bottom, bottom,
                            cscale, csep,
			       fscale, 1, show_pindex,suppress_links_block,
                                 outcolor,block_set);
                  }
               }
               else if (threed){ /*draw block layer by layer -- from top layer down*/
		 signed int ii3,jj3,hh3;
                       for (hh3=h3d-1;hh3>=0;hh3--){
                          for (jj3=j3d-1;jj3>=0;jj3--){
                            for (ii3=i3d-1;ii3>=0;ii3--){
			       zzu=(i3d*j3d*hh3)+(i3d*jj3) + ii3;
                               if (file_dim==1){/*block after loading file 1d or conv 1d*/
			           if (zzu>endposs || zzu<startposs) continue;
                               }
                               else if (all_block==0){
                                  if (outside_2d_3d_block(zzu, //outside block
                                     low_ii,low_jj,low_hh,
                                     high_ii,high_jj,high_hh)==1) continue;

                                  /*hollow out 3d block*/
				  if (block_edges==1){
				     if (outside_2d_3d_block(zzu,   //not outside inner block
                                        low_ii+1,low_jj+1,low_hh+1,
                                        high_ii-1,high_jj-1,high_hh-1)==0) continue;

			             /*hollow out sides of 3d block*/
                                     if (outside_2d_3d_block(zzu,   //not outside inner block
                                        low_ii,low_jj+1,low_hh+1,
                                        high_ii,high_jj-1,high_hh-1)==0) continue;
                                     if (outside_2d_3d_block(zzu,   //not outside inner block
                                        low_ii+1,low_jj,low_hh+1,
                                        high_ii-1,high_jj,high_hh-1)==0) continue;
                                     if (outside_2d_3d_block(zzu,   //not outside inner block
                                        low_ii+1,low_jj+1,low_hh,
                                        high_ii-1,high_jj-1,high_hh)==0) continue;
			          }
                               }
                               
                               draw_2d_3d_links(zzu,
                                  right, start_bottom, bottom,
                                     cscale, csep,
			                fscale, 1, show_pindex,suppress_links_block,
                                           outcolor,block_set);
                        
                       }
                    }
		 }
               }
               if (all_block==1) block_set=0;          
            }

            draw_2d_3d_links(poss,
                          right, start_bottom, bottom,
                          cscale, csep,
                          fscale, direct_wire, show_pindex,
                          suppress_links,outcolor,0);
            
            setcolor(tempcolor);
            /*restore viewport*/
	    //setviewport(0,0,Maxx,Maxy,0);
            setviewport(0,0,Maxx,(signed int)(start_bottom+vgay(40)-vgay(17)),1);

	    moveto(textbx,textby);
	    
            setfillstyle(SOLID_FILL,black);
	    bar(getx,gety,getx+CWidth*2,gety+CHeight);

            if (wiring_postscript==1){ /*disable wiring_postscript*/
               close(fid_PS); 
               wiring_postscript=0;
            }
         
            test_key=0;
            event_happened=0;
            inside_rect=0;

         while(event_happened==0){

#        if __WATCOM__
           mouse_call(7,0,X1,X2); //horizontal limits - confine mouse in array
           mouse_call(8,0,Y1,Y2); //vertical limits
	   if (!kbhit()){
                mouse_call(1,0,0,0); /*display mouse*/ 
                mouse_call(3,0,0,0); /*mouse position*/
                mouse_x=globcx;
	        mouse_y=globdx;
                /*check mousemove and show co-ordinates*/
	        if (mxtemp!=mouse_x || mytemp!=mouse_y){
                  int ipos,jpos;
                       /*show co-ordinates in memory box*/
                       ipos=i2d-1-(int)(i2d* (float)(mouse_x-X1)/(X2-X1));
		       jpos=j2d-1-(int)(j2d* (float)(mouse_y-Y1)/(Y2-Y1));
                       if (ipos<0) ipos=0;
                       if (jpos<0) jpos=0;
                       if (oned) sprintf(textb[0],"i,j=(%d,%d)=%d",ipos,jpos,poss);
		       else if (twod) sprintf(textb[0],"i,j=%d,%d",ipos,jpos);
                       else if (threed){
                          i3=ipos;
                          j3=jpos%j3d;
                          h3=jpos/j3d;
                          sprintf(textb[0],"i,j,h=%d,%d,%d",i3,j3,h3);
                       } 
                       memory_box(2,textb[0]);
	               mxtemp=mouse_x;
	               mytemp=mouse_y;
	        }
                mouse_call(5,0,0,0); /*check if left mouse button pressed*/
                if (globbx){
                   event_happened=1;
		   mouse_call(2,0,0,0); //hide mouse		 
                   ii=i2d-1-(int)(i2d* (float)(mouse_x-X1)/(X2-X1));
		   jj=j2d-1-(int)(j2d* (float)(mouse_y-Y1)/(Y2-Y1));
                   if (ii<0) ii=0;
                   if (jj<0) jj=0;
                   if (oned || twod){
                           oldposs=poss;
                           poss=i2d*jj + ii;
                   }
                   else if (threed){
                          i3=ii;
                          j3=jj%j3d;
                          h3=jj/j3d;
                          oldposs=poss;
                          poss=(i3d*j3d*h3) + (i3d*j3) + i3;
		   }
                   /*active cell co-ords shown in prompt window, and data window*/
                   draw_2d_3d_graphics_prompt(startposs,endposs,poss,
		        showrules,block_set,suppress_links,suppress_links_block);
                   test_key=0;
                   break;           
	        }
           }
	   else { /*key hit*/
               is[0]=keycheck(1);
               test_key=1;
               event_happened=1;
           }
	   
	        
#        elif __UNIX__	    
            if (!XCheckMaskEvent(D,
		       KeyPressMask|ButtonPressMask|PointerMotionMask,&Event) /*|| is[0]==15*/){
	       usleep(1);     //reduces cpu to about 20%, otherwise was 100% 
               continue;
            }                       
	    if (Event.type == MotionNotify){              
		 mouse_x=Event.xmotion.x;
		 mouse_y=Event.xmotion.y;
		 if (mouse_x>=X1 && mouse_y>=Y1
			       && mouse_x<=X2 && mouse_y<=Y2){
                     int ipos,jpos;
		       XDefineCursor(D,W,leftCursor); //cursor inside array
		       /*show co-ordinates in memory box*/
                       ipos=i2d-1-(int)(i2d* (float)(mouse_x-X1)/(X2-X1));
		       jpos=j2d-1-(int)(j2d* (float)(mouse_y-Y1)/(Y2-Y1));
                       if (ipos<0) ipos=0;
                       if (jpos<0) jpos=0;
                       if (oned) sprintf(textb[0],"i,j=(%d,%d)=%d",ipos,jpos,poss);
		       else if (twod) sprintf(textb[0],"i,j=%d,%d",ipos,jpos);		       
                       else if (threed){
                          i3=ipos;
                          j3=jpos%j3d;
                          h3=jpos/j3d;
                          sprintf(textb[0],"i,j,h=%d,%d,%d",i3,j3,h3);
                       } 
                       memory_box(2,textb[0]);
	         }
                 else{  //cursor outside array
                    XDefineCursor(D,W,rightCursor);
                    erase_memory_box(2);
                 } 
            }

	    if (Event.type==ButtonPress){ /*left or right button*/
                 event_happened=1;
		 mouse_x=Event.xbutton.x;
		 mouse_y=Event.xbutton.y;
                 /*fprintf(stderr,"\nEvent.type==ButtonPress mx=%d my=%d",mouse_x,mouse_y);*/
		 if (mouse_x>=X1 && mouse_y>=Y1
			       && mouse_x<=X2 && mouse_y<=Y2){
                   ii=i2d-1-(int)(i2d* (float)(mouse_x-X1)/(X2-X1));
		   jj=j2d-1-(int)(j2d* (float)(mouse_y-Y1)/(Y2-Y1));
                   if (ii<0) ii=0;
                   if (jj<0) jj=0;
                   if (oned || twod){
                           oldposs=poss;
                           poss=i2d*jj + ii;
                           //fprintf(stderr,"\ni,j=(%d,%d)=%d oldposs=%d",ii,jj,poss,oldposs);
                       }
                   else if (threed){
                          i3=ii;
                          j3=jj%j3d;
                          h3=jj/j3d;
                          oldposs=poss;
                          poss=(i3d*j3d*h3) + (i3d*j3) + i3;
                          //fprintf(stderr,"\ni-j-h=%d-%d-%d",i3,j3,h3);
		   }
                   /*active cell co-ords shown in prompt window, and data window*/
                   draw_2d_3d_graphics_prompt(startposs,endposs,poss,
		        showrules,block_set,suppress_links,suppress_links_block);
                   test_key=0;
                   break;
                    /*left button ==3*/
                    /*if (Event.xbutton.button==2){*/
                    /*right button*/
		    /*if (Event.xbutton.button==3){*/                      
		 }
	     }
             else if (Event.type == KeyPress){
                KeySym key;
                /*mapping from keycodes to keysyms -- use xmodmap -pk to see the current mapping*/ 
		//fprintf(stderr,"\nEvent.type == KeyPress");
                XLookupString(&Event.xkey, NULL , 16, &key, NULL);
                   if (key!=0xffe1 && key!= 0xffe2){ /*not (left or right) shift keys*/
		      button='k';      /*to avoid unnecessary overwrite --for capitals, i.e G*/
		      is[0]=keycheck(0);
                      test_key=1;
                      event_happened=1;
                   }              
             }
#        endif
         }//while(event_happened==0){
         event_happened=0;
	    
	     if (test_key==1){ /*a key was pressed, not mouse button above*/
	      switch(is[0]){
		//case 13: break; /*return to continue*/
	       case'q': 
		 direct_wire=0;
                 break; /*to backtrack*/
	       case'g':
		 jump_graph_table(0,NULL,'n'); //show network-graph
		 draw_2d_3d_graphics_prompt(startposs,endposs,poss,
		    showrules,block_set,suppress_links,suppress_links_block);
		 //is[0]=""; //was an error
		 is[0]=0; //fixed
	         continue;
               case'I': 
		 draw_k_hist(1); /*draw k frequency histogram (inputs)*/
                 is[0]=0;
                 break;
		 
               case'O': 
		 draw_k_hist(2); /*draw output frequency histogram*/
                 is[0]=0;
                 break;
               case'B': 
		 draw_k_hist(3); /*draw in-out frequency histogram*/
                 is[0]=0;
                 break;
               case'f':{                    /*load save network files*/
                char was_loaded,temp_ub;    /*and show as block in graphic*/
                 erase_prompt_box(6);
                 was_loaded=save_load_print_net();
                 is[0]=0;
                 if (was_loaded){
                    if (file_dim==1){
                       startposs=file_starti;
                       endposs=startposs+file_i-1;
                       low_ii=startposs%i2d;
                       low_jj=startposs/i2d; 
                       high_ii=endposs%j2d;
                       high_jj=endposs/j2d;
                    }
                    else if (file_dim==2){
                       low_ii=file_starti;
                       low_jj=file_startj; 
                       high_ii=low_ii+file_i-1; 
                       high_jj=low_jj+file_j-1;

                       startposs=i2d*low_jj + low_ii;
                       endposs=i2d*high_jj + high_ii;
                       
                    }
                    else if (file_dim==3){
                       low_ii=file_starti;
                       low_jj=file_startj;
                       low_hh=file_starth; 
                       high_ii=low_ii+file_i-1; 
                       high_jj=low_jj+file_j-1;
                       high_hh=low_hh+file_h-1;

                       startposs=(i3d*j3d*low_hh)+(i3d*low_jj)+low_ii;
                       endposs=(i3d*j3d*high_hh)+(i3d*high_jj)+high_ii;
                    }
                    temp_ub=nhood_ub;
                    nhood_lb_ub();
                    if (nhood_lb!=nhood_ub){ 
                       nhood_mixed=1;
		    }   
                    nhood_ub=temp_ub;
                    block_set=1;
                    show_block=1;
                    was_changed=1;
		 }
		 break;
               }
               case'S':
                 if (showrules==1){
                    erase_prompt_box(6);
                    if (rulemix ||
                          (outer_tot==1 && poss<value_range)) thisposs=poss;
		    else thisposs=0;
                    if (tot_only==0) load_save_wrs('s',carule[thisposs],0);
                    else{ 
                       if (totalistic==1) load_save_wrs('s',cacode[thisposs],0);
                       if (totalistic==2) load_save_wrs('s',v_code[thisposs],0);
                    }
                    is[0]=0;
                 }
                 break;
	       case'v':  /*revise rule for single cell or block*/
                 if (showrules==1
                      && basin_not_complete==0){ /*not while basin interupted*/
                    erase_prompt_box(6);
                    if (rulemix || 
                      (outer_tot==1 && poss<value_range)) thisposs=poss;
		    else thisposs=0; 
                    revise_rule_graphic(2,block_set,show_block,
                         low_ii,low_jj,low_hh,
                         high_ii,high_jj,high_hh,
                         thisposs,startposs,endposs);
                    is[0]=0;
                 }
		 break;
              case't': /*transform_rule*/
                 if (basin_not_complete==1 /*not while basin interupted*/
                       || showrules==0 || tot_only==1) break; 
                 erase_prompt_box(6);
		 if (rulemix) thisposs=poss;
		 else thisposs=0;
		 tempx2=getx;
		 tempy2=gety;
                 transform_rule(thisposs);
		 moveto(tempx2,tempy2);
		 is[0]=0;
		 break;
              case'D':
                 if (showrules==0) break;
                 erase_prompt_box(6);
                 if (tot_only==0 && totalistic==0) 
                              draw_Derrida_plot(carule);
                 else{
		    if (totalistic==1) draw_Derrida_plot(cacode);
                    else if (totalistic==2) draw_Derrida_plot(v_code);
	         }
                 /*draw_Derrida_plot();*/
                 is[0]=0;
		 break; 
              case'z': /*calculate av. and weighted av. ldz,Z*/
                 if (tot_only==1 || showrules==0 || rulemix==0) break;
                 erase_prompt_box(6);
                 if (rulemix && showrules==1) av_z_para();
		 break;	      
	      case'l': case'L':{ /*l=highlight_only L=Learn*/
               char highlight_only=0;             
		if (showrules==0 || tot_only==1 /*|| rulemix==0*/
                        || basin_not_complete==1) break;/*not while basin interupted*/
                    if (is[0]=='l') highlight_only=1;
                    sculpt_basin=0;
                    sprintf(textb[9],"%s","boximage_prompt[3]");
                    putimage(trboxw,2,boximage_prompt[3],COPY_PUT,textb[9]); 
                    draw_box(19,left-vgax(40),top-vgay(50),
			    right+vgax(40),bottom+vgay(40),0,-1);
                    sprintf(textb[9],"%s","boximage[7]");
		    putimage(left-vgax(40),top-vgay(50),boximage[7],COPY_PUT,textb[9]);
                    sprintf(textb[9],"%s","boximage[3]");
		    putimage(left-vgax(40)+2,start_bottom+vgay(40)-vgay(17),
						        boximage[3],COPY_PUT,textb[9]);
		    learn_sometime=sculpt_basin_field(highlight_only);
                    sculpt_basin=1;
		    was_changed=1;
                    sprintf(textb[9],"%s","boximage[19]");
                    putimage(left-vgax(40),top-vgay(50),boximage[19],COPY_PUT,textb[9]);
                    freeimage(boximage[19]);
		    is[0]=0;
		    break;
	       }  
               case'a': /*toggle showing 1 cell or block*/ 
                        show_block=abs(show_block-1);
                        break;
                case'G': /*toggle hollow/solid block, edge cells only or all cells*/ 
                        block_edges=abs(block_edges-1);
                        break;            
               case'b':{
                       signed int *ijh,*ijh_in,*ijh_def;
                       unsigned int temp_v;
                       char range_type=0,block_all=0;

                       if ((ijh=(signed int *)calloc(3,sizeof(signed int)))
				   ==NULL) outof_memory("ijh");
                       if ((ijh_in=(signed int *)calloc(3,sizeof(signed int)))
				   ==NULL) outof_memory("input_ijh");
                       if ((ijh_def=(signed int *)calloc(3,sizeof(signed int)))
				   ==NULL) outof_memory("input_def");
                       erase_prompt_box(6);
                       block_set=0;
                       xbox=draw_prompt_box(4);

                       
                       if (threed) sprintf(textb[0],
                          "3d block-3, all-a, no block and single cell-def:");
                       else if (twod) sprintf(textb[0],
                          "2d block-2, all-a, no block and single cell-def:");
                       else if (oned) sprintf(textb[0],
                          "1d block-1, all-a, no block and single cell-def:");
                       outtext(textb[0]);
                       input_string(1,0);
                       if (is[0]=='q' || is[0]==13){
                          show_block=0;
                          goto quit_b;
                       }
                       else if (is[0]=='a') block_all='a';
                       
                       if (atoi(is)==1 || atoi(is)==2 || 
                              (atoi(is)==3 && threed)) range_type=atoi(is);
                       if (range_type==1){ 
                          temp_ii=poss;
                          old_ii=oldposs;
                       }
                       else if (range_type==2){
                          temp_ii=poss%i2d;
	                  temp_jj=poss/i2d;
                          old_ii=oldposs%i2d;
	                  old_jj=oldposs/i2d;                    
                       }                                	
                       else if (range_type==3){
                          temp_ii=poss%i3d;
	                  temp_jj=poss%(i3d*j3d)/i3d;
                          temp_hh=poss/(i3d*j3d);
                          old_ii=oldposs%i3d;
	                  old_jj=oldposs%(i3d*j3d)/i3d;
                          old_hh=oldposs/(i3d*j3d);
                       }                                     
                       moveto(xbox,gety+CHeight);

                       if (oned){
			 unsigned int low_v,high_v;
                          if (block_all==0){
                             low_v=temp_ii;
                             sprintf(textb[0], 
                                "%dd block (0-%d), first(def %d):",
                                      range_type,lineL-1,low_v);
                             moveto(xbox,gety+CHeight);
                             outtext(textb[0]);
                             input_string(5,0);
                             if (is[0]=='q') goto quit_b;
                             else if (is[0]!=13 && atoi(is)>=0 && 
                               atoi(is)<=lineL-1) low_v=atoi(is);
                             high_v=old_ii;
                             sprintf(textb[0],"  second(def %d):",high_v);
                             outtext(textb[0]);
                             input_string(5,0);
                             if (is[0]=='q') goto quit_b;
                             else if (is[0]!=13 && atoi(is)>=0 && 
                                atoi(is)<=lineL-1) high_v=atoi(is);
                             if (low_v==high_v) goto quit_b;
                             else if (high_v<low_v){ //swap
			        temp_v=high_v;
                                high_v=low_v;
                                low_v=temp_v;
                             }
                          }
                          else if (block_all=='a'){
			     low_v=0;
                             high_v=lineL-1;
                          }
                          //for _ii for outside block to work
                          startposs=low_ii=low_v; 
                          endposs=high_ii=high_v;
                       } 
                       
                       else if (twod){
			 signed int i_temp[2],j_temp[2],ij_max[2];

			  ij_max[0]=i2d-1;
                          ij_max[1]=j2d-1;
                                     
                          ijh[0]=old_ii;
                          ijh[1]=old_jj;
                          ijh_def[0]=temp_ii;
                          ijh_def[1]=temp_jj;

                          if (block_all==0){
                             sprintf(textb[0],
	                      "%dd block (max=%d,%d)",range_type,i2d-1,j2d-1);
                             outtext(textb[0]);
                             for (zz=1;zz<=2;zz++){     
                                moveto(xbox,gety+CHeight);
                                if (zz==1) sprintf(textb[0],
				      "first corner (def %d,%d)",temp_ii,temp_jj);
                                else if (zz==2) sprintf(textb[0],
                                      "second corner (def %d,%d)",old_ii,old_jj);
                                outtext(textb[0]);
                                sprintf(textb[0],"%s"," I:");
                                sprintf(textb[1],"%s"," J:");
                             
                                for (z=0;z<=1;z++){
                                   outtext(textb[z]);
                                   input_string(4,0);
                                   if (is[0]=='q') goto quit_b;
                                   else if (is[0]!=13 && atoi(is)>=0 && 
                                      atoi(is)<=ij_max[z]) ijh_in[z]=atoi(is);
                                   else{
				      if (zz==1) ijh_in[z]=ijh_def[z];
				      else if (zz==2){
                                         if (z==0) ijh_in[z]=old_ii;
                                         else if (z==1) ijh_in[z]=old_jj;
				      }
                                   }
                                }
                                i_temp[zz-1]=ijh_in[0];
                                j_temp[zz-1]=ijh_in[1];   
			     }
                             if (i_temp[0]==i_temp[1] && j_temp[0]==j_temp[1]) goto quit_b; 
                             if (i_temp[1]<i_temp[0]){ /*swap i if necessary*/
			        temp_v=i_temp[1];
                                i_temp[1]=i_temp[0];
                                i_temp[0]=temp_v;
                             }
                             if (j_temp[1]<j_temp[0]){ /*swap j if necessary*/
			        temp_v=j_temp[1];
                                j_temp[1]=j_temp[0];
                                j_temp[0]=temp_v;
                             }
                             low_ii=i_temp[0];
                             low_jj=j_temp[0];                                         
                             startposs=i2d*low_jj + low_ii;

                             high_ii=i_temp[1];
                             high_jj=j_temp[1];                                         
                             endposs=i2d*high_jj + high_ii;
                             
                          }
                          else if (block_all=='a'){
                             low_ii=0;
                             low_jj=0;         
                             startposs=0;
                             high_ii=i2d-1;
                             high_jj=j2d-1;
                             endposs=lineL;
                          }
                       } 
                       else if (threed){
			 signed int i_temp[2],j_temp[2],h_temp[2],ijh_max[3];
			  ijh_max[0]=i3d-1;
                          ijh_max[1]=j3d-1;
                          ijh_max[2]=h3d-1;
                          
                          ijh[0]=old_ii;
                          ijh[1]=old_jj;
                          ijh[2]=old_hh;

                          ijh_def[0]=temp_ii;
                          ijh_def[1]=temp_jj;
                          ijh_def[2]=temp_hh;
                       
                          if (block_all==0){   
                             sprintf(textb[0],
	                      "%dd block (max=%d,%d,%d)",range_type,i3d-1,j3d-1,h3d-1);
                             outtext(textb[0]);
                             for (zz=1;zz<=2;zz++){     
                                moveto(xbox,gety+CHeight);
                                if (zz==1) sprintf(textb[0],
                                     "first corner (def %d,%d,%d)",
						   temp_ii,temp_jj,temp_hh);
                                else if (zz==2) sprintf(textb[0],
                                     "second corner (def %d,%d,%d)",
                                                   old_ii,old_jj,old_hh);

                                outtext(textb[0]);
                                sprintf(textb[0],"%s"," I:");
                                sprintf(textb[1],"%s"," J:");
                                sprintf(textb[2],"%s"," H:");
                             
                                for (z=0;z<=2;z++){
                                   outtext(textb[z]);
                                   input_string(4,0);
                                   if (is[0]=='q') goto quit_b;
                                   else if (is[0]!=13 && atoi(is)>=0 && 
				       //atoi(is)<=ijh[z]-1) ijh_in[z]=atoi(is);
                                       atoi(is)<=ijh_max[z]) ijh_in[z]=atoi(is);
                                   else{
                                      if (zz==1) ijh_in[z]=ijh_def[z];
                                      else if (zz==2){
                                         if (z==0) ijh_in[z]=old_ii;
                                         else if (z==1) ijh_in[z]=old_jj;
                                         else if (z==2) ijh_in[z]=old_hh;
                                      }
                                   }                                   
                                }
                                
                                i_temp[zz-1]=ijh_in[0];
                                j_temp[zz-1]=ijh_in[1];
                                h_temp[zz-1]=ijh_in[2];       
			     }
                             if (i_temp[0]==i_temp[1] 
                                 && j_temp[0]==j_temp[1] && h_temp[0]==h_temp[1]) goto quit_b;
 
                             if (i_temp[1]<i_temp[0]){ /*swap i if necessary*/
			        temp_v=i_temp[1];
                                i_temp[1]=i_temp[0];
                                i_temp[0]=temp_v;
                             }
                             if (j_temp[1]<j_temp[0]){ /*swap j if necessary*/
			        temp_v=j_temp[1];
                                j_temp[1]=j_temp[0];
                                j_temp[0]=temp_v;
                             }
                             if (h_temp[1]<h_temp[0]){ /*swap h if necessary*/
			        temp_v=h_temp[1];
                                h_temp[1]=h_temp[0];
                                h_temp[0]=temp_v;
                             }
                             low_ii=i_temp[0];
                             low_jj=j_temp[0];
                             low_hh=h_temp[0];
                             startposs=(i3d*j3d*low_hh) + (i3d*low_jj) + low_ii;

                             high_ii=i_temp[1];
                             high_jj=j_temp[1];
                             high_hh=h_temp[1];
                             endposs=(i3d*j3d*high_hh) + (i3d*high_jj) + high_ii;
                          }
                          else if (block_all=='a'){
                             low_ii=0;
                             low_jj=0;
                             low_hh=0;
                             startposs=0;
                             high_ii=i3d-1;
                             high_jj=j3d-1;
                             high_hh=h3d-1;
                             endposs=lineL-1; 
                          }
                       }                                             
                       block_set=1;                       
                       show_block=1;
                       suppress_links_block=3;
                       file_dim=0; /*cancel block after loading 1d
				     or converted to 1d if file did not fit*/
                      quit_b:
                       free(ijh);
                       free(ijh_in);
                       free(ijh_def);
                       is[0]=0;       
		       break;
                     }                   
	     case'k':  /*revise k for single cell or 1d, 2d or 3d block*/
	               if (basin_not_complete==1
                            || tot_only==1) break;/*not while basin interupted*/
                       if (showrules==1 && rulemix==0) break;
                       reset_k(showrules,block_set,show_block,
                                           poss,startposs,endposs);
                       was_changed=1;
                       is[0]=0;
		       break;
             case'K': { /*kill: cut all input and/or output links to cell, make rule neutral*/
		       if (showrules==1 && rulemix==0) break;
                       if (nonlocal==0 || showrules==0) break;
                       if (show_block==1){
                          for (zzu=startposs;zzu<=endposs;zzu++){
                              if (file_dim==1){ /*block after loading file 1d or conv 1d*/
			         if (zzu>endposs || zzu<startposs) continue;
                              }
                              else if (outside_2d_3d_block(zzu,
                                 low_ii,low_jj,low_hh,
                                    high_ii,high_jj,high_hh)==1) continue;
                              cut_in_out_links(zzu);
                          }
                       } 
                       else cut_in_out_links(poss);
                       was_changed=1;
                       is[0]=0;
		       break; 
		}
	        case'h': /*rewire single cell by hand*/
                       if (basin_not_complete==1) break;/*not while basin interupted*/
                       rewire_single_cell(poss);                       
                       was_changed=1;
                       is[0]=0;
		       break;

                case'r': /*random wiring for single cell 
                               or 1d, 2d or 3d block*/
                       if (basin_not_complete==1) break;/*not while basin interupted*/
                       if (block_set==0 || show_block==0) 
                                   randomly_wire_cell(poss,lineL-1);
                       
                       else{
                          for (zzu=startposs;zzu<=endposs;zzu++){
                             if (file_dim==1){/*block after loading file 1d or conv 1d*/
			         if (zzu>endposs || zzu<startposs) continue;
                             }
                             else if (outside_2d_3d_block(zzu,
                                 low_ii,low_jj,low_hh,
                                 high_ii,high_jj,high_hh)==1) continue;
		             randomly_wire_cell(zzu,lineL-1);
			  }
                       }
                       cell_out_freq();
                       was_changed=1;   		      	       
		       break;
                case'w': /*random wiring outside block*/
                       if (basin_not_complete==1) break;/*not while basin interupted*/
                       if (show_block==1 || (block_set==1 && oned_as_twod) ){
			  for (zzu=0;zzu<=lineL-1;zzu++){
                             if (file_dim==1){ /*block after loading file 1d or conv 1d*/
			        if (zzu>endposs || zzu<startposs)
                                      randomly_wire_cell(zzu,lineL-1);
                             }
                             else if (outside_2d_3d_block(zzu,
                                 low_ii,low_jj,low_hh,
                                 high_ii,high_jj,high_hh)==1) 
                                        randomly_wire_cell(zzu,lineL-1);
			     else continue;
		           }
                           cell_out_freq();
                           was_changed=1;
		       }
                       break;
                case'R':{ /*random wiring for single cell 
                               or 1d, 2d or 3d block, biased by k distribution*/
                       unsigned long tot_wires=0;
                       unsigned int zub;
                       if (basin_not_complete==1) break;/*not while basin interupted*/
                       for (zub=0;zub<=lineL-1;zub++) tot_wires+=nhoodm[zub];

                       if (block_set==0 || show_block==0) 
                               randomly_wire_cell_Kbias(tot_wires,poss,lineL-1);
                       else {
                          for (zzu=startposs;zzu<=endposs;zzu++){
                             if (file_dim==1){/*block after loading file 1d or conv 1d*/
			         if (zzu>endposs || zzu<startposs) continue;
                             }
                             else if (outside_2d_3d_block(zzu,
                                 low_ii,low_jj,low_hh,
                                 high_ii,high_jj,high_hh)==1) continue;
		             randomly_wire_cell_Kbias(tot_wires,zzu,lineL-1);
			  }
                       }
                       cell_out_freq();
                       was_changed=1;   		      	       
		       break;
	       }
	       case's': /*bias wiring for single cell or 
                               1d, 2d or 3d block*/
                       if (basin_not_complete==1) break;/*not while basin interupted*/
                       zonesize=set_max_zonesize();
                       bias_random_wiring();
                       is[0]=0;        
		       break;
		    
	       case'1': /*1d wiring for single cell or 1d, 2d or 3d block*/
                       if (basin_not_complete==1) break;/*not while basin interupted*/  
                       if (block_set==0 || show_block==0) 
                                  oneD_local_wire_cell(poss,lineL-1);
                       else{
                          for (zzu=startposs;zzu<=endposs;zzu++){
                             if (file_dim==1){/*block after loading file 1d or conv 1d*/
			         if (zzu>endposs || zzu<startposs) continue;
                             }
                             else if (outside_2d_3d_block(zzu,
                                 low_ii,low_jj,low_hh,
                                 high_ii,high_jj,high_hh)==1) continue;
		             oneD_local_wire_cell(zzu,lineL-1);
                          }
                       }		      
                       cell_out_freq();
                       was_changed=1;
		       break;
	       case'2':/*2d wiring for single cell or 1d, 2d or 3d block*/ 
                       if (basin_not_complete==1) break;/*not while basin interupted*/
                       if (block_set==0 || show_block==0) 
                                   wire_2d_local(poss,wiring[poss]);
                       else{
                          for (zzu=startposs;zzu<=endposs;zzu++){
                             if (file_dim==1){/*block after loading file 1d or conv 1d*/
			         if (zzu>endposs || zzu<startposs) continue;
                             }
                             else if (outside_2d_3d_block(zzu,
                                 low_ii,low_jj,low_hh,
                                 high_ii,high_jj,high_hh)==1) continue;
                             wire_2d_local(zzu,wiring[zzu]);
                          }
                       }
                       cell_out_freq();
                       was_changed=1;                  
		       break;
                case'3': /*3d wiring for single cell or 1d, 2d or 3d block*/
                       if (basin_not_complete==1) break;/*not while basin interupted*/
		       if (threed==0) break;
                       if (block_set==0 && show_block==0) 
                                    wire_3d_local(poss,wiring[poss]);
                       else{
		          for (zzu=startposs;zzu<=endposs;zzu++){     
                             if (file_dim==1){ /*block after loading file 1d or conv 1d*/
			         if (zzu>endposs || zzu<startposs) continue;
                             }
                             else if (outside_2d_3d_block(zzu,
                                 low_ii,low_jj,low_hh,
                                 high_ii,high_jj,high_hh)==1) continue;
                             wire_3d_local(zzu,wiring[zzu]);
                          }
                       }
                       cell_out_freq();
                       was_changed=1;
		       break;

              case 'x': if (twod){  /*tog square/hex lattice*/          
		          hex2d=abs(hex2d-1);
                          if (hex2d==1  && cscale>=1){ 
                              regular2d_tgrid=1;
                              Y1=bottom-(j2d+1)
				*(signed int)ceil((cscale*cos(PI/6)));/*for hex grid*/
                          }
			  else{
                              regular2d_tgrid=0;
                              Y1=bottom-(j2d+1)*cscale;
                          }
                          scale_changed=1;
                          /*no need - can be done in special-s*/ 
                          /*wireup_2d_nhood(i2d-1,j2d-1,0,0);*/
                       }
	               else if (threed){ /*redraw and toggle 3d grid, was 'T'*/
                          draw_3d_grid=abs(draw_3d_grid-1);
                          bottom=this_bottom=start_bottom;
                          scale_changed=1;
                       }                       
		       break;   		 
	      case LeftArrow:             
		       ii+=1;              
		       if (ii>i2d-1) ii=0;            
		       break;                                          
	      case RightArrow:            
		       ii-=1;              
		       if (ii<0) ii=i2d-1; 
		       break;                                          
	      case UpArrow:              
		       jj+=1;              
		       if (jj>j2d-1) jj=0; 
		       break;                                         
	      case DownArrow:             
		       jj-=1;              
		       if (jj<0) jj=j2d-1; 
		       break;              
              case '[':  /*3d: up h-axis*/
		       if (threed){
                        unsigned int temp_poss;           
                          i3=poss%i3d;
	                  j3=poss%(i3d*j3d)/i3d;
                          h3=poss/(i3d*j3d);
                          h3+=1;
                          if (h3>h3d-1) h3=0;
                          temp_poss=(i3d*j3d*h3) + (i3d*j3) + i3;
                          ii=temp_poss%i2d;
	                  jj=temp_poss/i2d; 
                       }
		       break;              
	      case ']':  /*3d: down h-axis*/
		       if (threed){
                        unsigned int temp_poss;           
                          i3=poss%i3d;
	                  j3=poss%(i3d*j3d)/i3d;
                          h3=poss/(i3d*j3d);
                          h3-=1;
                          if (h3<0) h3=h3d-1;
                          temp_poss=(i3d*j3d*h3) + (i3d*j3) + i3;
                          ii=temp_poss%i2d;
	                  jj=temp_poss/i2d; 
                       }
		       break;                                  
	       case'j': { 
                      signed int *ij;
                       erase_prompt_box(6);
                       if ((ij=(signed int *)calloc(2,sizeof(signed int)))
				   ==NULL) outof_memory("ij");
                       jump2d_3d(ij);
                       ii=ij[0];
                       jj=ij[1];
                       free(ij);
                       is[0]=0;
                       break;
               }                                           	  
              case 'p':
			 direct_wire=abs(direct_wire-1);
                         break;
              case 'i':
			 show_pindex=abs(show_pindex-1);
                         break; 
              case 'n':  /* tog through the following displays
                 0----->----0   0     cell-    link-     connected cell
                 0----->----*   1     cell-    link-  no connected cell
                 0-        -0   2     cell- no link-     connected cell
                 0-        -*   3     cell- no link - no connected cell
                 0-        -*   4  no cell-    link - no connected cell*/
		if (show_block==1){ /*presentation for block*/
                         if (suppress_links_block==0) suppress_links_block=1;
                         else if (suppress_links_block==1) suppress_links_block=2;
                         else if (suppress_links_block==2) suppress_links_block=3;
                         else if (suppress_links_block==3) suppress_links_block=4;
                         else if (suppress_links_block==4) suppress_links_block=0;
                }
                else{    /*presentation for cell*/
                         if (suppress_links==0) suppress_links=1;
                         else if (suppress_links==1) suppress_links=2;
                         else if (suppress_links==2) suppress_links=3;
                         else if (suppress_links==3) suppress_links=4;
                         else if (suppress_links==4) suppress_links=0;
                }
                         break;
              case 'e':  
                         /*expand 2d*, also 1d as 2d*/
                         scale_changed=1;
                         if (threed){ //delete 3d frame
                            setfillstyle(SOLID_FILL,black);
                            bar(sboxx,sboxy,
                            sboxx+i3d*fscale+j3d*sin(PI/4)*fscale,
                            sboxy+h3d*fscale+j3d*sin(PI/4)*fscale+1);
                         }
                         if (cscale>=1) cscale+=1;
                         else{
                            cscale/=.9; /*expand from < 1*/
                            if (cscale>=1 && cscale<2) cscale=1;
                         }
                         break;
              case 'E':  
                         if (fscale<127){ /*max char*/
                            scale_changed=1;   /*expand 3d*/  
                            if (threed){ //delete 3d frame
                                  setfillstyle(SOLID_FILL,black);
                                  bar(sboxx,sboxy,
                                  sboxx+i3d*fscale+j3d*sin(PI/4)*fscale,
                                  sboxy+h3d*fscale+j3d*sin(PI/4)*fscale+1);
			     }
                             if (fscale>=1) fscale+=1;
                             else{
                                fscale/=.9; /*expand from < 1*/
                                if (fscale>=1 && fscale<2) fscale=1;
                             }                            
			 }
                         break;
              case 'c':
                         /*limit 2d as 3d contraction, also 1d as 2d*/ 
                         if (j2d*cscale<vgay(10)) break;
                         if (cscale>1) cscale-=1;  /*contract 2d*/
                         else  cscale*=.9;
                         scale_changed=1;
                         if (threed){  //delete 3d frame
                            setfillstyle(SOLID_FILL,black);
                            bar(sboxx,sboxy,
                                 sboxx+i3d*fscale+j3d*sin(PI/4)*fscale,
                                    sboxy+h3d*fscale+j3d*sin(PI/4)*fscale+1);
			 }                       			 
                         break;
              case 'C':  
		         //if (fscale<=.01) break; 
                         /*limit 3d contraction*/
                         if (h3d*fscale+j3d*sin(PI/4)*fscale<vgay(10)) break;
                         scale_changed=1;
                         if (threed){  //delete 3d framec
                            setfillstyle(SOLID_FILL,black);
                            bar(sboxx,sboxy,
                               sboxx+i3d*fscale+j3d*sin(PI/4)*fscale+1,
                                    sboxy+h3d*fscale+j3d*sin(PI/4)*fscale+1);
			 }
                         if (fscale>1) fscale-=1;   /*contract 3d*/
                         else fscale*=.9;   /*continue contracting 3d*/
                         break;
              case 'd':{  /*start lower*/
                         this_bottom=bottom+((float)Maxy)/5;
                         /*undo if net fits*/
                         if (top>=vgay(50)){
                             this_bottom=bottom-((float)Maxy)/5;
                             break;
                         }
                         v_changed=1;
                         scale_changed=1;                              
                         break;
	              }
              case 'u':  /*start higher*/
                         this_bottom=bottom-((float)Maxy)/5;
                         /*dont raise higher than necessary*/
                         if (this_bottom<start_bottom){
                            this_bottom=start_bottom;
                         }
                         v_changed=1;
                         scale_changed=1;  
                         break;
              case 'T':  /*to toggle between no-gap and gap between cells, 
                         makes simple grid for block
                         applies to 2d, and 3d and 2d view of 3d*/ 
                         csep_zero_force=abs(csep_zero_force-1);
                         bottom=this_bottom=start_bottom;
                         scale_changed=1;                           
                         break;
              case '!':  /*exclamation mark: to toggle 2d gridcolor white-grey
                         applies to 2d, 1d in 2d and 2d version of 3d*/
                            gridcolor2d=abs(gridcolor2d-1);
                            bottom=this_bottom=start_bottom;
                            scale_changed=1;       
                         break;
              case 'W':  /*toggle filled block cells (red), and white
                         applies to 2d, and 3d and 2d view of 3d*/ 
                         fill_block_cells=abs(fill_block_cells-1);
                         bottom=this_bottom=start_bottom;
                         scale_changed=1;                         
                         break;
              case 'P':  /*to redraw the whole thing exactly as is 
                             and save vector PostScript*/
                         //bottom=this_bottom=start_bottom; 
                         //up/down is now ok for wiring_postscript, but prints below base panel
                         scale_changed=1;  
                         erase_prompt_box(6);
                         draw_prompt_box(1);
                         outtext("save wiring graphic to PostScript: greyscale-P color-p:"); 
                         input_string(1,0);
                         if (is[0]=='p'|| is[0]=='P'){
                           char temp_is;
			    temp_is=is[0];
                            if (is[0]=='p') wiring_postscript=1;
                            else if (is[0]=='P') wiring_postscript=2;
                            file_ret_w=select_filename("SAVE","PostScript file","*.ps","my_wgPS");
                            if (file_ret_w=='q'){
			       wiring_postscript=0;
                               break;
                            }
	                    memmove(filename_wiring_PS,filename,13);
                            /*delete previous*/
                            fid_PS=myopen(filename_wiring_PS,1,0);
                            vret=write(fid_PS, "",0);
                            close(fid_PS);
                            /*start new*/
                            fid_PS=myopen(filename_wiring_PS,1,1);
                            if (fid_PS==-1){ 
                                  file_error(filename_wiring_PS);
                                  close(fid_PS); 
                                  wiring_postscript=0;
                                  break;  
                            }
                            psize_ps=pointsize;
                            prepare_basinPS(2,2); /*write/define postScipt for wiring*/
                            is[0]=temp_is;                               
			 }    
                         break;
        
	     }/*end switch(is[0]){*/
	    }/*if (test_key==1){*/

            if (is[0]=='q' || is[0]==13) break;

            /*preserve active cell position*/
            if (twod) poss=i2d*jj + ii;
            else if (threed) poss=(i3d*j3d*h3) + (i3d*j3) + i3;

            /*show REVISED top right prompts (or in case covered)*/
            if (show_prompt==1) draw_2d_3d_graphics_prompt(startposs,endposs,poss,
		     showrules, block_set,suppress_links,suppress_links_block);

            if (sculpt_basin==1 && learn_sometime==0);/*do nothing*/
            else if (was_changed==1){	 
                nonlocal=1;
		regular3d=regular2d=regular2d_tgrid=
                       compress_1d_local=dontcompress=0;
            }
	    if (scale_changed==1) break;
	} //while(1){

        erase_memory_box(2);        

        sprintf(textb[9],"%s","boximage[7]");/*/*refresh 2d box*/
	putimage(left-vgax(40),topbox,boximage[7],COPY_PUT,textb[9]);
       
        sprintf(textb[9],"%s","boximage[3]"); /*refresh data box*/
	putimage(left-vgax(40)+2,start_bottom+vgay(40)-vgay(17),
				       boximage[3],COPY_PUT,textb[9]);
        
	freeimage(boximage[7]); /*2d box 1*/
	freeimage(boximage[6]); /*2d box 2*/
        if (scale_changed==1 || v_changed==1) goto start;
        
        setviewport(0,0,Maxx,Maxy,0);
        uncover_free_prompt_box(3); /*from get_prompt_box(3,6);*/

        sprintf(textb[9],"%s","boximage[3]"); /*uncover area below data box*/
	putimage(left-vgax(40)+2,start_bottom+vgay(40)-vgay(17),
				       boximage[3],COPY_PUT,textb[9]);
        freeimage(boximage[3]); /*data box*/
       
        if (threed){
            freeimage(boximage[17]); /*3d area*/
            sprintf(textb[9],"%s","boximage[20]"); /*restore previous active screen*/
	    putimage(0,0,boximage[20],COPY_PUT,textb[9]);
            freeimage(boximage[20]); /*active screen*/
        }
        
        i2d=tempi;
        j2d=tempj;
        was_changed=1; /*if network graphic was visited, assume
                         net was changed, dont mutate next time*/
        inside_wiring_graphic=0; /*need this to show rules in xterm with 'x' */
        if (twod){	  
           if (hex2d==1  && cscale>=1) regular2d_tgrid=1; /*2d hex layout*/
        }
        fid_PS=fid_temp_PS;
        basin_postScript=temp_basin_postScript;
#       if __WATCOM__
	   mouse_call(7,0,0,getmaxx()); //horizontal limits - release mouse
           mouse_call(8,0,0,getmaxy()); //vertical limits
#       endif  
}
/********** graphics prompt for 2d, 3d made function  Aug 1999  *********/
void draw_2d_3d_graphics_prompt(unsigned int startposs,
                                unsigned int endposs,
			        unsigned int poss,
                                char showrules, char block_set,
                                char suppress_links,char suppress_links_block){

  signed int xbox,low_ii,low_jj,low_hh,high_ii,high_jj,high_hh;
  char thisdim;
  unsigned char tempcolor;

        tempcolor=getcolor();
        setcolor(white);

        if (twod){
           thisdim=2;           
           if (hex2d==1) sprintf(textb[1],"%dx%d hex",i2d,j2d);
           else sprintf(textb[1],"%dx%d",i2d,j2d);
        }
         else if (threed){
            thisdim=3;
            sprintf(textb[1],"%dx%dx%d",i3d,j3d,h3d);
        }
        else if (oned){ 
            thisdim=1;
            sprintf(textb[1],"%d, 2d=%dx%d",poss,i2d,j2d); /*show 2d co-ords*/
        }
        xbox=draw_prompt_box(6);
        if (showrules){
           if (threed) sprintf(textb[0],
         "%dd (%s) wiring/rules: move-arrows, levels up/down-[/] jump-j/mouse-click",
                                                     thisdim,textb[1]);
	   else sprintf(textb[0],
               "%dd (%s) wiring/rules: move-arrows jump-j/mouse-click",
                                                     thisdim,textb[1]);
        }
        else{
           if (threed) sprintf(textb[0],
         "%dd (%s) wiring only: move-arrows, levels up/down-[/] jump-j/mouse-click",
                                                     thisdim,textb[1]);
	   else sprintf(textb[0],
                "%dd (%s) wiring only: move-arrows jump-j/mouse-click",
                                       thisdim,textb[1]);
        }
        outtext(textb[0]);
	moveto(xbox,gety+CHeight);
        if (threed) 
                outtext("exp/contr-e/c/E/C up/down-u/d tog:gaps-T gridcolor-! fill-W grid3d-x, PScript-P");
	else if (twod || oned) 
             outtext("exp/contr-e/c up/down-u/d tog:gaps-T gridcolor-! fill-W hex-x, PScript-P");
        //else outtext("exp/contr-e/c up/down-u/d redraw-T PScript-P");
	moveto(xbox,gety+CHeight);

        if (block_set) sprintf(textb[0],
	   "block-b tog:block-a edges-G block-links(%d)-n pseudo-p index-i ",
                                    suppress_links_block+1);
	else sprintf(textb[0],
           "block-b tog:all-a cell-links(%d)-n pseudo-p index-i ",
                                    suppress_links+1);
	outtext(textb[0]);
   
        if (basin_not_complete==1){ /*not while basin interupted*/
           if (tot_only==0){
              if (rulemix && showrules==1) outtext("avZ-z");
           }
        }
        else{
           if (tot_only==0 && showrules==1){
              setcolor(lightred);
	      if (direction=='f' && limitcheck==0) sprintf(textb[1]," learn-L");
              else sprintf(textb[1]," hilght/lrn-l/L");
              if (rulemix && showrules==1) 
                       sprintf(textb[0],"avZ-z%s",textb[1]);
	      else if (showrules==1) 
                       sprintf(textb[0],"%s",textb[1]);
              outtext(textb[0]);
              setcolor(white);
           }
        }
       

	moveto(xbox,gety+CHeight);       
        if (basin_not_complete==1) sprintf(textb[0],"");
        else{ 
           if (threed){
                    if (block_set){ 
		        low_ii=startposs%i3d;
	                low_jj=startposs%(i3d*j3d)/i3d;
                        low_hh=startposs/(i3d*j3d);
                        high_ii=endposs%i3d;
	                high_jj=endposs%(i3d*j3d)/i3d;
                        high_hh=endposs/(i3d*j3d);
                        sprintf(textb[0],
                          "rewire 3d block %d,%d,%d-%d,%d,%d:",
                            low_ii,low_jj,low_hh,high_ii,high_jj,high_hh);
		     }
                     else{
		        low_ii=poss%i3d;
	                low_jj=poss%(i3d*j3d)/i3d;
                        low_hh=poss/(i3d*j3d);
                        sprintf(textb[0],
                            "rewire 3d cell %d,%d,%d:",
                                          low_ii,low_jj,low_hh);
                     }
		  }
           else if (twod){ 
                     if (block_set){ 
		        low_ii=startposs%i2d;
	                low_jj=startposs/i2d;
                        high_ii=endposs%i2d;
	                high_jj=endposs/i2d;
                        sprintf(textb[0],
                             "rewire 2d block %d,%d-%d,%d:",
                                     low_ii,low_jj,high_ii,high_jj);
		      }
                      else{
			  low_ii=poss%i2d;
			  low_jj=poss/i2d;
                         sprintf(textb[0],
                           "rewire 2d cell %d,%d:",low_ii,low_jj);
                      }
	          }
           else if (oned){ 
                      if (block_set){ 
                         sprintf(textb[0],
                           "rewire 1d block %d-%d:",startposs,endposs);
                       }
                       else sprintf(textb[0],"rewire 1d cell %d: ",poss);
           }
        }
        outtext(textb[0]);

        if (basin_not_complete==1);/*not while basin interupted*/
        else{
           if (threed) outtext(
               " hand-h rnd-r/w/R special-s local:1d-1 2d-2 3d-3");
           else outtext(" hand-h rnd-r/w/R special-s local:1d-1 2d-2");
        }

        moveto(xbox,gety+CHeight);     
	if (showrules==1 && rulemix==0); /*do nothing*/
        /*else if (tot_only==1);*/ /*do nothing*/
        else if (basin_not_complete==0){ /*not while basin interupted*/
	   outtext("graph-g ");
           setcolor(green);
	   if (tot_only==0){ 
              sprintf(textb[0],"change k=%d(max %d)-k ",nhoodm[poss],nhood);
              outtext(textb[0]);
           }
           if (nonlocal==1 && showrules==1) outtext("kill-K ");
           setcolor(white); 
	}
        if (showrules){ 
	   outtext("graph-g ");
           setcolor(lightred);
           if (basin_not_complete==1) outtext("rule: Save-S Derrida-D");
           else{
              if (tot_only==0) outtext("rule: Save/rev/trans-S/v/t Derrida-D");
	      else outtext("rule: Save/rev-S/v Derrida-D");
           }
           setcolor(white);
        }
        moveto(xbox,gety+CHeight);
        outtext("file/data-f ");
        outtext("hist:In(k)/Out/Both-I/O/B reset-q cont-ret");
        setcolor(tempcolor);
}
/*************** draw hexagonal 2d cell Jan 2004  **************/
void draw_hexagonal_2d_cell_wiring(double this_hex_rad,
       float this_cscale,
          char this_show_2d_divs,char this_dots, unsigned char thiscolor,
                unsigned char outcolor,
                           signed int x1,signed int y1){
  
         if (this_cscale<=1){
            if (wiring_postscript){
	       color_ps(wiring_postscript-1,thiscolor);               
               smallspot_ps(x1,y1,1);
            } 
            putpixel(x1,y1,thiscolor);
	    return;
	 }
         
         poly[0]=(signed int)(x1+this_cscale/2);
         poly[1]=(signed int)y1;

         poly[2]=(signed int)(x1+this_cscale);
         poly[3]=(signed int)(y1+ceil(this_hex_rad/2));

	 poly[4]=(signed int)(x1+this_cscale);
	 poly[5]=(signed int)(y1+(this_hex_rad*3)/2);

         poly[6]=(signed int)(x1+this_cscale/2);
         poly[7]=(signed int)(y1+ceil(this_hex_rad*2));

         poly[8]=(signed int)x1;
         poly[9]=(signed int)(y1+(this_hex_rad*3)/2);

         poly[10]=(signed int)x1;
	 poly[11]=(signed int)(y1+ceil(this_hex_rad/2));
         

         /*draw the filled poly*/
         fillpoly(6, poly);
         
         /*if ((this_cscale>3 && this_show_2d_divs==1) ||
	   this_show_2d_divs==2){*/ /*2 forces the edge line*/
	     /*setcolor(black);*/
            if (wiring_postscript){
	       color_ps(wiring_postscript-1,fillcolor);
               hex_fill_ps();
               color_ps(wiring_postscript-1,outcolor);
               hex_outline_ps();
            }
	    setcolor(outcolor);
	    line(poly[0],poly[1],poly[2],poly[3]);
	    line(poly[2],poly[3],poly[4],poly[5]);
            line(poly[4],poly[5],poly[6],poly[7]);
            line(poly[6],poly[7],poly[8],poly[9]);
	    line(poly[8],poly[9],poly[10],poly[11]);
            line(poly[10],poly[11],poly[0],poly[1]);
	  /*}*/
          /*put a dot on zero cell*/
          /*if (this_dots==1 &&  this_cscale>=4 &&
	      (thiscolor==black || thiscolor==darkgray))
	      putpixel(x1+this_cscale/2,y1+this_hex_rad,green);*/
}


/************** check if outside 2d or 3d block Aug 1999  **************/
void draw_2d_3d_links(unsigned int poss,
       float right, float start_bottom, float bottom,
       float cscale, float csep, float fscale,char direct_wire, 
       char show_pindex, char this_suppress_links, char outcolor, char block_set){

 float temp_cscale,hcscale,cellx,celly,addhex=0,addhex1,addhex2;
 unsigned int n;
 signed int wire;
 float ccel_x,ccel_y,wire_x,wire_y,nhood_x,nhood_y;
 signed int /*ccel_x,ccel_y,*/
     iz,jz,tempx,tempy,
     temp_ii,
     /* wire_x,wire_y,*/    /*wire to plot positions*/
     /*nhood_x,nhood_y,*/  /*pseudo nhood plot positions*/
     iz3,jz3,hz3, /*for 3d wiring*/
     ii,jj,i3,j3,h3;
 char ccel,tempcolor,gridcolor;
 double hex_vmove,hex_rad;

            setviewport(2,0,Maxx,vgax(390)+vgax(18),1);      
            /* normal CHeight=15*/
            if (cscale>=15*1.4); 
            else{
               if (wiring_postscript) resetfont_ps("Times-Roman", psize_ps);
               set_small_font();
	    }

            /*convert to 2d co-ords*/
            ii=poss%i2d;
	    jj=poss/i2d;
	    
	    if (twod && hex2d==1 && cscale>=1 && (j2d-jj)%2==0) /*hex layout*/
                                        addhex=cscale/2;
            if (hex2d==1 && cscale>=1){
		hcscale=cscale+1;
                hex_rad=(double)(hcscale-csep) * cos(PI/6)*2/3;
                hex_vmove=(signed int)(ceil(cscale*cos(PI/6)));      
            }
	    else hex_vmove=cscale;
            if (twod && hex2d==1 && cscale>=1 && (j2d-jj)%2==0) /*hex layout*/
                                        addhex=cscale/2;

	    cellx=right-(ii+1)*cscale;
            celly=bottom-(jj+1)*hex_vmove;
            moveto(cellx,celly);
            /*fprintf(stderr,"\ntwod=%d hex2d=%d %d-%d=%d :%d %.1f",
	      twod,hex2d,j2d,jj,j2d-jj, (j2d-jj)%2,cellx);*/

            if (threed){
                 /*convert to 3d co-ords*/
                 i3=poss%i3d;
	         j3=poss%(i3d*j3d)/i3d;
                 h3=poss/(i3d*j3d);
                 /*define central 3d cell location*/
                 ccel_x=
                    right+vgax(38)+i3d*fscale+j3d*sin(PI/4)*fscale
                    -i3*fscale-j3*sin(PI/4)*fscale-fscale;
                 ccel_y= start_bottom-j3d*sin(PI/4)*fscale
                         -h3*fscale+j3*sin(PI/4)*fscale;
            }
            
            if (direct_wire==1){ 
	       if (this_suppress_links==4 && (twod || threed)); /*dont do*/
	       else{
		  if (fill_block_cells==0 || cscale<=4) //leave empty
                         block_fill_color=black; //works for both white and black background
		  else block_fill_color=red; //togged if fill_2d_block_cells==1
                  
		  setfillstyle(SOLID_FILL, block_fill_color); //fill with red or background color
                  setcolor(outcolor);
                  if (gridcolor2d==0){ //toggle with ! (exclamation)
		    if (bground=='w') gridcolor=lightgray; //change 2d grid color, black-lightgray
                    else if (bground=='b') gridcolor=darkgray; //change 2d grid color, white-darkgray
                  }
                  else gridcolor=white;
                  if (hex2d==1 && cscale>=1){
                       
                      draw_hexagonal_2d_cell_wiring(hex_rad,
			   hcscale-csep,2,0,block_fill_color,
			   gridcolor,//outcolor,//lightgray,                           
			   cellx+addhex,celly-hex_rad/4); 
		      }
                  else{
                      if (wiring_postscript){
                         color_ps(wiring_postscript-1,block_fill_color);
                         rect_fill_ps(cellx+addhex,celly,
				      abs((cellx+addhex)-(cellx+cscale-csep+addhex)),
				      abs(celly-(celly+cscale-csep)));
                         color_ps(wiring_postscript-1,gridcolor);
                         rect_outline_ps(cellx+addhex,celly,
				      abs((cellx+addhex)-(cellx+cscale-csep+addhex)),
				      abs(celly-(celly+cscale-csep)));
                      }
                      setcolor(gridcolor);
                      bar3d(cellx+addhex,celly,
                                cellx+cscale-csep+addhex,
				      celly+cscale-csep,0,1);
                      setcolor(outcolor);
                  }
                  if (threed){
		     if (fscale<=1){
                        if (wiring_postscript){
                           color_ps(wiring_postscript-1,red);
                           smallspot_ps(ccel_x,ccel_y,1);
                        } 
                        putpixel(ccel_x,ccel_y,red);
                     }
		     else{
		        pieslice(1,ccel_x,ccel_y,0,360,fscale/2);

                        if (wiring_postscript){ /*empty circles in postscript*/
                           color_ps(wiring_postscript-1,fillcolor);
                           circle_fill_ps(ccel_x,ccel_y,fscale/2);/*filled circle*/
                           color_ps(wiring_postscript-1,getcolor());
                           circle_ps(ccel_x,ccel_y,fscale/2);/*outline*/
                        }
	             }
                  }
                  if (this_suppress_links==3) goto end_links;
	       }
            }
            for (wire=nhoodm[poss]-1;wire>=0;wire--){
	            addhex1=addhex2=0;
                    /*specify psuedo-nhood position*/ 
	            if (oned){ /*for 1d shown as 2d*/
                       /*for nhood=9 lineL=3 to work*/
                       if (lineL-1<nhoodm[poss]/2){ 
	                  temp_ii=lineL+poss-(nhoodm[poss]/2)+wire;
	                  if (temp_ii<0) temp_ii+=lineL;
	                  n=abs(temp_ii)%lineL;
                       }
                       else n=(lineL+poss-(nhoodm[poss]/2)+wire)%(lineL);
                       /*convert to 2d co-odrds*/
                       i_n=n%i2d;
	               j_n=n/i2d;     
                    }
                    if (twod) /* i_n, j_n computed here */
                        ccel=pndood_2or3(2,poss,wire); 
                    else if (threed){
                       ccel=pndood_2or3(3,poss,wire);
		       /*wired to co-ords*/                     
                       iz3=wiring[poss][wire]%i3d;
	               jz3=wiring[poss][wire]%(i3d*j3d)/i3d;
                       hz3=wiring[poss][wire]/(i3d*j3d);
                       /*wired to plot positions*/ 
                       wire_x=
                        right+vgax(38)+i3d*fscale+j3d*sin(PI/4)*fscale
                                 -iz3*fscale-jz3*sin(PI/4)*fscale-fscale;
                       wire_y=start_bottom-j3d*sin(PI/4)*fscale
                                 -hz3*fscale+jz3*sin(PI/4)*fscale;
                       /*pseudo nhood plot positions*/
                       nhood_x= 
                        right+vgax(38)+i3d*fscale+j3d*sin(PI/4)*fscale
                          -i_n*fscale-j_n*sin(PI/4)*fscale-fscale;
                       nhood_y=start_bottom-j3d*sin(PI/4)*fscale
                               -h_n*fscale+j_n*sin(PI/4)*fscale;

                       if (direct_wire==0) moveto(nhood_x,nhood_y);
                       else moveto(ccel_x,ccel_y);
                    
                       if (this_suppress_links<4){
                          if (direct_wire==0 || ccel==1){
                             if (ccel==1) setfillstyle(SOLID_FILL,red);
		             else{
                                if (bground=='w') setfillstyle(SOLID_FILL,blue);
                                if (bground=='b') setfillstyle(SOLID_FILL,yellow);
                             }
                             if (fscale>=5) setcolor(outcolor);
                             else setcolor(fillcolor);                          
                             if (fscale<=1){
                                 if (wiring_postscript){
                                    color_ps(wiring_postscript-1,fillcolor);
                                    smallspot_ps(getx,gety,1);
                                 } 
                                 putpixel(getx,gety,fillcolor);

                             }
			     else{                             
                                 if (wiring_postscript){ /*empty circles in postscript*/
                                    color_ps(wiring_postscript-1,fillcolor);
                                    circle_fill_ps(getx,gety,fscale/2);/*filled circle*/
                                    color_ps(wiring_postscript-1,getcolor());
                                    circle_ps(getx,gety,fscale/2);/*outline*/
                                 }
                                 pieslice(1,getx,gety,0,360,fscale/2);
                             }
                          }
                       }
		       /*show couplings from 3-d pnhood if not same*/
                       if (direct_wire==1 || wiring[poss][wire]!=poss_n){
			   if (block_set) tempcolor=red;
                           else tempcolor=white;
                           setcolor(tempcolor);  
                           if (this_suppress_links==0 || 
                             this_suppress_links==1 || this_suppress_links==4){
                               if (wiring_postscript){
                                  color_ps(wiring_postscript-1,tempcolor);
                                  line_ps(getx,gety,wire_x,wire_y);
                               }
                               lineto(wire_x,wire_y);
                           }
                           else moveto(wire_x,wire_y);
                           if (this_suppress_links==0 || this_suppress_links==2){
                              if (fscale>=5) tempcolor=outcolor; 
                              else tempcolor=fillcolor;
                              setcolor(tempcolor);
		              setfillstyle(SOLID_FILL,green);
                              if (fscale<=1){
                                 if (wiring_postscript){
                                    color_ps(wiring_postscript-1,fillcolor);
                                    smallspot_ps(getx,gety,1);
                                 } 
                                 putpixel(getx,gety,fillcolor);

                              }
                              else{
                                 if (wiring_postscript){ /*empty circles in postscript*/
                                    color_ps(wiring_postscript-1,fillcolor);
                                    circle_fill_ps(getx,gety,fscale/2);/*filled circle*/
                                    color_ps(wiring_postscript-1,getcolor());
                                    circle_ps(getx,gety,fscale/2);/*outline*/
                                 }  
                                 pieslice(1,getx,gety,0,360,fscale/2);
			      }
		          }
                       }
                                           
                       /*convert pnhood to 1d count*/
                       n=(i3d*j3d*h_n) + (i3d*j_n) + i_n;
                       /*convert to pnhood back to 2d co-ordss*/
                       i_n=n%i2d;
	               j_n=n/i2d;
                    }                   
		    iz=wiring[poss][wire]%i2d;
		    jz=wiring[poss][wire]/i2d;
                    if (twod && hex2d==1 && (j2d-jz)%2==0 && jz!=celly) 
                       addhex1=cscale/2;/*hex layout*/
                
                    temp_cscale=cscale;
                    if (cscale<=1) temp_cscale=2; 
		    if (ccel==1) setfillstyle(SOLID_FILL,red);
		    else{
                       if (bground=='w') setfillstyle(SOLID_FILL,blue);
                       if (bground=='b') setfillstyle(SOLID_FILL,yellow);
                    }
                     
                    if (direct_wire==0){
                       if (twod && hex2d==1 && cscale>=1 && (j2d-j_n)%2==0) /*hex layout*/
                                  addhex2=cscale/2;
		       moveto(right-(i_n+1)*cscale+addhex2,
                                 bottom-(j_n+1)*hex_vmove);
                    }
		    else moveto(cellx+addhex,celly);

		   if (this_suppress_links<4){ 
                      if (direct_wire==0 || ccel==1){
			 //setcolor(outcolor);
                         if (hex2d==1 && cscale>=1) 
                             draw_hexagonal_2d_cell_wiring(hex_rad,
			        hcscale-csep,2,0,block_fill_color,outcolor,
                                       getx,gety-hex_rad/4); 
                         else{
                            if (wiring_postscript){
                               color_ps(wiring_postscript-1,fillcolor);
                               rect_fill_ps(getx,gety, 
					    abs(getx-(getx+temp_cscale-csep)),
					    abs(gety-(gety+temp_cscale-csep)));
                               color_ps(wiring_postscript-1,getcolor()); 
                               rect_outline_ps(getx,gety, 
					    abs(getx-(getx+temp_cscale-csep)),
					       abs(gety-(gety+temp_cscale-csep)));
                            }

                            bar3d(getx,gety,
                            getx+temp_cscale-csep,
				      gety+temp_cscale-csep,0,1);
                         }
                         if (direct_wire==0 && show_pindex==1){
			       if (bground=='w') setcolor(white);
			       else setcolor(black);
                            if (wiring_postscript) /*postscript scales normal -m -s*/
                                  color_ps(wiring_postscript-1,getcolor());
                            tempx=getx;
                            tempy=gety;
                            /*2d or 2d+(3d): index nodes in nhood*/
                            //if (cscale>=15*1.4);
                            if (cscale>=CHeight_def*.6){
                               if (cscale>=15*1.4){ /* normal CHeight=15*/
                                  restore_def_font();
                                  if (wiring_postscript) 
	                            resetfont_ps("Times-Bold",
                                          (signed int) ((double)psize_ps*1.5) );
                               } 
                               else if (cscale>=15*1.2){
                                  set_medium_font();
                                  if (wiring_postscript) 
	                            resetfont_ps("Times-Roman",
                                          (signed int) ((double)psize_ps*1.2) );
                               }
                               else{
                                  if (wiring_postscript) resetfont_ps("Times-Roman", psize_ps);
                                  set_small_font();
	                       }

                               if (hex2d==1 && cscale>=15*1.4) /*print nhood index numbers*/
                                    moverel(+cscale/7,+cscale/25);
                               else moverel(+cscale/6,+cscale/6);
                               sprintf(textb[4],"%d",wire);
                               if (wiring_postscript){ /*postscript scales normal -m -s*/
				  //color_ps(wiring_postscript-1,white); 
	                          nodetext_ps(3,bground,textb[4],getx,gety+CHeight*.8);
                               }
                               outtext(textb[4]);
                               moveto(tempx,tempy);                             
			    }
                            /*3d -- index in nhood*/
                            if (threed && fscale>=CHeight_def*.6){
			      signed int tempx3d,tempy3d;
                               if (fscale>=15*1.4){ /* normal CHeight=15*/
                                  restore_def_font();
                                  if (wiring_postscript) 
	                            resetfont_ps("Times-Bold",
                                          (signed int) ((double)psize_ps*1.5) );
                               }
                               else if (fscale>=15*1.2){ /* normal CHeight=15*/
                                  set_medium_font();
                                  if (wiring_postscript) 
	                            resetfont_ps("Times-Roman",
                                          (signed int) ((double)psize_ps*1.2) );
                               }
                               else{
                                   if (wiring_postscript) 
                                         resetfont_ps("Times-Roman", psize_ps);
                                   set_small_font();
                               }
			       moveto(nhood_x,nhood_y);
                               if (wire<=9) moverel(-fscale/5,-fscale/3);
                               else moverel(-fscale/3,-fscale/3);
                               tempx3d=getx; /*otherwise position displaced*/
                               tempy3d=gety;
                               sprintf(textb[4],"%d",wire);
                               outtext(textb[4]);
                               if (wiring_postscript){ /*postscript scales normal -m -s*/
				 //color_ps(wiring_postscript-1,getcolor());
				 nodetext_ps(3,bground,textb[4],tempx3d,tempy3d+(CHeight+1)*.8);
                               }
                               moveto(tempx,tempy);
                            }
                         } 
                       }
		    }
		    /*show couplings from 2-d nhood*/
		    moverel((cscale-csep)/2,(hex_vmove-csep)/2);
                    wire_x=right-(iz+1)*cscale+(cscale-csep)/2+addhex1,
                    wire_y=bottom-(jz+1)*hex_vmove+(hex_vmove-csep)/2;

                    if (direct_wire==1 || wiring[poss][wire]!=poss_n){
                       if (block_set) setcolor(red);
                       else setcolor(white);
                       if (wiring_postscript)
                                color_ps(wiring_postscript-1,getcolor());
                       if (this_suppress_links==0 || this_suppress_links==1 
			   || this_suppress_links==4){
			   if (wiring_postscript)
                               line_ps(getx,gety,wire_x,wire_y);
                           lineto(wire_x,wire_y);
                       }
                       else moveto(wire_x,wire_y);
		       moverel(-(cscale-csep)/2,
                                         -(hex_vmove-csep)/2);
                       if (this_suppress_links==0 || this_suppress_links==2){
		          setfillstyle(SOLID_FILL,green);
                          if (cscale<=4 && bground=='b') setcolor(fillcolor);
		          else setcolor(outcolor);
                          if (hex2d==1 && cscale>=1) draw_hexagonal_2d_cell_wiring(hex_rad,
			      hcscale-csep,2,0,getcolor(),outcolor,
                                            getx,gety-hex_rad/4);
		          else{ 
                             if (wiring_postscript){
                                color_ps(wiring_postscript-1,fillcolor);
                                rect_fill_ps(getx,gety, 
					    abs(getx-(getx+temp_cscale-csep)),
					    abs(gety-(gety+temp_cscale-csep)));
                                color_ps(wiring_postscript-1,getcolor()); 
                                rect_outline_ps(getx,gety, 
					    abs(getx-(getx+temp_cscale-csep)),
					       abs(gety-(gety+temp_cscale-csep)));
                             }
                             bar3d(getx,gety,
                                getx+temp_cscale-csep,
					gety+temp_cscale-csep,0,1);
                          }
                       }
		    }
		    moveto(cellx,celly);
	    }
          end_links:
            restore_def_font();
            if (wiring_postscript) 
	    resetfont_ps("Times-Roman",(signed int) ((double)psize_ps*1.5) );
}
/************** check if outside 2d or 3d block Aug 1999  **************/
char outside_2d_3d_block(unsigned int zzu,
              signed int low_ii,signed int low_jj,signed int low_hh,
              signed int high_ii,signed int high_jj,signed int high_hh){

   signed int this_ii,this_jj,this_hh;
   char outside=0;

   if (oned){
      if (zzu<low_ii || zzu>high_ii) outside=1;
   } 
   else if (twod){
      this_ii=zzu%i2d;
      this_jj=zzu/i2d;
      if (this_ii<low_ii || this_ii>high_ii ||
          this_jj<low_jj || this_jj>high_jj) outside=1; 
   }
   else if (threed){
       this_ii=zzu%i3d;
       this_jj=zzu%(i3d*j3d)/i3d;
       this_hh=zzu/(i3d*j3d);
       if (this_ii<low_ii || this_ii>high_ii ||
           this_jj<low_jj || this_jj>high_jj ||
           this_hh<low_hh || this_hh>high_hh) outside=1; 
   }
   return(outside);
}

/************** jump to new position in 2d or 3d graphic  **************/
void jump2d_3d(signed int *ij){
    signed int ii,jj,temp_ii,temp_jj,temp_hh,xbox;

                         moveto(getx-CWidth,gety);                         
			 setfillstyle(SOLID_FILL,black);
			 bar(getx,gety+2,                                  
			   getx+CWidth,gety+CHeight+2);                    
			 get_prompt_box(7,3);                              
			 erase_prompt_box(3);                              
			 xbox=draw_prompt_box(2);                          
			 if (oned || twod){ 
                             outtext("jump to coords I,J");
                             temp_ii=i2d-1; 
                             temp_jj=j2d-1; 
                         }
                         else if (threed){ 
                             outtext("jump to coords  I,J,H");
                             temp_ii=i3d-1; 
                             temp_jj=j3d-1; 
                             temp_hh=j3d-1; 
                         }
			 moveto(xbox,gety+CHeight);                        
			 sprintf(textb[0],"enter I (%d-0):",temp_ii);
			 outtext(textb[0]);
                         sprintf(textb[0],"%d",temp_ii);
			 input_string(strlen(textb[0]),1);                 
			 if (atoi(is)>=0 && atoi(is)<=temp_ii) temp_ii=atoi(is);
			 sprintf(textb[0]," enter J (%d-0):",temp_jj);
			 outtext(textb[0]);
			 sprintf(textb[0],"%d",temp_jj);
			 input_string(strlen(textb[0]),1);                 
			 if (atoi(is)>=0 && atoi(is)<=temp_jj) temp_jj=atoi(is);
                         if (threed){
                            sprintf(textb[0]," enter H (%d-0):",temp_hh);    
			    outtext(textb[0]); 
			    sprintf(textb[0],"%d",temp_hh);
			    input_string(strlen(textb[0]),1);                 
			    if (atoi(is)>=0 && atoi(is)<=temp_hh) temp_hh=atoi(is);
			 }
                         if (oned || twod){
                            ii=temp_ii;
                            jj=temp_jj;
                         }
                         else if (threed){
                            unsigned int temp_poss;
                            temp_poss=(i3d*j3d*temp_hh) + (i3d*temp_jj) + temp_ii;
                            ii=temp_poss%i2d;
	                    jj=temp_poss/i2d; 
                         }
                         ij[0]=ii;
                         ij[1]=jj;

			 is[0]=0;                         
                         uncover_free_prompt_box(7);
}

/******************* 2-D regular 9-1 nhood wiring, Dec 93 **************/
void wireup_2d_nhood(signed int itop,signed int jtop,
			    signed int ibot,signed int jbot){
 unsigned int poss;
 signed int jj,ii;
    for (jj=jtop;jj>=jbot;jj--){
       for (ii=itop;ii>=ibot;ii--){
	   poss=i2d*jj + ii;
           wire_2d_local(poss,wiring[poss]);
       }            
    }
    cell_out_freq();
}
/******************* 3-D regular 9-1 nhood wiring, May 98  **************/
void wireup_3d_nhood(signed int itop,signed int jtop,signed int htop,
		     signed int ibot,signed int jbot,signed int hbot){
 unsigned int poss;
 signed int hh,jj,ii;
    for (hh=htop;hh>=hbot;hh--){
       for (jj=jtop;jj>=jbot;jj--){
          for (ii=itop;ii>=ibot;ii--){
               poss=(i3d*j3d*hh) + (i3d*jj) + ii;
               wire_3d_local(poss,wiring[poss]);
          }            
       }
    }
    cell_out_freq();
}
/************************ local 2d wiring  *************************/
void wire_2d_local(unsigned int poss, unsigned int *pnhood){
 signed int wire;
     for (wire=0;wire<=nhoodm[poss]-1;wire++){                  
         pndood_2or3(2,poss,wire); 
         /*pnhood[wire]=i2d*j_n+i_n;*/
         pnhood[wire]=poss_n;
     }
}

/************************ local 3d wiring  *************************/
void wire_3d_local(unsigned int poss,unsigned int *pnhood){    
 signed int wire;

      for (wire=0;wire<=nhoodm[poss]-1;wire++){
         pndood_2or3(3,poss,wire);
         pnhood[wire]=poss_n;
         /*if (poss_n>lineL-1) {
            fprintf(stderr,"\n error: ijh=%d,%d,%d poss=%d: %d>%d\n",
                           i_n,j_n,h_n,poss,poss_n,lineL-1);
            input_string(1,0);
         }*/
      }
}

/************************ specify psuedo-nhood *************************/
char pndood_2or3(char dim,unsigned int poss, signed int wire){

   signed int ii,jj,hh,temp_j2d;
   char ccel=0;          

          if (dim==2){
             ii=poss%i2d;
	     jj=poss/i2d;
          }
          else if (dim==3){
             ii=poss%i3d;
	     jj=poss%(i3d*j3d)/i3d;
             hh=poss/(i3d*j3d);
             /*convert j2d to 3d*/
             temp_j2d=j2d;
             j2d=j3d;
          }
               
              /*  * 0 *  ..the nhood, for both 2d and 3d*/
	   if (nhoodm[poss]==1){
                 switch(wire){
		    case 0:  centre;
		             ccel=1;
		 }
	   }
 
           /*--------------- k =2 to 27 for 2d -------------------*/
           if (dim==2){  
              /* 1 * 0 ..nhood=2 - no self wiring */ 
	      if (nhoodm[poss]==2){
		  switch(wire){
		       case 1:  northwest   ; break;
		       case 0:  southeast;
		  }
	      }
	  
                    /*nhood=3 hex grid only - no self wiring
		    2 *	      odd rows     2 *     even rows     2 *
		    * * 1   ..the nhood  * * 1   ..the nhood    * * 1
		    0 *                    0 *                   0 *    */
	      else if (nhoodm[poss]==3 && hex2d==1 && dim==2){
		    if ((jj+1)%2==0){ /*odd*/
		       switch(wire){
			  case 2:  northwest; break;
			  case 1:  east; break;
			  case 0:  southwest; break;
		       }
		    }
		    else{
		       switch(wire){ /*even*/
			  case 2:  north; break;
			  case 1:  east; break;
			  case 0:  south; break;
		       }
		    }
              }	      
	      /*  2 1 0   ..nhood=3 */
	      else if (nhoodm[poss]==3){
		  switch(wire){
		       case 2:  northwest; break;
		       case 1:  centre; 
                                ccel=1; break;
		       case 0:  southeast;
		  }
	      }

              /*nhood=4 hex grid only - with self wiring
		    3 *	      odd rows     3 *     even rows     3 *
		    * 2 1   ..the nhood  * 2 1   ..the nhood    * 2 1
		    0 *                    0 *                   0 *    */
	      else if (nhoodm[poss]==4 && hex2d==1 && dim==2){
		    if ((jj+1)%2==0){ /*odd*/
		       switch(wire){
			  case 3:  northwest; break;
			  case 2:  centre     ; 
			           ccel=1     ;break;
                          case 1:  east;      break;
			  case 0:  southwest; break;
		       }
		    }
		    else{
		       switch(wire){ /*even*/
			  case 3:  north    ; break;
                          case 2:  centre     ; 
			           ccel=1     ;break;
			  case 1:  east     ; break;
			  case 0:  south    ; break;
		       }
		    }	      
              }

	      /*     3
		   2 * 1   ..nhood=4 - no self wiring
                     0     */
	      else if (nhoodm[poss]==4){
		  switch(wire){
		       case 3:  north    ; break;
		       case 2:  west     ; break;
		       case 1:  east     ; break;
		       case 0:  south    ;
		  }		   
	      }
	      /*   4
		 3 2 1   ..nhood=5
		   0   */
	      else if (nhoodm[poss]==5){
		    switch(wire){
		       case 4: north;    break;
		       case 3: west;     break;
		       case 2: centre;
                               ccel=1;   break;
		       case 1: east;     break;
		       case 0: south;
		    }
	      }
	  
              /*nhood=6 hex grid only - no self wiring
		    5 4	      odd rows     5 4     even rows     5 4
		    3 * 2   ..the nhood  3 * 2   ..the nhood    3 * 2
		    1 0                    1 0                   1 0   */
	      else if (nhoodm[poss]==6){
		    if ((jj+1)%2==0){ /*odd*/
		       switch(wire){
			  case 5:  northwest; break;
			  case 4:  north    ; break;
			  case 3:  west     ; break;
			  case 2:  east     ; break;
			  case 1:  southwest; break;
			  case 0:  south    ;
		       }
		    }
		    else{
		       switch(wire){ /*even*/
			  case 5:  north    ; break;
			  case 4:  northeast; break;
			  case 3:  west     ; break;
			  case 2:  east     ; break;
			  case 1:  south    ; break;
			  case 0:  southeast;
		       }
		    }	      
              }
	      /* hex only grid nhood=7
		    6 5	      odd rows     6 5     even rows     6 5
		    4 3 2   ..the nhood  4 3 2   ..the nhood    4 3 2
		    1 0                    1 0                   1 0   */
	      else if (nhoodm[poss]==7){
		    if ((jj+1)%2==0){  /*odd*/
		       switch(wire){
			  case 6:  northwest; break;
			  case 5:  north    ; break;
			  case 4:  west     ; break;
			  case 3:  centre   ; 
                                   ccel=1   ; break;
			  case 2:  east     ; break;
			  case 1:  southwest; break;
			  case 0:  south    ;
		       }
		    }
		    else{            /*even*/
		       switch(wire){
			  case 6:  north    ; break;
			  case 5:  northeast; break;
			  case 4:  west     ; break;
			  case 3:  centre   ;
                                   ccel=1   ; break;
			  case 2:  east     ; break;
			  case 1:  south    ; break;
			  case 0:  southeast;
		       }
		    }
	      }
	      /* square grid only, nhood=8
                 7 6 5
		 4 * 3   ..the nhood=8
		 2 1 0    */
	      else if (nhoodm[poss]==8){
		    switch(wire){
		       case 7:  northwest; break;
		       case 6:  north    ; break;
		       case 5:  northeast; break;
		       case 4:  west     ; break;
		       case 3:  east     ; break;
		       case 2:  southwest; break;
		       case 1:  south    ; break;
		       case 0:  southeast;
		    }
	      }
	      /* square grid, nhood=9
                 8 7 6
		 5 4 3   ..nhood=9
		 2 1 0   */
	      else if (nhoodm[poss]==9 && hex2d==0){
		    switch(wire){
		       case 8: northwest; break;
		       case 7: north;     break;
		       case 6: northeast; break;
		       case 5: west;      break;
		       case 4: centre; 
                               ccel=1;    break;
		       case 3: east;      break;
		       case 2: southwest; break;
		       case 1: south;     break;
		       case 0: southeast;
		    }
		   
	      }
              /* hex grid nhood=9 - no self wiring
                   8                 8                        8
                 7 6   ..odd rows    7 6 ..even rows         7 6  
		 5 * 4             5 * 4                    5 * 4
	       3 2 1 0             3 2 1 0                 3 2 1 0  */
	      else if (nhoodm[poss]==9 && hex2d==1){
                 if ((jj+1)%2==0){  /*odd*/
		    switch(wire){
		       case 8: north1;    break;
		       case 7: northwest; break;
		       case 6: north;     break;
		       case 5: west;      break;
		       case 4: east;      break;
		       case 3: west1south;break;
		       case 2: southwest; break;
		       case 1: south;     break;
		       case 0: southeast;
		    }
		 } 
                 else{  /*even*/
		    switch(wire){
		       case 8: north1;    break;
		       case 7: north;     break;
		       case 6: northeast; break;
		       case 5: west;      break;
		       case 4: east;      break;
		       case 3: southwest; break;
		       case 2: south;     break;
		       case 1: southeast; break;
		       case 0: east1south;
		    }
		 }  
	      }


              /* square grid nhood=12 (not nice)
                   9
                 8 7 6
	         5 * 4   ..nhood=10  - no self wiring
		 3 2 1 
                   0     */
	      else if (nhoodm[poss]==10 && hex2d==0){
		    switch(wire){
		       case 9: north1;    break;
		       case 8: northwest; break;
		       case 7: north;     break;
		       case 6: northeast; break;
		       case 5: west;      break;
                       case 4: east;      break;
		       case 3: southwest; break;
		       case 2: south;     break;
		       case 1: southeast; break;
		       case 0: south1;
		    }
	      }

              /* hex grid nhood=10
                   9                 9                        9
                 8 7   ..odd rows    8 7 ..even rows         8 7  
		 6 5 4             6 5 4                    6 5 4
	       3 2 1 0             3 2 1 0                 3 2 1 0  */
	      else if (nhoodm[poss]==10 && hex2d==1){
                 if ((jj+1)%2==0){  /*odd*/
		    switch(wire){
		       case 9: north1;    break;
		       case 8: northwest; break;
		       case 7: north;     break;
		       case 6: west;      break;
                       case 5: centre; 
                               ccel=1;    break;
		       case 4: east;      break;
		       case 3: west1south;break;
		       case 2: southwest; break;
		       case 1: south;     break;
		       case 0: southeast;
		    }
		 } 
                 else{  /*even*/
		    switch(wire){
		       case 9: north1;    break;
		       case 8: north;     break;
		       case 7: northeast; break;
		       case 6: west;      break;
                       case 5: centre; 
                               ccel=1;    break;
		       case 4: east;      break;
		       case 3: southwest; break;
		       case 2: south;     break;
		       case 1: southeast; break;
		       case 0: east1south;
		    }
		 }  
	      }

              /* square grid, nhood=11 (not nice)
                  10
                 9 8 7
	         6 5 4  ..nhood=11
		 3 2 1   
                   0    */
	      else if (nhoodm[poss]==11){
		    switch(wire){
		       case 10:north1;    break;
		       case 9: northwest; break;
		       case 8: north;     break;
		       case 7: northeast; break;
		       case 6: west;      break;
                       case 5: centre;
                               ccel=1;    break;
                       case 4: east;      break;
		       case 3: southwest; break;
		       case 2: south;     break;
		       case 1: southeast; break;
		       case 0: south1;
		    }
	      }
              /* square grid, nhood=12 - no self wiring
                  11
                10 9 8
	       7 6 * 5 4  ..nhood=12 - no self wiring
		 3 2 1
                   0     */
	      else if (nhoodm[poss]==12 && hex2d==0){
		    switch(wire){
                       case 11:north1;    break;
		       case 10:northwest; break;
		       case 9: north;     break;
		       case 8: northeast; break;
		       case 7: west1;     break;
		       case 6: west;      break;
                       case 5: east;      break;
                       case 4: east1;     break;
		       case 3: southwest; break;
		       case 2: south;     break;
		       case 1: southeast; break;
		       case 0: south1;
		    }
	      }

             /* hex grid nhood=12 - no self wiring
                 11                  11                      11
             10 9 8 7 ..odd rows   10 9 8 7 ..even rows   10 9 8 7
	        6 * 5               6 * 5                   6 * 5 
	      4 3 2 1               4 3 2 1                4 3 2 1
                  0                   0                       0     */
	      else if (nhoodm[poss]==12 && hex2d==1){
                 if ((jj+1)%2==0){  /*odd*/
		    switch(wire){
                       case 11:north1;    break;
		       case 10:west1north;break;
		       case 9: northwest; break;
		       case 8: north;     break;
		       case 7: northeast; break;
		       case 6: west;      break;
                       case 5: east;      break;
                       case 4: west1south;break;
		       case 3: southwest; break;
		       case 2: south;     break;
		       case 1: southeast; break;
		       case 0: south1;
		    }
                 }
		 else{
                    switch(wire){
                       case 11:north1;    break;
		       case 10:northwest; break;
		       case 9: north;     break;
		       case 8: northeast; break;
		       case 7: east1north;break;
		       case 6: west;      break;
                       case 5: east;      break;
                       case 4: southwest; break;
		       case 3: south;     break;
		       case 2: southeast; break;
		       case 1: east1south;break;
		       case 0: south1;
		    }
                 }
	      }

              /* square grid, nhood=13
                   12
                11 10  9
	      8  7  6  5 4  ..nhood=13 
		 3  2  1
                    0     */
	      else if (nhoodm[poss]==13 && hex2d==0){
		    switch(wire){
                       case 12:north1;    break;
                       case 11:northwest; break;
		       case 10:north;     break;
		       case 9: northeast; break;
		       case 8: west1;     break;
		       case 7: west;      break;
		       case 6: centre;
                               ccel=1;    break;
                       case 5: east;      break;
                       case 4: east1;     break;
		       case 3: southwest; break;
		       case 2: south;     break;
		       case 1: southeast; break;
		       case 0: south1;
		    }
	      }

              /* hex grid, nhood=13
                 12                   12                      12
            11 10 9 8 ..odd rows   11 10 9 8 ..even rows   11 10 9 8
	        7 6 5               7  6 5                   7 6 5 
	     4  3 2 1               4  3 2 1                4 3 2 1
                  0                    0                       0     */
	      else if (nhoodm[poss]==13 && hex2d==1){
                 if ((jj+1)%2==0){  /*odd*/
		    switch(wire){
                       case 12:north1;    break;
		       case 11:west1north;break;
		       case 10:northwest; break;
		       case 9: north;     break;
		       case 8: northeast; break;
		       case 7: west;      break;
                       case 6: centre;
                               ccel=1;    break;
                       case 5: east;      break;
                       case 4: west1south;break;
		       case 3: southwest; break;
		       case 2: south;     break;
		       case 1: southeast; break;
		       case 0: south1;
		    }
                 }
		 else{
                    switch(wire){
                       case 12:north1;    break;
		       case 11:northwest; break;
		       case 10: north;     break;
		       case 9: northeast; break;
		       case 8: east1north;break;
		       case 7: west;      break;
                       case 6: centre;
                               ccel=1;    break;
                       case 5: east;      break;
                       case 4: southwest; break;
		       case 3: south;     break;
		       case 2: southeast; break;
		       case 1: east1south;break;
		       case 0: south1;
		    }
                 }
	      }

              /* square grid only, nhood=14 (not nice)
                   13
                   12
                11 10  9
	      8  7     6 5  ..nhood=14 
		 4  3  2
                    1     
                    0      */
	      else if (nhoodm[poss]==14){
		    switch(wire){
                       case 13:north2;    break;
                       case 12:north1;    break;
                       case 11:northwest; break;
		       case 10:north;     break;
		       case 9: northeast; break;
		       case 8: west1;     break;
		       case 7: west;      break;
		       case 6: east;      break;
                       case 5: east1;     break;
                       case 4: southwest; break;
		       case 3: south;     break;
		       case 2: southeast; break;
		       case 1: south1;    break;
		       case 0: south2;
		    }
	      }

              /* square grid, nhood=15 (not nice)
                   14
                   13
                12 11 10
	      9  8  7  6 5  ..nhood=15
		 4  3  2
                    1     
                    0      */
	      else if (nhoodm[poss]==15 && hex2d==0){
		    switch(wire){
                       case 14:north2;    break;
                       case 13:north1;    break;
                       case 12:northwest; break;
		       case 11:north;     break;
		       case 10: northeast;break;
		       case 9: west1;     break;
		       case 8: west;      break;
                       case 7: centre;
                               ccel=1;    break;
		       case 6: east;      break;
                       case 5: east1;     break;
                       case 4: southwest; break;
		       case 3: south;     break;
		       case 2: southeast; break;
		       case 1: south1;    break;
		       case 0: south2;
		    }
	      }

              /* hex grid nhood=15 - no self wiring
                   14 13                     14 13
             12 11 10  9  ..odd rows      12 11 10  9 ..even rows
	      8  7  *  6                8  7  *  6
	      5	 4  3  2                   5  4  3  2
                    1  0                      1  0
                           14  13
                     12  11  10   9
                    8    7   *   6
                      5   4   3   2
                            1   0
                          */

	      else if (nhoodm[poss]==15 && hex2d==1){
                 if ((jj+1)%2==0){  /*odd*/
		    switch(wire){
                       case 14: north1;     break;
                       case 13: north1east; break;
                       case 12: west1north; break;
		       case 11: northwest;  break;
		       case 10: north;      break;
		       case 9: northeast;   break;
		       case 8: west1;       break;
                       case 7: west;        break;
		       case 6: east;        break;
                       case 5: west1south;  break;
                       case 4: southwest;   break;
		       case 3: south;       break;
		       case 2: southeast;   break;
		       case 1: south1;      break;
		       case 0: south1east;
		    }
                 }
                 else{  /*even*/
		    switch(wire){
                       case 14: north1;     break;
                       case 13: north1east; break;
                       case 12: northwest;  break;
		       case 11: north;      break;
		       case 10: northeast;  break;
		       case 9: east1north;  break;
		       case 8: west1;       break;
                       case 7: west;        break;
		       case 6: east;        break;
                       case 5: southwest;   break;
                       case 4: south;       break;
		       case 3: southeast;   break;
		       case 2: east1south;  break;
		       case 1: south1;      break;
		       case 0: south1east;
		    }
                 }
	      } 
              /* square grid nhood=16  - no self wiring
                   15
                   14
                13 12 11
	  10  9  8  *  7  6  5 
		 4  3  2
                    1     
                    0      */
	      else if (nhoodm[poss]==16 && hex2d==0){
		    switch(wire){
                       case 15:north2;    break;
                       case 14:north1;    break;
                       case 13:northwest; break;
		       case 12:north;     break;
		       case 11:northeast;break;
		       case 10:west2;     break;
		       case 9: west1;     break;
		       case 8: west;      break;
                       case 7: east;      break;
                       case 6: east1;     break;
                       case 5: east2;     break;
                       case 4: southwest; break;
		       case 3: south;     break;
		       case 2: southeast; break;
		       case 1: south1;    break;
		       case 0: south2;
		    }
	      }
 
              /* hex grid nhood=16
                   15 14                     15 14
             13 12 11 10  ..odd rows      13 12 11 10 ..even rows
	      9  8  7  6                9  8  7  6
	      5	 4  3  2                   5  4  3  2
                    1  0                      1  0
                           15  14
                     13  12  11  10
                   9    8   7   6     stp opposite sence??
                      5   4   3   2
                            1   0
                          */

	      else if (nhoodm[poss]==16){
                 if ((jj+1)%2==0){  /*odd*/
		    switch(wire){
                       case 15: north1;     break;
                       case 14: north1east; break;
                       case 13: west1north; break;
		       case 12: northwest;  break;
		       case 11: north;      break;
		       case 10: northeast;  break;
		       case 9: west1;       break;
                       case 8: west;        break;
                       case 7: centre;
                               ccel=1;      break;
		       case 6: east;        break;
                       case 5: west1south;  break;
                       case 4: southwest;   break;
		       case 3: south;       break;
		       case 2: southeast;   break;
		       case 1: south1;      break;
		       case 0: south1east;
		    }
                 }
                 else{  /*even*/
		    switch(wire){
                       case 15: north1;     break;
                       case 14: north1east; break;
                       case 13: northwest;  break;
		       case 12: north;      break;
		       case 11: northeast;  break;
		       case 10: east1north;  break;
		       case 9: west1;       break;
                       case 8: west;        break;
                       case 7: centre;
                               ccel=1;      break;
		       case 6: east;        break;
                       case 5: southwest;   break;
                       case 4: south;       break;
		       case 3: southeast;   break;
		       case 2: east1south;  break;
		       case 1: south1;      break;
		       case 0: south1east;
		    }
                 }
	      }  

               /* square grid only nhood=17
                   16
                   15
                14 13 12
	  11 10  9  8  7  6  5 
		 4  3  2
                    1     
                    0      */
	      else if (nhoodm[poss]==17){
		    switch(wire){
                       case 16:north2;    break;
                       case 15:north1;    break;
                       case 14:northwest; break;
		       case 13:north;     break;
		       case 12:northeast; break;
		       case 11:west2;     break;
		       case 10: west1;    break;
		       case 9: west;      break;
                       case 8: centre;
                               ccel=1;    break;
                       case 7: east;      break;
                       case 6: east1;     break;
                       case 5: east2;     break;
                       case 4: southwest; break;
		       case 3: south;     break;
		       case 2: southeast; break;
		       case 1: south1;    break;
		       case 0: south2;
		    }
	      }

              /* hex grid only, nhood=18  - no self wiring
                17 16 15                     17 16 15
             14 13 12 11  ..odd rows         14 13 12 11 ..even rows
	     10  9  *  8 7                10  9  *  8 7
	      6	 5  4  3                      6  5  4  3 
                 2  1  0                      2  1  0

                       17  16  15 
                     14  13  12  11
                   10   9   *   8   7      stp opposite sence??
                      6	  5   4   3
                        2   1   0
              */

	      else if (nhoodm[poss]==18){
                 if ((jj+1)%2==0){  /*odd*/
		    switch(wire){
                       case 17: north1west; break;
                       case 16: north1;     break;
                       case 15: north1east; break;
                       case 14: west1north; break;
		       case 13: northwest;  break;
		       case 12: north;      break;
		       case 11: northeast;  break;
		       case 10: west1;      break;
		       case 9: west;        break;                  
		       case 8: east;        break;
                       case 7: east1;       break;
                       case 6: west1south;  break;
                       case 5: southwest;   break;
		       case 4: south;       break;
		       case 3: southeast;   break;
                       case 2: south1west;  break;
		       case 1: south1;      break;
		       case 0: south1east;
		    }
                 }
                 else{  /*even*/
		    switch(wire){
                       case 17: north1west; break;
                       case 16: north1;     break;
                       case 15: north1east; break;
                       case 14: northwest;  break;
		       case 13: north;      break;
		       case 12: northeast;  break;
		       case 11: east1north; break;
		       case 10: west1;      break;
                       case 9:  west;       break;
                       case 8: east;        break;
		       case 7: east1;       break;
                       case 6: southwest;   break;
                       case 5: south;       break;
		       case 4: southeast;   break;
		       case 3: east1south;  break;
                       case 2: south1west;  break;
		       case 1: south1;      break;
		       case 0: south1east;
		    }
                 }
	      }  
               /* hex grid only, nhood=19
                18 17 16                     18 17 16
             15 14 13 12  ..odd rows         15 14 13 12 ..even rows
	     11 10  9  8 7                11 10  9  8 7
	      6	 5  4  3                      6  5  4  3 
                 2  1  0                      2  1  0

                       18  17  16 
                     15  14  13  12
                   11  10   9   8   7      stp opposite sence??
                      6	  5   4   3
                        2   1   0
              */

	      else if (nhoodm[poss]==19){
                 if ((jj+1)%2==0){  /*odd*/
		    switch(wire){
                       case 18: north1west; break;
                       case 17: north1;     break;
                       case 16: north1east; break;
                       case 15: west1north; break;
		       case 14: northwest;  break;
		       case 13: north;      break;
		       case 12: northeast;  break;
		       case 11: west1;      break;
		       case 10: west;       break;
                       case 9: centre;
                               ccel=1;    break;
		       case 8: east;        break;
                       case 7: east1;       break;
                       case 6: west1south;  break;
                       case 5: southwest;   break;
		       case 4: south;       break;
		       case 3: southeast;   break;
                       case 2: south1west;  break;
		       case 1: south1;      break;
		       case 0: south1east;
		    }
                 }
                 else{  /*even*/
		    switch(wire){
                       case 18: north1west; break;
                       case 17: north1;     break;
                       case 16: north1east; break;
                       case 15: northwest;  break;
		       case 14: north;      break;
		       case 13: northeast;  break;
		       case 12: east1north; break;
		       case 11: west1;      break;
                       case 10:  west;      break;
                       case 9: centre;
                               ccel=1;    break;
                       case 8: east;        break;
		       case 7: east1;       break;
                       case 6: southwest;   break;
                       case 5: south;       break;
		       case 4: southeast;   break;
		       case 3: east1south;  break;
                       case 2: south1west;  break;
		       case 1: south1;      break;
		       case 0: south1east;
		    }
                 }
	      }  
              /* square grid only nhood=20  - no self wiring
                19 18 17
             16 15 14 13 12
	     11 10  *  9  8 
	      7  6  5  4  3
                 2  1  0
                      */
	      else if (nhoodm[poss]==20){
		    switch(wire){
                       case 19: north1west;break;
                       case 18: north1;    break;
                       case 17: north1east;break;
		       case 16: west1north;break;
		       case 15: northwest; break;
		       case 14: north;     break;
		       case 13: northeast; break;
		       case 12: east1north;break;
                       case 11: west1;     break;
                       case 10: west;      break;
                       case 9: east;       break;
                       case 8: east1;      break;
                       case 7: west1south; break;
                       case 6: southwest;  break;
                       case 5: south;      break;
                       case 4: southeast;  break;
                       case 3: east1south ;break;
		       case 2: south1west; break;
		       case 1: south1;     break;
		       case 0: south1east; break;
		    }
	      }
              /* square grid nhood=21
                20 19 18
             17 16 15 14 13
	     12 11 10  9  8 
	      7  6  5  4  3
                 2  1  0
                      */
	      else if (nhoodm[poss]==21 && hex2d==0){
		    switch(wire){
                       case 20: north1west;break;
                       case 19: north1;    break;
                       case 18: north1east;break;
		       case 17: west1north;break;
		       case 16: northwest; break;
		       case 15: north;     break;
		       case 14: northeast; break;
		       case 13: east1north;break;
                       case 12: west1;     break;
                       case 11: west;      break;
                       case 10: centre;
                               ccel=1;    break;
                       case 9: east;       break;
                       case 8: east1;      break;
                       case 7: west1south; break;
                       case 6: southwest;  break;
                       case 5: south;      break;
                       case 4: southeast;  break;
                       case 3: east1south ;break;
		       case 2: south1west; break;
		       case 1: south1;     break;
		       case 0: south1east; break;
		    }
	      }
              /* hex grid nhood=21 - no self wiring
                   20                           20
                   19 18 17                  19 18 17
          16 15 14 13 12  ..odd rows   16 15 14 13 12 ..even rows
	     11 10  *  9               11 10  *  9
	   8  7	 6  5  4                8  7  6  5  4
                    3  2  1                   3  2  1
                    0                            0
                             20
                           19  18  17
                 16  15  14  13  12
                   11  10   *   9
                  8   7   6   5   4
                            3   2   1
                              0
                          */

	      else if (nhoodm[poss]==21 && hex2d==1){
                 if ((jj+1)%2==0){  /*odd*/
		    switch(wire){
                       case 20: north2;     break;
                       case 19: north1;     break;
                       case 18: north1east; break;
                       case 17: northeast1; break;
                       case 16: west2north; break;
                       case 15: west1north; break;
		       case 14: northwest;  break;
		       case 13: north;      break;
		       case 12: northeast;   break;
		       case 11: west1;       break;
                       case 10: west;        break;
		       case 9: east;        break;
                       case 8: west2south;  break;
                       case 7: west1south;  break;
                       case 6: southwest;   break;
		       case 5: south;       break;
		       case 4: southeast;   break;
		       case 3: south1;      break;
		       case 2: south1east;  break;
                       case 1: southeast1; break;
                       case 0: south2;
		    }
                 }
                 else{  /*even*/
		    switch(wire){
                       case 20: north2east; break;
                       case 19: north1;     break;
                       case 18: north1east; break;
                       case 17: northeast1; break;
                       case 16: west1north; break;
                       case 15: northwest;  break;
		       case 14: north;      break;
		       case 13: northeast;  break;
		       case 12: east1north; break;
		       case 11: west1;      break;
                       case 10: west;       break;
		       case 9: east;        break;
                       case 8: west1south;  break;
                       case 7: southwest;   break;
                       case 6: south;       break;
		       case 5: southeast;   break;
		       case 4: east1south;  break;
		       case 3: south1;      break;
		       case 2: south1east;  break;
                       case 1: southeast1; break;
                       case 0: south2east;
		    }
                 }
	      } 
               /* hex grid only, nhood=22
                   21                           21
                   20 19 18                  20 19 18
          17 16 15 14 13  ..odd rows   17 16 15 14 13 ..even rows
	     12 11 10  9               12 11 10  9
	   8  7	 6  5  4                8  7  6  5  4
                    3  2  1                   3  2  1
                    0                            0
                             21
                           20  19  18
                 17  16  15  14  13
                   12  11  10   9
                  8   7   6   5   4
                            3   2   1
                              0
                          */

	      else if (nhoodm[poss]==22){
                 if ((jj+1)%2==0){  /*odd*/
		    switch(wire){
                       case 21: north2;     break;
                       case 20: north1;     break;
                       case 19: north1east; break;
                       case 18: northeast1; break;
                       case 17: west2north; break;
                       case 16: west1north; break;
		       case 15: northwest;  break;
		       case 14: north;      break;
		       case 13: northeast;   break;
		       case 12: west1;       break;
                       case 11: west;        break;
                       case 10: centre;
                               ccel=1;    break;
		       case 9: east;        break;
                       case 8: west2south;  break;
                       case 7: west1south;  break;
                       case 6: southwest;   break;
		       case 5: south;       break;
		       case 4: southeast;   break;
		       case 3: south1;      break;
		       case 2: south1east;  break;
                       case 1: southeast1; break;
                       case 0: south2;
		    }
                 }
                 else{  /*even*/
		    switch(wire){
                       case 21: north2east; break;
                       case 20: north1;     break;
                       case 19: north1east; break;
                       case 18: northeast1; break;
                       case 17: west1north; break;
                       case 16: northwest;  break;
		       case 15: north;      break;
		       case 14: northeast;  break;
		       case 13: east1north; break;
		       case 12: west1;      break;
                       case 11: west;       break;
                       case 10: centre;
                               ccel=1;    break;
		       case 9: east;        break;
                       case 8: west1south;  break;
                       case 7: southwest;   break;
                       case 6: south;       break;
		       case 5: southeast;   break;
		       case 4: east1south;  break;
		       case 3: south1;      break;
		       case 2: south1east;  break;
                       case 1: southeast1; break;
                       case 0: south2east;
		    }
                 }
	      }
              /* square grid only nhood=23 (not nice)
                   22
                21 20 19
             18 17 16 15 14
	     13 12 11 10  9 
	      8  7  6  5  4
                 3  2  1
                    0
                      */
	      else if (nhoodm[poss]==23){
		    switch(wire){
                       case 22: north2;    break;
                       case 21: north1west;break;
                       case 20: north1;    break;
                       case 19: north1east;break;
		       case 18: west1north;break;
		       case 17: northwest; break;
		       case 16: north;     break;
		       case 15: northeast; break;
		       case 14: east1north;break;
                       case 13: west1;     break;
                       case 12: west;      break;
                       case 11: centre;
                               ccel=1;    break;
                       case 10: east;      break;
                       case 9: east1;      break;
                       case 8: west1south; break;
                       case 7: southwest;  break;
                       case 6: south;      break;
                       case 5: southeast;  break;
                       case 4: east1south ;break;
		       case 3: south1west; break;
		       case 2: south1;     break;
		       case 1: south1east; break;
                       case 0: south2;     break;
		    }
	      }

              /* square grid nhood=24 - no self wiring
              23 22 21 20 19
              18 17 16 15 14
              13 12  * 11 10  
              9  8   7  6  5
              4  3   2  1  0 */
              else if (nhoodm[poss]==24 && hex2d==0){
		    switch(wire){
		       case 23: northwest1; break;
                       case 22: north1west; break;
		       case 21: north1;     break;
		       case 20: north1east; break;
		       case 19: northeast1; break;
                       case 18: west1north; break;
		       case 17: northwest;  break;
		       case 16: north;      break;
                       case 15: northeast;  break;
                       case 14: east1north; break;
                       case 13: west1;      break;
                       case 12: west;       break;
                       case 11: east;       break;
                       case 10: east1;      break;
                       case 9: west1south;  break;
                       case 8: southwest;   break;
                       case 7: south;       break;
		       case 6: southeast;   break;
		       case 5: east1south;  break;
		       case 4: southwest1;  break;
		       case 3: south1west;  break;
		       case 2: south1;      break;
                       case 1: south1east;  break;
                       case 0: southeast1;
		    }
	      }
              /* hex grid, nhood=23
                          
                     23  22                     23  22 
                     21  20  19             21  20  19
                 18  17  16  15             18  17  16  15 
     odd rows..  14  13   *  12  11     14  13   *  12  11  ..even rows
             10   9   8   7   6   5     10   9   8   7   6   5 
                  4   3   2   1   0      4   3   2   1   0 
                    
                       23  22
                     21  20  19
                   18  17  16  15
                 14  13   *  12  11
               10   9   8   7   6   5   
                  4   3   2   1   0
                          */

	      else if (nhoodm[poss]==24 && hex2d==1){
                 if ((jj+1)%2==0){  /*odd*/
		    switch(wire){
                       case 23: north2west; break;
                       case 22: north2;     break;
                       case 21: north1west; break;
                       case 20: north1;     break;
                       case 19: north1east; break;
                       case 18: west1north; break;
		       case 17: northwest;  break;
		       case 16: north;      break;
		       case 15: northeast;  break;
		       case 14: west1;      break;
                       case 13: west;       break;
		       case 12: east;       break;
                       case 11: east1;      break;
                       case 10: west2south; break;
                       case 9: west1south;  break;
                       case 8: southwest;   break;
		       case 7: south;       break;
		       case 6: southeast;   break;
		       case 5: east1south;  break;
                       case 4: southwest1;  break;
		       case 3: south1west;  break;
                       case 2: south1;      break;
                       case 1: south1east;  break;
                       case 0: southeast1;
		    }
                 }
                 else{  /*even*/
		    switch(wire){
                       case 23: north2;     break;
                       case 22: north2east; break;
                       case 21: north1west; break;
                       case 20: north1;     break;
                       case 19: north1east; break;
                       case 18: northwest;  break;
		       case 17: north;      break;
		       case 16: northeast;  break;
		       case 15: east1north; break;
		       case 14: west1;      break;
                       case 13: west;       break;
		       case 12: east;       break;
                       case 11: east1;      break;
                       case 10: west1south; break;
                       case 9: southwest;   break;
                       case 8: south;       break;
		       case 7: southeast;   break;
		       case 6: east1south;  break;
		       case 5: east2south;  break;
                       case 4: southwest1;  break;
		       case 3: south1west;  break;
                       case 2: south1;      break;
                       case 1: south1east;  break;
                       case 0: southeast1;
		    }
                 }
	      }

              /* square grid nhood=25
              24 23 22 21 20
              19 18 17 16 15
              14 13 12 11 10  
               9  8  7  6  5
               4  3  2  1  0 */
              else if (nhoodm[poss]==25 && hex2d==0){
		    switch(wire){
		       case 24: northwest1; break;
                       case 23: north1west; break;
		       case 22: north1;     break;
		       case 21: north1east; break;
		       case 20: northeast1; break;
                       case 19: west1north; break;
		       case 18: northwest;  break;
		       case 17: north;      break;
                       case 16: northeast;  break;
                       case 15: east1north; break;
                       case 14: west1;      break;
                       case 13: west;       break;
                       case 12: centre;
                               ccel=1;      break;
                       case 11: east;       break;
                       case 10: east1;      break;
                       case 9: west1south;  break;
                       case 8: southwest;   break;
                       case 7: south;       break;
		       case 6: southeast;   break;
		       case 5: east1south;  break;
		       case 4: southwest1;  break;
		       case 3: south1west;  break;
		       case 2: south1;      break;
                       case 1: south1east;  break;
                       case 0: southeast1;
		    }
	      }
              /* hex grid, nhood=25
                          
                     24  23                     24  23 
                     22  21  20             22  21  20
                 19  18  17  16             19  18  17  16 
     odd rows..  15  14  13  12  11     15  14  13  12  11  ..even rows
             10   9   8   7   6   5     10   9   8   7   6   5 
                  4   3   2   1   0      4   3   2   1   0 
                    
                       24  23 
                     22  21  20
                   19  18  17  16
                 15  14  13  12  11
               10   9   8   7   6   5   
                  4   3   2   1   0
                          */

	      else if (nhoodm[poss]==25 && hex2d==1){
                 if ((jj+1)%2==0){  /*odd*/
		    switch(wire){
                       case 24: north2west; break;
                       case 23: north2;     break;
                       case 22: north1west; break;
                       case 21: north1;     break;
                       case 20: north1east; break;
                       case 19: west1north; break;
		       case 18: northwest;  break;
		       case 17: north;      break;
		       case 16: northeast;  break;
		       case 15: west1;      break;
                       case 14: west;       break;
                       case 13: centre;
                               ccel=1;      break;
		       case 12: east;       break;
                       case 11: east1;      break;
                       case 10: west2south; break;
                       case 9: west1south;  break;
                       case 8: southwest;   break;
		       case 7: south;       break;
		       case 6: southeast;   break;
		       case 5: east1south;  break;
                       case 4: southwest1;  break;
		       case 3: south1west;  break;
                       case 2: south1;      break;
                       case 1: south1east;  break;
                       case 0: southeast1;
		    }
                 }
                 else{  /*even*/
		    switch(wire){
                       case 24: north2;     break;
                       case 23: north2east; break;
                       case 22: north1west; break;
                       case 21: north1;     break;
                       case 20: north1east; break;
                       case 19: northwest;  break;
		       case 18: north;      break;
		       case 17: northeast;  break;
		       case 16: east1north; break;
		       case 15: west1;      break;
                       case 14: west;       break;
                       case 13: centre;
                               ccel=1;      break;
		       case 12: east;       break;
                       case 11: east1;      break;
                       case 10: west1south; break;
                       case 9: southwest;   break;
                       case 8: south;       break;
		       case 7: southeast;   break;
		       case 6: east1south;  break;
		       case 5: east2south;  break;
                       case 4: southwest1;  break;
		       case 3: south1west;  break;
                       case 2: south1;      break;
                       case 1: south1east;  break;
                       case 0: southeast1;
		    }
                 }
	      }
              /* square grid nhood=26 - no self wiring
              25 24 23 22 21
              20 19 18 17 16
           15 14 13  * 12 11 10  
              9  8   7  6  5
              4  3   2  1  0 */
              else if (nhoodm[poss]==26 && hex2d==0){
		    switch(wire){
		       case 25: northwest1; break;
                       case 24: north1west; break;
		       case 23: north1;     break;
		       case 22: north1east; break;
		       case 21: northeast1; break;
                       case 20: west1north; break;
		       case 19: northwest;  break;
		       case 18: north;      break;
                       case 17: northeast;  break;
                       case 16: east1north; break;
		       case 15: west2;      break;
                       case 14: west1;      break;
                       case 13: west;       break;
                       case 12: east;       break;
                       case 11: east1;      break;
		       case 10: east2;  break; 
                       case 9: west1south;  break;
                       case 8: southwest;   break;
                       case 7: south;       break;
		       case 6: southeast;   break;
		       case 5: east1south;  break;
		       case 4: southwest1;  break;
		       case 3: south1west;  break;
		       case 2: south1;      break;
                       case 1: south1east;  break;
                       case 0: southeast1;
		    }
	      }
              /* square grid nhood=27 - self wiring
              26 25 24 23 22
              21 20 19 18 17
           16 15 14 13 12 11 10  
              9  8   7  6  5
              4  3   2  1  0 */
              else if (nhoodm[poss]==27 && hex2d==0){
		    switch(wire){
		       case 26: northwest1; break;
                       case 25: north1west; break;
		       case 24: north1;     break;
		       case 23: north1east; break;
		       case 22: northeast1; break;
                       case 21: west1north; break;
		       case 20: northwest;  break;
		       case 19: north;      break;
                       case 18: northeast;  break;
                       case 17: east1north; break;
		       case 16: west2;      break;
                       case 15: west1;      break;
                       case 14: west;       break;
                       case 13:centre;
                                 ccel=1;    break;
                       case 12: east;       break;
                       case 11: east1;      break;
		       case 10: east2;      break; 
                       case 9: west1south;  break;
                       case 8: southwest;   break;
                       case 7: south;       break;
		       case 6: southeast;   break;
		       case 5: east1south;  break;
		       case 4: southwest1;  break;
		       case 3: south1west;  break;
		       case 2: south1;      break;
                       case 1: south1east;  break;
                       case 0: southeast1;
		    }
	      }
          }

	  /*--------------------------- k =2 to 27 for 3d -------------------*/
          else if (dim==3){

	      /* 1 * *
	         * * *  (up)
                 * * *

                 * * *
                 * * *  nhood=2 - no self wirin
                 * * *

                 * * *
                 * * *  (down)
                 * * 0  */
              
	      if (nhoodm[poss]==2){
		    switch(wire){
                       case 1: up_northwest;  break;
		       case 0: down_southeast;
		       
		    }		   
	      }

	      /* 2 * *
	         * * *  (up)
                 * * *

                 * * *
                 * 1 *  nhood=3 - self wirin
                 * * *

                 * * *
                 * * *  (down)
                 * * 0  */
              
	      else if (nhoodm[poss]==3){
		    switch(wire){
                       case 2: up_northwest;  break;
		       case 1: centre; 
                               ccel=1;  break;
		       case 0: down_southeast;
		       
		    }		   
	      }
              
              /* 3 * *
	         * * *  (up)
                 * * 2

                 * * *
                 * * *  nhood=4 - no self wirin
                 * * *

                 * * 1
                 * * *  (down) 
                 0 * *  */
              
	      else if (nhoodm[poss]==4){
		    switch(wire){
                       case 3: up_northwest;   break;
		       case 2: up_southeast;   break;
		       case 1: down_northeast; break;
		       case 0: down_southwest;
		       
		    }		   
	      }
       
             /*  4 * *
	         * * *  (up)
                 * * 3

                 * * *
                 * 2 *  nhood=5 - self wirin
                 * * *

                 * * 1
                 * * *  (down)
                 0 * *  */
              
	      else if (nhoodm[poss]==5){
		    switch(wire){
                       case 4: up_northwest;   break;
		       case 3: up_southeast;   break;
                       case 2: centre; 
                               ccel=1;  break;
		       case 1: down_northeast; break;
		       case 0: down_southwest;
		       
		    }		   
	      }
 

              /*      5 (up)
                   4 /
		 3 * 2   ..nhood=6 - no self wiring 
		 / 1   
                0 (down)       */
	      else if (nhoodm[poss]==6){
		    switch(wire){
                       case 5: up;        break;
		       case 4: north;     break;
		       case 3: west;      break;
		       case 2: east       break;
		       case 1: south;     break;
		       case 0: down;
		    }		   
	      }
              /*      6(up)
                   5 /
		 4 3 2   ..nhood=7
		 / 1   
                0 (down)
                        */ 
	      else if (nhoodm[poss]==7){
		    switch(wire){
                       case 6: up;      break;
                       case 5: north;   break;
		       case 4: west;    break;
		       case 3: centre; 
                               ccel=1;  break;
		       case 2: east;    break;
		       case 1: south;   break;
		       case 0: down;
		    }
	      }

              /*      7   (up)
                   6 /  
	       5 4 * 3 2   ..nhood=8 - no self wiring (superseded)
		 / 1   
                0  (down)
                        */ 
              /*  7  *  *
	          *  6  *  (up)
		  *  *  *
 
	          *  5  *
		  4  *  3   ..nhood=8 - no self wiring
		  *  2  *

                  *  *  *                        
                  *  1  *  (down)
                  *  *  0  */  
	      else if (nhoodm[poss]==8){
		    switch(wire){
                       case 7: up_northwest; break;
                       case 6: up;   break;
                       case 5: north;   break;
		       case 4: west;    break;
		       case 3: east;    break;
		       case 2: south;   break;
		       case 1: down;   break;
		       case 0: down_southeast;
		    }
	      }
	      
             /*       8 (up)
                   7 /
	       6 5 4 3 2   ..the nhood=9 (superseded)
	         / 1   
                0  (down)
                        */
              /*  8  *  *
	          *  7  *  (up)
		  *  *  *
 
	          *  6  *
		  5  4  3   ..nhood=9 - self wiring
		  *  2  *

                  *  *  *                        
                  *  1  *  (down)
                  *  *  0  */  
	      else if (nhoodm[poss]==9){
		    switch(wire){
                       case 8: up_northwest;   break;
                       case 7: up;  break;
                       case 6: north;  break;
                       case 5: west;   break;
		       case 4: centre; 
                               ccel=1; break;
		       case 3: east;   break;
		       case 2: south;  break;
		       case 1: down;  break;
		       case 0: down_southeast;
		    }
	      } 

              /*      9 (up)
                     /
	         8 7 6
		 5 * 4   ..nhood=10 - no self wiring (superdeded)
		 3 2 1                        
                 /        
                0 (down)*/

              /*  9  *  *
	          *  8  *  (up)
		  *  *  7
 
	          *  6  *
		  5  *  4   ..nhood=10 - no self wiring
		  *  3  *

                  *  *  2                        
                  *  1  *  (down)
                  0  *  *  */ 
	      else if (nhoodm[poss]==10){
		    switch(wire){
                       case 9: up_northwest; break;
		       case 8: up; break;
		       case 7: up_southeast; break;
		       case 6: north; break;
		       case 5: west;      break;
		       case 4: east       break;
		       case 3: south; break;
		       case 2: down_northeast; break;
		       case 1: down; break;
		       case 0: down_southwest;
		    }
	      }
              /*      10(up)
                     /
	         9 8 7
		 6 5 4   ..the nhood=11 (superseded)
		 3 2 1   
                 /        
                0 (down)           */

              /*  10  *  *
	          *  9  *  (up)
		  *  *  8
 
	          *  7  *
		  6  5  4   ..nhood=11 - self wiring
		  *  3  *

                  *  *  2                        
                  *  1  *  (down)
                  0  *  *  */ 
	      else if (nhoodm[poss]==11){
		    switch(wire){
                       case 10:up_northwest;     break;
		       case 9: up; break;
		       case 8: up_southeast;     break;
		       case 7: north; break;
		       case 6: west;      break;
		       case 5: centre;
                               ccel=1;    break;
		       case 4: east;      break;
		       case 3: south; break;
		       case 2: down_northeast;     break;
		       case 1: down; break;
                       case 0: down_southwest;        
		    }                    
	      }
              /*        11 (up)
                       /
                   9  10
	           8 /
	       7 6 * 5 4  ..the nhood - no self wiring  (superceded)
		 / 3
                1  2    
               /           
              0 (down)       */

               /* 11 * 10
	          *  *  *  (up)
		  9  *  8
 
	          *  7  *
		  6  *  5   ..nhood=12 - no self wiring
		  *  4  *

                  3  *  2                        
                  *  *  *  (down)
                  1  *  0  */
 
	      else if (nhoodm[poss]==12){
		    switch(wire){
                       case 11:up_northwest;  break;
                       case 10:up_northeast;      break;
                       case 9: up_southwest;  break;
		       case 8: up_southeast;   break;
		       case 7: north;   break;
		       case 6: west;    break;
		       case 5: east;    break;
		       case 4: south;   break;
		       case 3: down_northwest;   break;
		       case 2: down_northeast;  break;
		       case 1: down_southwest;    break;
		       case 0: down_southeast;
		    }
	      }          
              /*        12 (up)
                       /
                  10  11
	           9 /
	       8 7 6 5 4   ..the nhood (superceded)
		 / 3
                1  2    
               /           
              0 (down)       */

               /* 12 * 11
	          *  *  *  (up)
		  10 *  9
 
	          *  8  *
		  7  6  5   ..nhood=13 - self wiring
		  *  4  *

                  3  *  2                        
                  *  *  *  (down)
                  1  *  0  */

	      else if (nhoodm[poss]==13){
		    switch(wire){
                       case 12:up_northwest;    break;
                       case 11:up_northeast;    break;
                       case 10:up_southwest;    break;
                       case 9: up_southeast;    break;
		       case 8: north;     break;
		       case 7: west;      break;
		       case 6: centre;
                               ccel=1;    break;
		       case 5: east;      break;
		       case 4: south;     break;
		       case 3: down_northwest;  break;
		       case 2: down_northeast;  break;
		       case 1: down_southwest;      break;
		       case 0: down_southeast;
		    }
	      }
              /*  * 13  *
                 12  * 11  (up)
		  * 10  *
 
	          9  *  8
		  7  *  6   ..nhood=14 - no self wiring
		  5  *  4

                  *  3  *                        
                  2  *  1  (down)
                  *  0  *  */    

              else if (nhoodm[poss]==14){
		    switch(wire){
                       case 13: up_north;  break;
		       case 12: up_west;   break;
		       case 11: up_east;   break; 
		       case 10: up_south;  break;
		       case 9: northwest;  break;
		       case 8: northeast;  break;
		       case 7: west;       break;
		       case 6: east;       break;
		       case 5: southwest;  break;
		       case 4: southeast;  break;
		       case 3: down_north; break;
		       case 2: down_west;  break;
		       case 1: down_east;  break;
		       case 0: down_south;
		    }
	      }
              /*  * 14  *
                 13  * 12  (up)
		  * 11  *
 
	         10  *  9
		  8  7  6   ..nhood=15 - self wiring
		  5  *  4

                  *  3  *                        
                  2  *  1  (down)
                  *  0  *  */    

              else if (nhoodm[poss]==15){
		    switch(wire){
                       case 14: up_north;  break;
		       case 13: up_west;   break;
		       case 12: up_east;   break; 
		       case 11: up_south;  break;
		       case 10: northwest; break;
		       case 9: northeast;  break;
		       case 8: west;       break;
		       case 7: centre; 
                               ccel=1;     break;
		       case 6: east;       break;
		       case 5: southwest;  break;
		       case 4: southeast;  break;
		       case 3: down_north; break;
		       case 2: down_west;  break;
		       case 1: down_east;  break;
		       case 0: down_south;
		    }
	      }
              /*  * 15  *
                 14  * 13  (up)
		  * 12  *
 
	         11 10  9
		  8  *  7   ..nhood=16 - no self wiring
		  6  5  4

                  *  3  *                        
                  2  *  1  (down)
                  *  0  *  */    

              else if (nhoodm[poss]==16){
		    switch(wire){
                       case 15: up_north;  break;
		       case 14: up_west;   break;
		       case 13: up_east;   break; 
		       case 12: up_south;  break;
		       case 11: northwest; break;
		       case 10: north;     break;
		       case 9: northeast;  break;
		       case 8: west;       break;
		       case 7: east;       break;
		       case 6: southwest;  break;
		       case 5: south;      break;
		       case 4: southeast;  break;
		       case 3: down_north; break;
		       case 2: down_west;  break;
		       case 1: down_east;  break;
		       case 0: down_south;
		    }
	      }
              /*  * 16  *
                 15  * 14  (up)
		  * 13  *
 
	         12 11 10
		  9  8  7   ..nhood=17 - self wiring
		  6  5  4

                  *  3  *                        
                  2  *  1  (down)
                  *  0  *  */    

              else if (nhoodm[poss]==17){
		    switch(wire){
                       case 16: up_north;  break;
		       case 15: up_west;   break;
		       case 14: up_east;   break; 
		       case 13: up_south;  break;
		       case 12: northwest; break;
		       case 11: north;     break;
		       case 10: northeast; break;
		       case 9: west;       break;
                       case 8: centre; 
                               ccel=1;     break;
		       case 7: east;       break;
		       case 6: southwest;  break;
		       case 5: south;      break;
		       case 4: southeast;  break;
		       case 3: down_north; break;
		       case 2: down_west;  break;
		       case 1: down_east;  break;
		       case 0: down_south;
		    }
	      }
              /*  * 17  *
                 16 15 14  (up)
		  * 13  *
 
	         12 11 10
		  9  *  8   ..nhood=18 - no self wiring
		  7  6  5

                  *  4  *                        
                  3  2  1  (down)
                  *  0  *  */    

              else if (nhoodm[poss]==18){
		    switch(wire){
                       case 17: up_north;  break;
		       case 16: up_west;   break;
		       case 15: up;        break;
		       case 14: up_east;   break; 
		       case 13: up_south;  break;
		       case 12: northwest; break;
		       case 11: north;     break;
		       case 10: northeast; break;
		       case 9: west;       break;
		       case 8: east;       break;
		       case 7: southwest;  break;
		       case 6: south;      break;
		       case 5: southeast;  break;
		       case 4: down_north; break;
		       case 3: down_west;  break;
		       case 2: down;       break;
		       case 1: down_east;  break;
		       case 0: down_south;
		    }
	      }
              /*  * 18  *
                 17 16 15  (up)
		  * 14  *
 
	         13 12 11
		 10  9  8   ..nhood=19 - self wiring
		  7  6  5

                  *  4  *                        
                  3  2  1  (down)
                  *  0  *  */    

              else if (nhoodm[poss]==19){
		    switch(wire){
                       case 18: up_north;  break;
		       case 17: up_west;   break;
		       case 16: up;        break;
		       case 15: up_east;   break; 
		       case 14: up_south;  break;
		       case 13: northwest; break;
		       case 12: north;     break;
		       case 11: northeast; break;
		       case 10: west;      break;
		       case 9: centre; 
			          ccel=1;  break;
		       case 8: east;       break;
		       case 7: southwest;  break;
		       case 6: south;      break;
		       case 5: southeast;  break;
		       case 4: down_north; break;
		       case 3: down_west;  break;
		       case 2: down;       break;
		       case 1: down_east;  break;
		       case 0: down_south;
		    }
	      }
              /* 19 18  *
                 17 16 15  (up)
		  * 14  *
 
	         13 12 11
		 10  *  9   ..nhood=20 - no self wiring
		  8  7  6

                  *  5  *                        
                  4  3  2  (down)
                  *  1  0  */    

              else if (nhoodm[poss]==20){
		    switch(wire){
                       case 19: up_northwest;  break;
                       case 18: up_north;  break;
		       case 17: up_west;   break;
		       case 16: up;        break;
		       case 15: up_east;   break; 
		       case 14: up_south;  break;
		       case 13: northwest; break;
		       case 12: north;     break;
		       case 11: northeast; break;
		       case 10: west;      break;
		       case 9: east;       break;
		       case 8: southwest;  break;
		       case 7: south;      break;
		       case 6: southeast;  break;
		       case 5: down_north; break;
		       case 4: down_west;  break;
		       case 3: down;       break;
		       case 2: down_east;  break;
		       case 1: down_south; break;
                       case 0: down_southeast;
		    }
	      }

              /* 20 19  *
                 18 17 16  (up)
		  * 15  *
 
	         14 13 12
		 11 10  9 ..nhood=21 - self wiring
		  8  7  6

                  *  5  *                        
                  4  3  2  (down)
                  *  1  0  */    

              else if (nhoodm[poss]==21){
		    switch(wire){
                       case 20: up_northwest;  break;
                       case 19: up_north;  break;
		       case 18: up_west;   break;
		       case 17: up;        break;
		       case 16: up_east;   break; 
		       case 15: up_south;  break;
		       case 14: northwest; break;
		       case 13: north;     break;
		       case 12: northeast; break;
		       case 11: west;      break;
		       case 10: centre; 
			        ccel=1;    break;
		       case 9: east;       break;
		       case 8: southwest;  break;
		       case 7: south;      break;
		       case 6: southeast;  break;
		       case 5: down_north; break;
		       case 4: down_west;  break;
		       case 3: down;       break;
		       case 2: down_east;  break;
		       case 1: down_south; break;
                       case 0: down_southeast;
		    }
	      }

              /* 21 20  *
                 19 18 17  (up)
		  * 16 15
 
	         14 13 12
		 11  * 10 ..nhood=22 - no self wiring
		  9  8  7

                  6  5  *                        
                  4  3  2  (down)
                  *  1  0  */    

              else if (nhoodm[poss]==22){
		    switch(wire){
                       case 21: up_northwest;  break;
                       case 20: up_north;  break;
		       case 19: up_west;   break;
		       case 18: up;        break;
		       case 17: up_east;   break; 
		       case 16: up_south;  break;
		       case 15: up_southeast; break;
		       case 14: northwest; break;
		       case 13: north;     break;
		       case 12: northeast; break;
		       case 11: west;      break;
		       case 10: east;      break;
		       case 9: southwest;  break;
		       case 8: south;      break;
		       case 7: southeast;  break;
		       case 6: down_northwest;  break;
		       case 5: down_north; break;
		       case 4: down_west;  break;
		       case 3: down;       break;
		       case 2: down_east;  break;
		       case 1: down_south; break;
                       case 0: down_southeast;
		    }
	      }
              /* 22 21  *
                 20 19 18  (up)
		  * 17 16
 
	         15 14 13
		 12 11 10 ..nhood=23 - self wiring
		  9  8  7

                  6  5  *                        
                  4  3  2  (down)
                  *  1  0  */    

              else if (nhoodm[poss]==23){
		    switch(wire){
                       case 22: up_northwest;  break;
                       case 21: up_north;  break;
		       case 20: up_west;   break;
		       case 19: up;        break;
		       case 18: up_east;   break; 
		       case 17: up_south;  break;
		       case 16: up_southeast; break;
		       case 15: northwest; break;
		       case 14: north;     break;
		       case 13: northeast; break;
		       case 12: west;      break;
		       case 11: centre; 
			        ccel=1;    break;
		       case 10: east;      break;
		       case 9: southwest;  break;
		       case 8: south;      break;
		       case 7: southeast;  break;
		       case 6: down_northwest;  break;
		       case 5: down_north; break;
		       case 4: down_west;  break;
		       case 3: down;       break;
		       case 2: down_east;  break;
		       case 1: down_south; break;
                       case 0: down_southeast;
		    }
	      }
              /* 23 22 21
                 20 19 18  (up)
		  * 17 16
 
	         15 14 13
		 12  * 11 ..nhood=24 - no self wiring
		 10  9  8

                  7  6  *                        
                  5  4  3  (down)
                  2  1  0  */    

              else if (nhoodm[poss]==24){
		    switch(wire){
                       case 23: up_northwest;  break;
                       case 22: up_north;  break;
		       case 21: up_northeast;   break;
		       case 20: up_west;   break;
		       case 19: up;        break;
		       case 18: up_east;   break; 
		       case 17: up_south;  break;
		       case 16: up_southeast; break;
		       case 15: northwest; break;
		       case 14: north;     break;
		       case 13: northeast; break;
		       case 12: west;      break;
		       case 11: east;      break;
		       case 10: southwest;  break;
		       case 9: south;      break;
		       case 8: southeast;  break;
		       case 7: down_northwest;  break;
		       case 6: down_north; break;
		       case 5: down_west;  break;
		       case 4: down;       break;
		       case 3: down_east;  break;                       
		       case 2: down_southwest;  break;
                       case 1: down_south; break;
                       case 0: down_southeast;
		    }
	      }
              /* 24 23 22
                 21 20 19  (up)
		  * 18 17
 
	         16 15 14
		 13 12 11 ..nhood=25 - self wiring
		 10  9  8

                  7  6  *                        
                  5  4  3  (down)
                  2  1  0  */    

              else if (nhoodm[poss]==25){
		    switch(wire){
                       case 24: up_northwest;  break;
                       case 23: up_north;  break;
		       case 22: up_northeast;   break;
		       case 21: up_west;   break;
		       case 20: up;        break;
		       case 19: up_east;   break; 
		       case 18: up_south;  break;
		       case 17: up_southeast; break;
		       case 16: northwest; break;
		       case 15: north;     break;
		       case 14: northeast; break;
		       case 13: west;      break;
		       case 12: centre; 
			        ccel=1;    break;
		       case 11: east;      break;
		       case 10: southwest;  break;
		       case 9: south;      break;
		       case 8: southeast;  break;
		       case 7: down_northwest;  break;
		       case 6: down_north; break;
		       case 5: down_west;  break;
		       case 4: down;       break;
		       case 3: down_east;  break;                       
		       case 2: down_southwest;  break;
                       case 1: down_south; break;
                       case 0: down_southeast;
		    }
	      }
              /* 25 24 23
                 22 21 20  (up)
		 19 18 17
 
	         16 15 14
		 13  * 12 ..nhood=26 - no self wiring
		 11 10  9

                  8  7  6                        
                  5  4  3  (down)
                  2  1  0  */    

              else if (nhoodm[poss]==26){
		    switch(wire){
                       case 25: up_northwest;  break;
                       case 24: up_north;  break;
		       case 23: up_northeast;   break;
		       case 22: up_west;   break;
		       case 21: up;        break;
		       case 20: up_east;   break;
		       case 19: up_southwest; break;
		       case 18: up_south;  break;
		       case 17: up_southeast; break;
		       case 16: northwest; break;
		       case 15: north;     break;
		       case 14: northeast; break;
		       case 13: west;      break;
		       case 12: east;      break;
		       case 11: southwest;  break;
		       case 10: south;      break;
		       case 9: southeast;  break;
		       case 8: down_northwest;  break;
		       case 7: down_north; break;
		       case 6: down_northeast;  break;
		       case 5: down_west; break;
		       case 4: down;       break;
		       case 3: down_east;  break;                       
		       case 2: down_southwest;  break;
                       case 1: down_south; break;
                       case 0: down_southeast;
		    }
	      }
              /* 26 25 24
                 23 22 21  (up)
		 20 19 18
 
	         17 16 15
		 14 13 12 ..nhood=27 - self wiring
		 11 10  9

                  8  7  6                        
                  5  4  3  (down)
                  2  1  0  */    

              else if (nhoodm[poss]==27){
		    switch(wire){
                       case 26: up_northwest;  break;
                       case 25: up_north;  break;
		       case 24: up_northeast;   break;
		       case 23: up_west;   break;
		       case 22: up;        break;
		       case 21: up_east;   break;
		       case 20: up_southwest; break;
		       case 19: up_south;  break;
		       case 18: up_southeast; break;
		       case 17: northwest; break;
		       case 16: north;     break;
		       case 15: northeast; break;
		       case 14: west;      break;
		       case 13: centre; 
			        ccel=1;    break;
		       case 12: east;      break;
		       case 11: southwest;  break;
		       case 10: south;      break;
		       case 9: southeast;  break;
		       case 8: down_northwest;  break;
		       case 7: down_north; break;
		       case 6: down_northeast;  break;
		       case 5: down_west; break;
		       case 4: down;       break;
		       case 3: down_east;  break;                       
		       case 2: down_southwest;  break;
                       case 1: down_south; break;
                       case 0: down_southeast;
		    }
	      }
	  } /*(dim==3)*/
                   
          if (dim==2) poss_n=i2d*j_n + i_n;           
          else if (dim==3){ 
             poss_n=(i3d*j3d*h_n) + (i3d*j_n) + i_n;             
             j2d=temp_j2d; /*restore j2d*/
          }
          return ccel;
}

/***************** show wiring/rule scheme, Dec 93 *********************/
void show_w_r_scheme(void){
 signed int tempx,tempy,xbox;
 char thisdim,print_xterm,temp_font;

    erase_memory_box(2); //to erase memory_box while backtracking
 
   setcolor(white);
   tempx=getx;
   tempy=gety;
   small_font=0; /*for wiring_matrix 'M' and 'm'*/
   temp_font=font_d_m_s; /*keep track of font: d=default, m=medium, s=small*/
    if (temp_font!='d') restore_def_font(); 

   if (rulemix==0 && rules_set){      
      if (tot_only==0) show_rule_bottom(nhood,0,carule[0],0);
      else{
         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);
      }
   }
 start:
   print_xterm=0;
   if (oned){ 
      thisdim=1;
      sprintf(textb[1],"n=%d",lineL);
   }
   else if (twod){
      thisdim=2;
      if (hex2d==1) sprintf(textb[1],"%dx%d hex",i2d,j2d);
      else sprintf(textb[1],"%dx%d",i2d,j2d);
   }
   else if (threed){
      thisdim=3;
      sprintf(textb[1],"%dx%dx%d",i3d,j3d,h3d);
   }
   get_prompt_box(2,3);
   xbox=draw_prompt_box(3);
   if (totalistic==0 && tot_only==0) sprintf(textb[2],"rcode");
   else{ 
      if (totalistic==1) sprintf(textb[2],"tcode");
      else if (totalistic==2) sprintf(textb[2],"kcode");
   }
   if (rules_set) sprintf(textb[0],
      "%dd network (%s), review/revise/learn, wiring and %s"
                         ,thisdim,textb[1],textb[2]);
   else sprintf(textb[0],
      "%dd network (%s), review/revise, wiring only - rules not set"
                        ,thisdim,textb[1]);
   outtext(textb[0]);
   moveto(xbox,gety+CHeight);

#  if __WATCOM__	
      sprintf(textb[0],"graph-g, matrix: revise-m view-M");
#  elif __UNIX__
      sprintf(textb[0],"graph-g, matrix: revise-m view-M prtx-Mp");
#  endif
   outtext(textb[0]);
   moveto(xbox,gety+CHeight);
   
   if (threed) outtext("graphic: 1d+timestep-1 circle-c 2d+3d-3:");
   else outtext("graphic: 1d+timestep-1 circle-c 2d-2:");
      
   input_string(2,0);   
   uncover_free_prompt_box(2);
   if (is[0]=='q' || is[0]==13) return;
   
   cell_out_freq();
   if (is[0]=='2' || (is[0]=='3' && threed))
                        show_graphic_wiring_2d_3d(rules_set);
   else if (is[0]=='1') show_graphic_wiring_1d(1,rules_set);
   else if (is[0]=='c') show_graphic_wiring_1d(2,rules_set);

   else if (is[0]=='m'){
       whatwire=3;
       nonlocal=1;
       compress_1d_local=0;
       wiring_matrix();
   } 
   else if (is[0]=='M'){
       if (is[1]=='p') print_xterm=1;
       print_wiring_scheme(0,0,0,lineL-1,print_xterm);
   }


   else if (is[0]=='g') jump_graph_table(0,NULL,'n'); 
   if (is[0]=='q') goto start;

   if (temp_font=='s') set_small_font();
   else if (temp_font=='m') set_medium_font();            
   moveto(tempx,tempy);
}

/******* seperate function to save/load/print network architecture ******/
char save_load_print_net(void){
 signed int tempx,tempy,wire,xbox,z;
 unsigned int poss;
 unsigned long toutwires;
 char was_loaded,thispdata,thisfiledata,
      wrstype;
    /*rule=0,wiring scheme=1,rule scheme=2,rule/scheme scheme=3,seed='s'*/
 float tlratio,tzparam,wtlratio,wtzparam,weight;
 signed int fid;
 char post=0;

   /*only a combined rulemix+wiring file can be loaded into a 
     mixed k network, and only after rules have been set.
     Filing option for rules are n/a (non-applicable) before rule are set.*/

   /*revised - a wiring sceme only CAN be loaded*/

   /*
   wrstype==0 "SINGLE RULE"
   wrstype==1 "WIRING ONLY"
   wrstype==2 "RULE SCHEME ONLY"
   wrstype==3 "WIRING-RULE SCHEME"
   */

   tempx=getx;
   tempy=gety;
  
  start1:
   if (1){
      if (rules_set==0){
         if (nhood_mixed) sprintf(textb[3],
                 "k-mix, no rules, save/load/print: save kmix-k");
         else sprintf(textb[3],
                 "k-hom, no rules, save/load/print:");
	 sprintf(textb[0],"wiring-only: print-pw, load-lw, save-sw");
         sprintf(textb[1],"rulemix-only: n/a");
	 sprintf(textb[2],"rulemix+wiring: n/a:");
      }
      else if (rules_set &&  rulemix==1 && nhood_mixed==0){
         sprintf(textb[3],"k-hom, rulemix, save/load/print:");
	 sprintf(textb[0],"wiring-only: print-pw, load-lw, save-sw,");
	 sprintf(textb[1],"rulemix-only: print-pr, load-lr, save-sr,");
	 sprintf(textb[2],"rulemix+wiring: print-pb, load-lb, save-sb:");
      }
 
      else if (rules_set &&  rulemix==1 && nhood_mixed==1){
         sprintf(textb[3],"k-mix, rulemix, save/load/print: save kmix-k");
	 sprintf(textb[0],"wiring-only: print-pw, load-lw, save-sw,");
         sprintf(textb[1],"rulemix-only: n/a");
	 sprintf(textb[2],"rulemix+wiring: print-pb, load-lb, save-sb:");
      }

      else{
         if (nhood_mixed==1) sprintf(textb[4],"%s","k-mix");
         else sprintf(textb[4],"%s","k-hom");
         if (rulemix==1) sprintf(textb[5],"%s","rulemix");
         else sprintf(textb[5],"%s","no rulemix");
         sprintf(textb[3],"%s, %s, save/load/print: save kmix-k",textb[4],textb[5]);
	 sprintf(textb[0],"wiring-only: print-pw, load-lw, save-sw:");
         sprintf(textb[1],"rulemix-only: n/a");
	 sprintf(textb[2],"rulemix+wiring:  n/a:");
      }
      get_prompt_box(2,4);
      xbox=draw_prompt_box(4);
      outtext(textb[3]);
      moveto(xbox,gety+CHeight);  
      outtext(textb[0]);
      moveto(xbox,gety+CHeight);
      outtext(textb[1]);
      moveto(xbox,gety+CHeight);
      outtext(textb[2]);
      input_string(2,0);
      
      uncover_free_prompt_box(2);
      /*if (is[0]=='q') goto start;*/
      if (is[0]=='q'){
         erase_prompt_box(1);
         moveto(tempx,tempy);
         return(0);
      }
      was_loaded=0;
      /*save the k-mix*/
      if (nhood_mixed && is[0]=='k'){
         load_save_nhoodmix('s');
         goto start1;
      }      

      if (is[0]=='p' || is[0]=='l' || is[0]=='s'){
         if (rules_set==0 || rulemix==0)  wrstype=1; 
	 else if (rules_set &&  rulemix==1 && nhood_mixed==0){
	    wrstype=1;
	    if (is[1]=='w') wrstype=1;
	    if (is[1]=='r') wrstype=2;
	    if (is[1]=='b') wrstype=3;
	 }
      else if (rules_set &&  rulemix==1 && nhood_mixed==1){
            wrstype=1;
	    if (is[1]=='w') wrstype=1;
	    if (is[1]=='b') wrstype=3;
	 }
      }
      if (is[0]=='l' && basin_not_complete==0){ /*not while basin interupted*/ 
         was_loaded=load_save_wrs('l',NULL,wrstype);
         if (was_loaded>-1 && was_loaded!=0){ /*if error was_loaded can be -1 or 0 ??*/
	    was_changed=1;
	    cell_out_freq();
         }
         else was_loaded=0; /*return at end of function*/
      }
      else if (is[0]=='s') load_save_wrs('s',NULL,wrstype);
      else if (is[0]=='p'){
	start2:
#        if __WATCOM__ 
	    sprintf(textb[0],"network text data: to printer-p save-s both-b: ");
#        elif __UNIX__
            sprintf(textb[0],"network text data: to xterm-p save-s both-b: ");
#        endif 
	 get_prompt_box(2,1);
	 draw_prompt_box(1);
	 outtext(textb[0]);
	 input_string(1,0);
         uncover_free_prompt_box(2);
	 if (is[0]=='q') goto start1;
	 thispdata=pdata;
	 filedata=thisfiledata;
	 pdata=filedata=0;
	 if (is[0]=='p') pdata=1;
	 else if (is[0]=='s') filedata=1;
	 else if (is[0]=='b'){
	    pdata=1;
	    filedata=1;
	 }
	 if (filedata){
	    file_ret_w=select_filename("SAVE","DATA","*.dat","my_net");
	    if (file_ret_w=='q') goto start2;
	    memmove(filename_data,filename,13);

	    fid=myopen(filename_data,1,0);
	   
	    if (fid==-1){
               file_error(filename);
               draw_prompt_box(1);
	       outtext(textb[0]);
	       input_string(1,0);
	       erase_prompt_box(1);	    
	    }
	    close(fid);
	 }
	 cell_out_freq();
	 toutwires=0;
	 if (nhood_mixed){
	    for (poss=lineL-1;poss!=Maxu;poss--) toutwires+=nhoodm[poss];
	 }
	 else toutwires+=lineL*nhood;
	 tlratio=tzparam=wtlratio=wtzparam=0;

#        if __WATCOM__	 
            if (pdata){
	       prn_putc(ESC); /*initialise printer*/
	       prn_putc('@');
	    }
#        endif
	 
         if (nhood_mixed) sprintf(textb[1],
	  "\nv%dkmix(%d-%d),",value_range,nhood,nhood_lb);
	 else sprintf(textb[1],"\nv%dk%d,",value_range,nhood);
         if (oned) sprintf(textb[2], "1d n=%d",lineL);
         else if (twod) sprintf(textb[2], "2d %dx%d n=%d",i2d,j2d,lineL); 
         else if (threed) sprintf(textb[2], "3d %dx%dx%d n=%d",i3d,j3d,h3d,lineL); 
         sprintf(textb[0],"%s %s",textb[1],textb[2]);
          
	 if (pdata){
	    print_out(textb[0]);
	    print_out("\n");
	 }
	 if (filedata){
	    save_data(textb[0]);
	    save_data("\n");
	 }         

         if (tot_only==0){
             if (totalistic==0) sprintf(textb[1],"rcode(hex)");
             else if (totalistic==1) sprintf(textb[1],"tcode(hex) rcode(hex)");
             else if (totalistic==2) sprintf(textb[1],"kcode(hex) rcode(hex)");
             sprintf(textb[2]," ld ld-r Z C A");
         }
         else if (tot_only==1){
             if (totalistic==1) sprintf(textb[1],"tcode(hex)");
             else if (totalistic==2) sprintf(textb[1],"kcode(hex)");
             sprintf(textb[2],"");
         }

	 if (nhood_mixed){ /* -- shows each k*/
	    if (wrstype==1) sprintf(textb[0],"cell. k, wiring(%d-0),",nhood-1);
	    if (wrstype==2) sprintf(textb[0],"cell. k, %s %s", textb[1],textb[2]);
	    if (wrstype==3) sprintf(textb[0],"cell. k, wiring(%d-0), %s %s",nhood-1,textb[1],textb[2]);
	 }
	 else{ /* -- k omitted*/
	    if (wrstype==1) sprintf(textb[0],"cell. wiring(%d-0),",nhood-1);
	    if (wrstype==2) sprintf(textb[0],"cell. %s %s", textb[1],textb[2]);
	    if (wrstype==3) sprintf(textb[0],"cell. wiring(%d-0), %s %s",nhood-1,textb[1],textb[2]);
            
	 }
	 if (pdata){
	    print_out(textb[0]);
	    print_out("\n");
	    print_out("---------------------------------------------");
	    print_out("\n");
	 }
	 if (filedata){
	    save_data(textb[0]);
	    save_data("\n");
	    save_data("---------------------------------------------");
	    save_data("\n");
	 }
	 for (poss=lineL-1;poss!=Maxu;poss--){
	    post=0;
	    if( (is[0]=keycheck(0))=='q') break; /*abort printing */
	    if (nhood_mixed) sprintf(textb[0],"%d. %d, ",poss,nhoodm[poss]);
	    else sprintf(textb[0],"%d. ",poss);

	    if (pdata) print_out(textb[0]);
	    if (filedata) save_data(textb[0]);

	    /*wiring*/
	    if (wrstype==3 || wrstype==1){
	       for (wire=nhood-1;wire>=0;wire--){
		  if (wire>nhoodm[poss]-1) sprintf(textb[0],"- ");
		  else{
		     if (wire==0) sprintf(textb[0],
					   "%d, ",wiring[poss][wire]);
		     else sprintf(textb[0],"%d ",wiring[poss][wire]);
		  }
		  if (pdata) print_out(textb[0]);
		  if (filedata) save_data(textb[0]);
	       }
	       if (wrstype==1){
		  if (pdata) print_out("\n");
		  if (filedata) save_data("\n");
	       }
	    }

	    /*rule*/
            if (wrstype==3 || wrstype==2){ /*includes rules*/
	       if (totalistic){
		  if (totalistic==1) 
                     print_current_bitstring_hexbytes(2,2,cacode[poss],nhoodm[poss],Maxx,white,3);
		  else if (totalistic==2) 
                      print_current_bitstring_hexbytes(2,2,v_code[poss],nhoodm[poss],Maxx,white,3);
                  if (tot_only==0){ /*leave a gap before rcode*/
                     if (pdata) print_out(" ");
                     if (filedata) save_data(" ");
                  }
	       }
               if (tot_only==1){
                 if (pdata) print_out("\n");
		 if (filedata) save_data("\n");
                 continue;
               }

               print_current_bitstring_hexbytes(2,1,carule[poss],nhoodm[poss],Maxx,white,3);
	       if (value_range==2) z_parameter_all(nhoodm[poss],0,carule[poss]);
               else z_parameter_all_mvalue(nhoodm[poss],0,carule[poss]);
               
	       if (!rulemix && poss==0)
		   sprintf(textb[0],
		      "ld=%.3g ld-r=%.3g Z=%.3g",lambda,lratio,zparam[0]);
	       else sprintf(textb[0],
		      " %.3g %.3g %.3g ",lambda,lratio,zparam[0]);
	       if (pdata) print_out(textb[0]);
	       if (filedata) save_data(textb[0]);

	       tlratio+=lratio;
	       tzparam+=zparam[0];
	       weight=(float)celloutfreq[poss]/toutwires;
	       wtlratio+=lratio*weight;
	       wtzparam+=zparam[0]*weight;

	       /*show canalyzing inputs*/
	       canalyzing(nhoodm[poss],0,carule[poss]);
	       sprintf(textb[0],"%d/%d",canaltotal,nhoodm[poss]);
	       if (canaltotal && nhoodm[poss]>1){
		  memmove(textb[0]+3," ",1);
		  for (z=nhoodm[poss]-1;z>=0;z--){
		     if (get_bit(canal,z)==1){
			   sprintf(textb[1],"%d",z);
			   memmove(textb[0]+4+nhoodm[poss]-1-z,textb[1],1);
		     }
		     else memmove(textb[0]+4+nhoodm[poss]-1-z,"*",1);
		  }
	       }
	       memmove(textb[0]+4+nhoodm[poss],"",1);
               if (pdata) print_out(textb[0]);
	       if (filedata) save_data(textb[0]);

               /*post functions*/
               if (pdata && !filedata) /*just print*/
                      post=post_func(nhoodm[poss],carule[poss],2,0,0,0);
               else if (pdata && filedata) /*print and save*/
                      post=post_func(nhoodm[poss],carule[poss],2,0,fid,1);
	       else if (filedata) /*just save*/
                      post=post_func(nhoodm[poss],carule[poss],2,0,fid,2);
               if (post==0){
                   if (pdata) print_out(" 0");
	           if (filedata) save_data(" 0");
               }
               if (pdata) print_out("\n");
	       if (filedata) save_data("\n");
	    }
	 }
	 if (tot_only==0 && (wrstype==3 || wrstype==2)){
	    tlratio=tlratio/lineL;
	    tzparam=tzparam/lineL;
	    sprintf(textb[0],"average:ld-r=%g Z=%g",tlratio,tzparam);
	    if (pdata){
	       print_out(textb[0]);
	       print_out("\n");
	    }
	    if (filedata){
	       save_data(textb[0]);
	       save_data("\n");
	    }
	    sprintf(textb[0],"weighted average:ld-r=%g Z=%g",
					  wtlratio,wtzparam);
	    if (pdata){
	       print_out(textb[0]);
	       print_out("\n");
	    }
	    if (filedata){
	       save_data(textb[0]);
	       save_data("\n");
	    }
	 }
	 if (pdata) print_out("\n");
	 if (filedata) save_data("\n");
	 pdata=thispdata;
	 filedata=thisfiledata;
      }
      is[0]=0;
      is[1]=0;
   }
   if (was_loaded) return(1); /* return value could be -1, 0, or k */
   else return(0);
}

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