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

/********************* GLOBAL variables 1 ************************/
#ifndef __386__       /*watcom c/386 compiler*/
#   define __386__ 0
#endif
#define __WATCOM__  __386__

#ifndef unix
#   define unix 0
#endif
#ifdef __DARWIN__
#  define unix 1
#endif
#define __UNIX__ unix


#define kNumBoxImages		30
#define kNumBoxPromptImages	15

/********************************************************/
#if __WATCOM__
   #include <graph.h>
#endif
/********************************************************/
#ifndef EXT
   #define EXT extern
#endif
#    if __WATCOM__ /*for sound effects*/
   EXT char makesound;
#    endif
/* xwindows compatibility */
EXT signed int Leftx,
                 Maxx,
		 Maxy;

EXT unsigned int CWidth,CHeight,
              CWidth_def,CHeight_def;
EXT signed int pixmap_width; /*width of pixmap run_forward( and end_page(*/

/*for watcom compiler*/
#if __WATCOM__
   EXT struct xycoord xy;       /*current x,y coordinates*/
   EXT struct textsettings ts;  /*current text settings*/
   EXT struct videoconfig vc;   /*curent video info*/
   EXT struct _fontinfo info;   /*info about font*/
   EXT unsigned char fillcolor; /*to fill inside rectangles etc*/
   EXT signed int fillpattern;
   EXT char title_file_found,
	    first_title;
   EXT void *title_image;  /*bottom title image*/
   EXT char sfont; /*size or fon if loaded, 0 if not*/
   EXT signed int nfonts; /*number of fonts loaded*/
#endif

#if __UNIX__
   EXT Display *D;
   EXT int     S;
   EXT Window  W;
   EXT Drawable	*current_draw;
   EXT GC      Gc,GcRev;
   EXT XEvent  Event;
   EXT Cursor rightCursor, 
              leftCursor;
   EXT XFontStruct *nonpropfont,
                   *mediumnonpropfont, 
                   *smallnonpropfont,
                   *propfont,
                   *mediumpropfont,
                   *smallpropfont,
                   *italicfont,
                   *tempfont;
   EXT char fonttype; /*non-prop=0, prop=1*/
   EXT unsigned int screen_depth;	/*depth of screen*/

   EXT Pixmap 
        *stpimage, /*space-time pattern image buffer for scrolling*/
        **boximage, /*pointer to image buffers for box*/
        **boximage_prompt, /*image buffer for prompt box */   
        *statblock; /*block for mean ent-standard dev of ent graph*/
 
   EXT XRectangle viewport[1];
   EXT Colormap default_cmap;
   EXT XColor color_def;
#endif

   EXT char inside_rect;/*pointer is inside drawing rectangle*/
   EXT signed int 
        getx,gety,
        putimageH,putimageW,
        WinMaxy,   /*screen height including bottom title bar*/
        startMaxx, 
        startWinMaxy;
   EXT unsigned char oldcolor[16];	
   EXT unsigned char
    nowcolor, /*keeptrack of current forground color*/
    fillcolor,/*keeptrack of current fillcolor color*/
    White,
    Black,
    Yellow,
    Gold, 
    Khaki,
    Wheat,
    Tan,
    Goldenred,
    Orange,
    Coral,
    Salmon,
    Red,
    Orange_Red,
    Indian_Red,
    Firebrick,
    Brown,
    Sienna,
    Maroon,
    Medium_Violet_Red,
    Violet_Red,
    Pink,
    Green,
    Spring_Green,
    Medium_Spring_Green,
    Green_Yellow,
    Pale_Green,
    Yellow_Green,
    Lime_Green,
    Medium_Sea_Green,
    Sea_Green,
    Forest_Green,
    Olive_Drab,
    Dark_Olive_Green,
    Dark_Green,
    Cadet_Blue,
    Medium_Aquamarine,
    Dark_Turquoise,
    Turquoise,
    Aquamarine,
    Cyan,
    Blue,
    Medium_Blue,
    Medium_Slate_Blue,
    Cornflower_Blue,
    Sky_Blue,
    Light_Blue,
    Light_Steel_Blue, 
    Steel_Blue,
    Dark_Slate_Blue,
    Navy,
    Navy_Blue,
    Midnight_Blue,
    /* extra */
    Ghost_White;
   EXT int *Color_Table;
   

/************************* GLOBAL DATA 1 ************************/
/************** global variables  ********************/
EXT signed int istr_node_count; /*for interactive state transition graph, istr_graph defined below*/
//EXT unsigned long *dec_state0;
//EXT unsigned long *dec_state1;
EXT char early_exit_draw_fan;

EXT char **pat_state0;
EXT char **pat_state1;
EXT unsigned int *index_successor;
EXT unsigned long *istr_index;
EXT unsigned int max_istr_node_no;

/*for isotropic functions*/
EXT char *nhd_color_order; /*shuffle nhd colors except white and black*/
EXT char *iso_group_image; /*max memory for an iso-group image*/
EXT signed int **glbl_iso_list; /*as isotropic_list but global/larger to contain any size*/
EXT char *iso_rule;
EXT signed int *group_list_iso; /*list of all nhoods and iso-rule index for each*/
EXT signed int iso_tablemax;
EXT signed int index_of_flip; /*for any rule table, but especially isotropic flip, Jan 2020*/
EXT char isotropic_set;
EXT char set_iso_bitflip;
EXT char set_iso_input_histogram;
EXT char iso_rule_allowed;
EXT signed int iso_prototype_count; /*for 3x3 prototype blocks set wit "/" forward-slash, July2021*/ 


/*for transient bins using attractor histogram*/
EXT signed int transient_bin[12];


EXT char hex2d; /*was a local variable in wiring, now global*/
EXT unsigned long auto_sample_rule_count; /*for consecutive dec rules for small rule-space*/
EXT float demorad; /*rad of circle in screensave demo -- now global 21 Jan 2017
                         to allow basin scale change on-the-fly, 'C' and 'E'*/
EXT signed int Si,Sj,Ei,Ej; /*for moving a patch*/
//EXT char patch_only;

EXT signed int poly[12];
EXT signed int foldposs; /*now global variable so can be changed*/
EXT signed int
    trboxw, /*width of top-right box, varies according to font, Maxx*/
    vret, /*return value for read, write, etc*/
    Max_oy, /*if way below screen dont'draw, Max_oy=Maxy*2 set in main*/
    Ham_bias,
    pointsize,
    psize_ps,
    fid_PS,
    fid_data,
    new_basin_row,
    bottom_title_middx, /*to define x where onthefly options start*/ 
    slowfactor, /* or on interrupt, or in drpara */
    porder_min,
    porder_max, /*network subset limits (def 1-lineL)*/
    /*xtl, ytl, not used -- top left of space-time patterns*/
    glider_rule_order, /*for glider rules, toggle rand/seq order*/
    slant, /*to slant-straiten out even k stp*/
    temp_i2d,temp_j2d; /*reset and restore buffers for neutral orders*/

EXT unsigned int
    maxLu32, /*max string length base on 32 bits*/
    maxL_lu, /*max string length for unsigned long - for dec rule or state*/
    max_exh_lu, /*max string exhaustive testing algorithm*/
    seglen, /*for size of block, was local in select_seed()*/
    *v_tablecodemax; /* max index of table for 
                                  v_code totalistyic rules for diff k*/

EXT unsigned long 
    pre_speed; /*to slow down basins on-the-fly: -/+*/

EXT unsigned char
    bias_percent_rule[9], /*value freqency for rule*/
    bias_percent_seed[9], /*value freqency for seed*/  
    *color_v; /*colors for value_range*/         

EXT unsigned long stat_patch_index;
EXT unsigned char xstat1, ystat1, xstat2, ystat2;
EXT char
    stat_patch, /*to confine stat search in scatter-plot patch*/    
    NULLboundaries, /*for NULL boundary conditions*/
    CursorFlash_auto_reset,
    **dcolor, /*colors for postScript files*/
    postScript_graph_state, /*during stp -- to save graph state to postScript*/
    inside_wiring_graphic, /*need this to show rules in xterm with 'x' */
    basin_not_complete,/*to prevent changes to network when basins interrupted*/
    wiring_postscript, /*wiring graphic, 
                            needed for draw_save_3d_frame .. draw_axon_plane*/
    jump_layout_only, /*for field basin layout - drag basin positions*/ 
    *filename_basin_PS, /*save basin graphic to postScript file, Dec07*/
    basin_postScript, 
    stagger_even_rows, /*for basins, or rows in stp*/
    TFO_SEED_FIELD, /*info in bottom title, 0, TF=1 SEED=2 FIELD=3*/
    font_d_m_s, /*keep track of font: d=default, m=medium, s=small*/
    *bigbuf,   /*for saving state data in boa and subtrees*/
    p_order, /*partial-order, upadate sequential rand subsets of the network*/
    onthefly_box_erased,
    min_max_entropy, /*use greatest monotonic entropy increase
                            instead of standard deviation*/
    outer_tot, /* for outer totalistic rules*/
    border, /*border width: forward only, define a fixed border, 1,2,3d */ 
    b_value, /*border value: to try to absorb gliders etc */
    twod_local, /*to identify 2d local wiring*/
    reverse_value_order, /*tcode in reverse order -- for Antonio's rules*/
    ptype, pmu, /*for Post functions*/
    *flipvalue,   /*value before flip (added Nov 2002), up to 50*/
    tot_only, /* =1 for totalistic rules only, 
                      program constrained to run forward only - no basins, 
                      this allows greater k, especially for v>2*/
    ***v_index, /* v_code totalistic value array 
			v_index[k][local rule index][char local totals]*/
    value_range, /*multi-state networks*/
    value_bits, /*no of bits required for value_range*/
    new_weight, /* fonts: 2=bold 1=medium */ 
    mutant_layout; /*to show single basin, subtree mutant on one screen*/

EXT float *grayscale; /*equivalent grayscale for postScript*/
          
/*network graph and attractor jumpgraph */
EXT unsigned int 
    *m_att_period, /*attractor periods in field, for jump_graph*/
    file_i,file_j,file_h, /*size of file array*/
    file_starti,file_startj,file_starth;/*start position in base array*/

EXT unsigned long *m_basin_volume; /*size of basins in field_ for jump_graph
                       changed to long from int because of big basins, dec 2001 */
EXT signed int 
    **basin_pos,
    **basin_pos_injump, /*to save positions jump-graph nodes, April 2022*/
    **stp_graph_layout,/*for graph layout of space-time patterns*/
    *bin_bound; /*values as % of frozen frequency bin boundarys*/

EXT float 
    *stp_graph_node_size,/*for graph layout, node size, space-time patterns*/
    pause_fact;

EXT unsigned char *stp_cell_color; /*for graph layout*/

/*new variables >2000*/
EXT char
    exh_pairs_in_jump_nodes,//to redraw basins within jump-graph nodes if exhaustive_testing
    use_preset_basin_pos,
    graph_layout, /*to run stp on graph layout*/
    num_bin_bound, /*the number of bin boundarys*/
    
    jump_graph,  /*to show the jump_graph after drawing the basin of att field*/
    ibaf_graph,  /*name changed Dec2021 "interactive basin-of-attraction-field graph
                 applies after drawing exhaustive basin of att field
                 was "ist_graph" interactive state transition graph April2021*/
    istr_graph, /*str-graph is an interactive state transition graph as drawn (and/or interupted),
                   a subtree, single basin, or field, or part thereof- March 2025*/
    ***m_att, /*to record attractor data, for attractor histogram and jump-graph*/
    ***m_trans, /*to record transient data for attractor histogram*/
    reorderRBN, /*to reorder RBN to optimize preimage algorithm*/
    file_dim; /*dimension of (converted?) file array*/

EXT unsigned long defCursorFlash,kCursorFlash;


/*new variables >1998*/
EXT unsigned char 
    *freq_colors; /*for frozen frequency bins*/
   
EXT char 
    neutral_order,
    *is,   /*input string buffer*/
    *color_filter, /*to filter out colors in space-time patterns*/
    *mutation_filter, /*to keep track of on-the-fly mutations, june2020*/ 
    single_entropy;
    
EXT signed int 
    *force_layer, /*force links to 3d layers*/
    view_x0,view_y0,
    view_x1,view_y1,   /*co-ords of current viewport*/ 
    tview_x0,tview_y0,
    tview_x1,tview_y1, /*temp co-ords of current viewport*/
    time_skip, /*timesteps that may be skipped (on the fly)*/
    rule_box_top, /*top of the rule box at bottom of screen*/
    hyper_prob;    
                  
EXT unsigned int 
    entropy_poss,
    *nhd,  /*pointer to array of nhood values-for CA cell colors*/
    *seq_order; /* reorder for sequential updating */ 

EXT unsigned long 
    ittpause, /*to pause stp at defined time-step*/
    *hist_order, /*keep track of histogram bar size order 
                                   (changed from signed int - June 06)*/
    wires_cut,
    sizeof_statbuf;/*keep track of buf size stat rule sample*/

EXT float 
    bias_density_rule, /*to set rules and seed at random with biased density*/
    bias_density_seed,
    orient_angle, /*to rotate def basin orientation*/
    fan_angle_fact,  /*to change def pre-image fan angle*/
    out_prob,temp_out_prob, /*probability of output*/
    update_prob,temp_update_prob; /*probability of update*/

/*names for colors*/
EXT unsigned char   /*colors*/
		black,        /* 0 */
		blue,         /* 1 */
		green,        /* 2 */
		cyan,         /* 3 */
		red,          /* 4 */
		magenta,      /* 5 */
		brown,        /* 6 */
		lightgray,    /* 7 */
		darkgray,     /* 8 */
		lightblue,    /* 9 */
		lightgreen,   /* 10 */
		lightcyan,    /* 11 */
		lightred,     /* 12 */
		lightmagenta, /* 13 */
		yellow,       /* 14 */
		white,        /* 15 */

  matrixcolor, /*diff colors for each basin in state space matrix*/
  *glider_buf, /*buffer to hold glider rules*/
  *statbuf;  /*buffer for rule statistical sample*/

EXT char /*flags 0 or 1*/
  exLimit,      /*allow extra (risky) n, k, even if insufficient memory*/
  ex_device,    /*send/receive char to external device*/
  seq_update,   /*for sequential as opposed to parallel*/
  rules_set,    /*if mem for rules was allocated*/
  nhood_mixed,  /*different size nhoods at each cell*/
  ncolor,    	/*1-color acc to nhood, 0-color acc to value*/
  totalistic,   /*indicates a totalistic rule*/
  segfan,       /*condition found,1 for segmented fan, else 0*/
  /*allbitssame,*/ /*1 for all 0s or 1s, else 0 - local in run and back*/
  insegloop,   	/*inside the fan segment loop*/
  startsegfan, 	/*starting a new fan segment*/
  justonepreimage,  /*indicates 1 pre-image from point att*/
  justonepreimage_found, /*above should only happen once*/
  pretog,      	/*to toggle **preim0 and **preim1*/
  earlyexit,   	/*allows interupt before pre-image fan is complete*/
  earlyexitbasin,   /*to note early exit for basin*/
  earlyexitfield,   /*   "      "        for field*/
  isrepeat,    	/* =1 if repeat found*/
  seed_was_set,	/*indicates new seed*/
  hires,       	/*0=VGA; 1=upgradeto IBM8514 1024 * 768*/
  scrolling,   	/*to select scrolling or successive pages*/
  nowscrolling,	/*to indicate scrolling in progress*/
  basinfield,   /*0=singlebasin, 1=basin of attraction field*/
  toggle_single_field, /*toggle above*/
  stp,	        /*to suppress space-time pattern*/
  fieldpause,	/*pause between fields*/
  rangeL,      	/*range of CA size*/
  mutantdontpause,  /*1=dont pause after mutant graphics, 0=pause*/
  acceptall,    /*accept all drawing defaults*/
  stppause,     /*1=DONT PAUSE on space-time screenfull, 0=pause*/
  screensavedemo, /*generates randomly located basins*/
  show_ss_matrix, /*show states on 2-d matris as basins are drawn*/
  show_ss_matrixF, /* as above forwards only*/
  ss_m_att_only, /*show attractor states only in state space matrix*/
  see_ppstack,  /*to see growth of partial pre-image stack*/
  diff_plot,    /*to plot difference between 2 networks*/
  exhaustive_testing, /*find pre-images by exhaustive testing*/
  dontcompress, /*dont compress basins/fields by symetries etc*/
  layout_notset, /*layout defaults to be set*/
  in_startbasin,
  in_startfield,
  successive_basins, /*show basin field as successive basins*/
  show_one_att_state,/*show one attractor state as bit pattern in each basin*/
  forward_only, /*forward only, just space-time patterns*/
  set_z_high,   /*search rule with high Z paramater*/
  secondpart,   /*first and second part of prog, after rules set*/
  showbits_1d_as_2d, /*to show 1d bit nodes in 2d*/

		/*flags more than 0,1*/
  accept_from,  /*accept defaults from.. all,layout,presentation,etc*/
  datapause, 	/*pause for tree data=2, basin only=1, default=0*/
  shownumbers, 	/*-1-dont show, 0-spot, 1-dec, 2-hex,
                  3-and 4 - 1d or 2d  bitstring*/
  just_G,       /*show garden-of-eden nodes only*/
  dontcopytrees,/*0-copy trees,1-show g-E nodes,2-reduce g-E nodes*/
  pdata,	/*print data to xterm, 1-basin only, 2-also tree data*/
  filedata,     /*data to file,          "             "   */
  filestates,   /*   "          showing details of states*/
  printstates,  /* as above, but print to xterm*/
  mutate,/*5-code,4-code rand,3-rule,2-rule rand,1-onebit cum,0-bit single*/
  mutate_wiring, /*0-don't, 1-cumulative, 2-restore original before*/
  mutate_wiring_and_rule, /* ...as well as rule*/
  was_changed,  /*rule/s or wiring was changed, so dont mutate automaticaly*/
  stpgraph,     /*0=do nothing, 1=pattern density, 2=look up frequency*/
  pause_show_code,/*for lambda-Z graph totalistic codes*/
  att_hist,     /*for attractor or skeleton histogram*/
  att_trans, /*to record transient states for attractor histogram*/
  bin_trans, /*to sort trans length into bins -- show in terminal*/
  att_seed_dens, /*0,1 flag to include seed density data for all-0/1s
                  point attractors*/
  /*char flags*/
  direction,	 /*'f'-forward, 'b'-back*/
  bground,       /*'b'-black, 'w'-white*/
  codetypeonly,  /*for lambda-Z graph totalistic codes
		   all codes-a, clusters-c equivs-e*/
     system_bits, /*either 32 or 64*/
     *nhoodm,   /*for different nhood size at each cell*/
     *rot,      /*for segment repeats,equivalent cycle states etc */
     *exh_pairs, /*array for exhaustive pairs, calloc in prestate_successor_pairs()*/
     *exh_pairs_backup, /*for jump-graph if exhaustive_testing, including random-map, freed in graphxx.c*/
     **nm,     /*nhood_matrix top left 4,31...bottom right 0,0*/
     *canal,   /*for canalyzing inputs*/
     *iscanal,   /*to distinguish canalizing cells (genes)*/
     **carule,     /*pointer to pointers to rule tables*/
     **carule_mut, /*to restore single successive mutations for multi-value, and rule-mix*/ 
     **cacode,     /*pointer to pointers to totalistic code tables*/
     **v_code,   /* pointer to pointers to totalistic v-code tables, fraction of diff values*/
     
     **diffrule, /*limited set of rules for rulemix*/
     **v_diffcode, /*limited set of codes for rulemix*/
     **diffcode, /*limited set of v-codes for rulemix*/
     *state1,                  /* pointer to active ca line - bits*/
     *state2,                  /*           next                 */
     //*stateB,                /*           previous, moved to backx.c */
     *kv_out,             /* outputs in rule-table muple */
     *kv_freq,            /* value frequencies in rule-table muple */
     *next_right_stack,   /* set of next right values */
     *bitseed,            /*           seed                 */
     *firstseed,          /*           seed for pre-images  */
     *this_firstseed, /*for upstream_only (forwards before backwards) was local*/
     *all_0s,             /*	       all_0s*/
     *all_1s,             /*	       all_1s*/
     *tempState,    /*pointer to temp state, attractor or pre-image*/
     *tempState2,   /* another, for tickoff*/
     **segseed,   /*pointer to pointers of first state in each segment of
			pre-image fan for all 0s and 1s*/
     nhood,  /*nhood=size of neighbourhoods, or upper bound if different sizes*/
     Maxnhood, /*maximum allowable nhood size?*/
     Maxk, /*also maximum allowable nhood size*/
     defMaxk, /*default max nhood*/
     nhood_lb, /*lower bound if different sizes*/
     nhood_ub; /*upper bounds*/

EXT unsigned int canaltotal; /*total canalyzing inputs in nhood*/

EXT signed int
    tx1,tx2,ty1,ty2, txd,tyd, /*for text sizes and default text sizes*/
    globax,globbx,globcx,globdx, /*for mouse*/
    mouse_x,mouse_y;  /*position of mouse*/

EXT char mouse_found, /*1 if found, 0 if not*/
     button, /*if pressed - 'l' or 'r'*/
     button_not_rel; /*if not releaced - 'l' or 'r'*/

EXT unsigned long
     totalgraphrules,/*no of rules in G-density or lambda-Z graphs*/
     endcount; /*counts mutants for gd-z graph*/

EXT signed int
    scrolly, /* lowest row for scrolling*/
    Maxint, /*=32767 max signed signed int*/
    lambda_bias, /*bias lambda ratio when setting random rule*/
    
    gens,   /*no of generations for analysis*/
    frozen_gens, /*no of generations to highlight frozen cells*/
    msize, /*size of state space matrix*/
    *seg,   /*pointer to
		size of segments of pre-image fan for all 0s and 1s*/
    *seg_2d_h, /*same for 2d, horiz and*/
    *seg_2d_v, /*             vertical*/

    /*to see partial pre-image stack growth, rnd wiring*/
    pp_startx0,pp_starty0,pp_startx,pp_starty,    
    pp_bartotw,pp_wild,pp_barwidth,pp_depthy,pp_heighty,
    pp_widthx,    
    **no_glider_rules, /*number of glider rules saved for 
                        diff value_range, then diff nhoods*/
    repseg_2d[2];/*length repeating segments horiz-0, vert-1*/
EXT unsigned int
    /*two-d*/
    cyclematch_2d[2],     /*no of rotation equivalent cols/rows in cycle*/
    cyclematch_2d_diag[2];/*            diagonal shifts, pos or neg     */

EXT unsigned long /*to find average histogram*/
      Maxlu,
      pp_wild_tot,
      pp_histcount,
      *pp_hist_total,
      *pp_hist,/*pointer to actual pp stack for each cell, rnd wiring*/
      pp_hist_max, /*max stack in 2 latest histograms*/
      pp_ymax, /*max anticipated pp stack, rnd wiring*/
      pp_divy,
      matrixx,matrixy; /*state space matrix, max x,y axis*/

EXT unsigned short Max_ushort;
EXT unsigned int
         blockx,blocky,blockz, /*for central block, rectangle or cuboid*/
	 Maxu, /* max unsigned int in = */	 
	 segno, /*no of segments in pre-image fan from all 0s and 1s*/
         segindex, /*index of fan segments, all 0s or 1s*/
	 startL,endL, /*start and end sizes for range*/
	 lineL,    /*line length no of cells in array, L,L-1,.....,0*/
         templineL,
	 ppL, /*check for new line length to view pp stack growth*/
	 L,        /*L=lineL-1, index of 1st array cell*/
	 bytesL,     /*no of bytes in bitseed*/
	 rangebytesL,     /*no of bytes in rangeseed*/

	 /*one-d*/
	 cyclematch,  /*no of rotation equivalent segments in cycle*/
	 attrepseg, /*length of equiv. segments in attractor state*/

	 /*two-d*/
	 attrepseg_2d_h,/*colums,  no repeating in toroidal bit array,*/
	 attrepseg_2d_v,/*rows,    same for all states on att cycle*/
	 basinno_2d_h,/*basin with states rotated horiz by 1*/
	 basinno_2d_v,/*for each above, basin with states rotated vert by 1*/
	 attrepseg_2d_patch,/*patches*/

	 level,     /*current level*/
         level_limit, /*limit levet for running backward*/
         /*fansize,*/ /*size of pre-image fan, changed to unsigned long*/
	 maxtreelevel,   /*max level in given tree*/
	 maxbasinlevel,  /*max level in given basin*/
	 totbasinsinfield;  /* total no of basins*/

EXT signed long wires_to_move, /*when mutating by wire moves*/
	    bits_to_flip;      /*               by bit flips*/
EXT unsigned int *cycles; /*keep track of cycle length frequency*/
EXT unsigned long
  thisindex, /*index in current level*/
  nextindex, /*index in next level*/
  nextbefore,/*index before start of pre-image fan*/
  thismax,   /*no of states in current level*/
  nextmax,   /*                 next         */
  fansize,   /*size of pre-image fan, changed to unsigned long*/
	      totalsegfan, /*total states in segfan*/
	      attperiod,  /*attractor period*/
              attindex,   /*index of attractor cycle*/
              stepforward, /*itterations forward before going backward*/
	      precount,   /*counts pre-images*/
	      pretested,  /*count of states tested*/
	      gofEno,     /*count of garden of Eden states in tree*/
	      totalgofE,  /*         total                in basin*/
	      totalprecount, /*total states*/
	      treesize,    /*size of given tree or sub-tree*/
	      totsubtree,  /*total                         */
	      basinsize,   /*total no of states in basin*/
	      totatt_states, /*total no of attractor states */
	      maxtreefan,  /*max size of pre-image fan in given tree*/
	      maxbasinfan,
	      maxfieldfan, /*                            in field*/
	      fieldsize, /*size of field - check against state space*/
	      fieldgofE; /*count of garden of Eden states in field*/
              
EXT float
      cinputfreq, /*fraction canalyzing inputs*/
      xtext,  /*start position of text in textwidth units*/
      fieldgofEdensity, /*dencity of g of E states in field*/
      basingofEdensity, /*                         in basin*/
      totsubgofEdensity;/*                       in subtree*/


/*** GLOBAL variables 2 (same for watcom) were in separate file eglob_b.h **********/

EXT float 
     cellscale, /*for rule/seed shown as bits*/     
     cellsep;   /*for rule/seed shown as bits*/
EXT char
     scale,     /*size of ca cell in pixels, for basin nodes*/
     sep,        /*=2 for 1 pix division between cells, 1 for no div*/
     *path,
     *filename,
     *filename_data,     
     **att,     /*array of pointers to pointers to attractor states*/
     **textb, /*3 text buffers*/
     

     node_tight, /*bit/value nodes in basins: 0 allows divs, 1 no divs - tight*/
     node_dots,  /*=1 put dots on zero cells*/

        
     textscale,    /*textheight in relation to ca scale*/     
     *tickoff,	 /*tick off states in state-space for basin field*/
     gd_z_graph, /*to draw g-of-E density<->Z-parameter graph*/
     lambda_z_graph, /* to draw lambda ratio - Z graph*/
     *codetickoff, /*bitstring for code tickoff for equiv codes*/
     *tempcode, /*temp code table for transformations*/
     pre_fansize_freq_hist, /*to show pre-image frequency histogram*/
     show_maj; /*to show above, maj 0s or 1s, or of selected value..*/

#if __WATCOM__
EXT void
     *stpimage,          /*space-time pattern image buffer for scrolling*/
     **boximage,      /*pointer to image buffers for box*/
     **boximage_prompt, /*image buffer for prompt box*/
     *statblock;
#endif

EXT float
      *zparam, /*zparam[1]=z->, zparam[2]=z<-, zparam[0]=greatest*/
      lowlimZ,/*limit Z range for gd_z_graph nhood<=3 or totalistic*/
      highlimZ,
      lambda,lratio,
      *rad,     /*array of log2 levels*/
      startrad,   /*max radius of attractor cycle in pixels*/
      pstartrad, /*                      % half screen x axis*/
      trans_shrink_fact, /*=1, to shrink or lengthen transient presentation*/
      rightborder, /*if border smaller than this*xspacing, next row*/
      angle, 		/*centre line angle of fan relative to origin*/
      heading,          /*angle of pre-image node                    */
      spot,             /*radius of node spot*/
      firstxspacing,firstyspacing, /* remember initial co-ords*/
      xoffset,
      yoffset,  /*position of att cycle on screen, % off centre*/
      xspacefact,yspacefact, /* factor ""        ""           ""  */
      /*factor to change size of default node number or string*/
      labelsizefactor;
EXT signed int
    height_req_seed_win, /*height required for seed window*/
    /*rand_seed_percent,  % change for random seed*/
    bitflipcount,    /*count of bits fipped*/
    *flippos,    /*position of flip in rule-table, up to 50*/
    lastlevel,
    
    fox,foy, /*initial co-ords for layout preview*/
    firstox,firstoy,  /*initial field co-ords*/
    xspacing,yspacing, /*spacing between basins, in pixels*/
    startxspacing,startyspacing, /*start spacing between basins, in pixels*/
    fieldno, /*count of fields for size range*/
    mut, /*mutant index+1*/
    startmut,endmut, /*start and end bitflip positions, countdown*/
    basintypeno, /*no of non equivalent basin types*/
    /*attindex,*/ /*index of attractor cycle- now unsigned long in eglob_a.h*/
    basinno, /*no of equivalent basins of one type*/
    
    barxl,baryt,barxr,baryb, /*for field progress bar*/
    gox,goy,    /*graph x,y origin*/
    graphspot,  /*rad o graph spot*/
  /*isexception,*/ /*for checking exceptions in Raja's rule*/

    /*these would be better as floats? to avoid distortions in attractor basins*/
    cx,cy,     /*current plot co-ords*/
    ox,oy,  /*co-ords of current origin on or off standard screen*/
    *xx0,*yy0, /*co-ords of next level*/
    *xx1,*yy1, /*or current level*/
    *cyclex,*cycley, /*co-ords of attractor cycle nodes*/
    *segx,*segy;     /*co-ords of fan segments, all 0s or 1s*/

EXT unsigned int
    limitcheck,   /*limit of steps checked for repeat*/
    maxinhist;   /*for in-degree histogram, over this limit last bin*/

EXT unsigned char
    start_edge_color,/*edge start color in basins*/ 
    linec,       /*color of line*/
    spotc;       /*color of node circle*/
EXT unsigned long
    isexception, /*for checking exceptions in Raja's rule*/
    segstates, /*count of of segmented states*/
    statespace,    /*size of state-space, 0..max*/
    tickspace,    /*size of tick off space, 0..2^18-1*/
    progbar, 	     /*no used states in field so far*/
    sspace, /*state space tick off array*/
    *pre_fan_freq; /*array for pre_fan_frequency*/
EXT double
    lx,ly;   /*length of x,y axes*/
/************* random booean network variables*************/
/*************         random wiring      *****************/
EXT char *rule_all_0s,/*for checking for same n-tupules in rbn pre-image algorithm*/
     *rule_all_1s, 
     oned,           /*1d networks*/
     twod,           /*2d networks*/
     threed,         /*3d networks*/
     setting_seed,   /* =1 when setting a new seed*/ 
     d_mode,         /*how to draw stp 1-1d, 2-2d, 3-2d+time, 4-3d*/
     whatwire,       /*type of wiring..
                          treed=6
	                  hypercube=5
			  load wiring=4
			  hand wire=3
			  regular 2-D=2
			  regular 1-D=1
			  random=0       */
     nonlocal,   /*regular CA, nonlocal=0, else=1 */
     wiring_madelocal, /*to toggle random-local wiring*/
     rnd_rewiring_each_timestep, /*randomy rewire at each time-step, April 2018*/
     compress_1d_local; /*if local treated as nonlocal*/
     

EXT unsigned int
     **wiring,   /*wiring[cell poss][nhood index]=(wired to) cell poss*/
     **wiring_backup,   /*same as above*/
     *celloutfreq, /*no of output wires to each cell*/
     zonesize;   /*size of wiring zone, if no restriction = lineL*/
EXT signed int
     i2d,j2d, b_i2d,b_j2d,   /*size 2d network*/
     i3d,j3d,h3d;   /*size 3d network*/
/*************         mixed rules      *****************/
EXT char
     rulemix,   /* =0 for onr rule only, =1 for rule mix*/     
     loc_twod_fonly, /*dont wire up regular 2-d CA, dont allocate wiring mem,
			run forwards only and compute nhood*/
     regular2d, /*2d local nhood*/
     regular3d, /*3d local nhood*/
     regular2d_tgrid; /*local hex grid (tiling)*/
/******************  learning algorithms  ***************/
EXT signed int
     nodiffrules, /*limited no of rule from wich rule choise is made*/
     notolearn; /*number of pre-images to learn*/
     /*target state, aspiring pre-images (hilight in basin)*/
EXT char
     *tar,**learn_pre,
     hilight_learn, /*to hilight target state, tar and pre in basin*/
     dont_save; /*omit option to save seed*/
EXT unsigned long
     totstatrules, /*total rules in statistical rule sample*/
     current_sample_index; /*to keep track of current*/
/***************************************************/




