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

/****************** EXTERNAL revised feb 96 *************/
#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

/*#ifndef linux
#  define linux 0
#endif
#define __LINUX__ linux*/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#if __WATCOM__
#  include <graph.h>
#  include <conio.h>
#  include <string.h>
#  include <CTYPE.H>
#  include <DOS.H>
#  include <time.h>
#  include <process.h>
#  include <bios.h>
#  include <limits.h>
#  include <io.h>
#  include <fcntl.h>
#  include <sys\stat.h>
#  include <graph.h>
#  include <malloc.h>
#  include <dos.h>
#endif

#if __UNIX__
#  include <string.h>
#  include <ctype.h>
#  include <memory.h>
#  include <sys/param.h>
#ifndef __CYGWIN__
#  include <sys/syscall.h>
#endif
#  include <sys/time.h>
#  include <sys/types.h>
#  include <sys/uio.h>

#     ifdef __SOLARIS__
#        include <sys/stat.h>
/* #include <sunmath.h>*/
#     endif

#     if __IRIX__               /* IRIX added by Oscar */
#        include <sys/stat.h>
#     endif

#  include <X11/Xos.h>
#  include <X11/Xlib.h>
#  include <X11/Xutil.h>
#  include <X11/cursorfont.h>
#  include <X11/keysymdef.h>
#endif

#include "eglob_ab.h" /*eglob_a.h and eglob_b.h now combined*/

/*************** define some structures ****************/
/*variables for difference plot*/
typedef struct diff_var {
   char  pause_dam_hist,
	 d_bin_type;
   unsigned long
      *damage_buf,
       diff_sample_count,
       damage_count,
       old_damage_count,
       d_maxy;
   unsigned int              
       d_histno,
       d_ittcount,
       same_count,
       ame_limit,
       max_d_hist,
       min_d_hist,
       same_limit,		 
       att_types;
    signed int 
        d_leftx,
	d_topy,
        d_boty;
   double
	d_divx,
	d_divy,
	d_height,
	d_width;
   float percent_damage;
   char textbuf[40];
} diff_var;

/*variables for auto entropy plot*/
typedef struct auto_ent {
   signed int sample_size,
	        sample_sofar;
   unsigned long edataruleno; /*rule count for statistics plot*/
  char show_edata,/*for showing/creating automatic (entropy) rule sample*/
        file_edata,
        auto_sample_pause, /*toggle automatic sample pause*/
        bias_rnd_rules,
        bias_isomorphic,
        bias_allV2V, /*force all Vs to V*/
        bias_all020; /*force all 0s to 0*/
   float *edata, /*to save entropy data*/
         ave,adev,sdev,svar,skew,curt;
} auto_ent;

/*variables for entropy and eeg-entropy plot*/
typedef struct ent_eeg {   
  char  new_hist,   /*newlookuphist (in groups if long lookuptable) */
        showeeg,      
        showlookupfreq,/*=0, =1 lookup histogram, =2 3d histogram*/
        showlookupfuz, 
        lookup_entropy,
        barsep,
        ent_nhood,/*to allow entropy for single sites in mixed k net*/
        ecolor;/*color for eeg-entropy graph*/       
   double *eegratiobefore,tot_eegcount;  
   signed int
        history_lines_in_plots,
        ent_den_plot_before[2],
        *hist_group,    /*newlookuphist (in groups if long lookuptable)*/    
        col_group_size, /*                 "                           */
        lastgroup_size, /*                 "                           */
        actgens, /*actual gens for analysis if less than gens*/
        twodgy,       
        newbar,/* not in for*/  
        newbar0,/*not in for*/
        *oldbar,            
        thisxbox,
        thisybox,
        startxbox,
        startybox,
        xboxmax,
        yboxmax,
        topleftx, /*not in for*/
        toplefty, /*not in for*/        
        barno,  
        barlength,
        stpwidth;   /*width of space-time pattern+10*/       
   float
      hist_bar_factor, /*to amplify the bars: intut-entropy histogram*/ 
      eegwidth,
      lookupfreqwidth,
      barw;/*$*/      
   unsigned int
           **eegcount,
           **lookupcount,
	  sstep, /*start time-step for entropy data*/
	  estep; /*end time-step for entropy record*/
} ent_eeg;

/*variables space-time pattern interrupts*/
typedef struct int_stp {   
#   if __UNIX__
       Pixmap *offscreen_pixmap;
#   endif
  /*to monitor pulsing in terminal, July 2018*/
  float etempent,old_etempent,emax_ent,emin_ent,
        av_wave_length,av_wave_height,wave_height_total;
    unsigned long old_this_emin,old_this_emax,
             wave_sample,wave_height_sample,wave_total;   
   unsigned char e_up, e_down;
   //-------------------------------------
  signed int
    rect_h, /*height of hex rectangle*/
    a_sample_ht, /*height of time-step block when scanning rule samples*/
    tablemax,   
    strip,
    downy,
    diffgap,
    i2d_b,j2d_b,i3d_b,j3d_b,h3d_b;    /*back up*/
  unsigned char
    color0,color1;
  char
     req_iso_ptrns[9], /*define nd show range of 3x3 iso-rule seeds, Sept2021*/
     filter_toggle, /*in spite of filtering, to toggle filtering in on/off with '-', June2020*/
     track_pulsing, /*show details of lu_entropy at each time-step*/
     seedORblock, /*def 0=seed for 1d, def=1 for 2d/3d 
                    when scanning  rule samples in time-step blocks*/
     draw_3d_grid, /*to toggle 3d grid in draw_axon_plane(..*/
     pi_outline,/*draw outline to filled circle,1/0*/
     keep_index,
     time_step_density_plot,  /*show density...x=t, y=t-1*/ 
     partial_order, /*to update subsets of the network*/
     show_2d_divs, /*show divisions in 2d*/
     divcolor, /*division color, black or white*/
     show_dots, /*show divisions in 2d*/
     slant_even_k, /*to straiten out even k stp, or show 2d hex*/
     node_outline, /* for graph layout only */
     slice_3d, /*to show 3d network in slices*/
     invisible,/*suppess 2d diagonal scrolling stp, show graph only*/
     skip_timesteps, /*to skip a given number of timesteps*/
     temp_seq_update,/*for sequential or rand update*/
     a_index_sample,
     Hamming_plot,
     fscale,
     fsep,
     screenend,
     keyindex, /*flag keyindex shown*/
     itt_step,
     frozen_islands,
     rule_unmixed,     /*to toggle mixed-single rule/s*/
     cell_not_changed,
     **last_state1; /*state at timestep t-1,t-2,...t=10*/       
  unsigned long
     stp_speed,   /*to slow down space-time patterns*/
     ittcount, /*counts forward itterations*/
     statrule_index, /*index for loading stat sample rules*/
     mincount, /*April 2018*/
     maxcount; /*for amplitude/frquency of pulsing*/     
  float 
        polyx,polyy,  /*cell distorted by 45 deg*/
        axo_cell_h,
        aa,
        wx,
        **den_state; /*show density...x=t, y=t-1*/
  double hex_rad;
} int_stp;


typedef struct sk_att{ 
  char 
     **att_type_state, /*array of one att state for each att type*/
     **trans_states, /*Feb 2012: array of transient states for current attractor*/
     *frozen_buff,
     *ref_buff,
     skel_val;
  unsigned long
   this_trans_length,
   att_sample_no,
   *att_type_no;    /*freq of each attractor type*/
  unsigned int
     *att_type_period, /*array of periods of each attractor type*/
     *att_type_trans_length, /*array of transients lengths of each attractor type*/
     **dens_seed; /*to keep track of density of seed to uniform point attractors*/
 
  unsigned long
     frozen_1s,
     frozen_0s;
  float 
     percent_frozen_diff, /*% diff allowed for unchanged frozen*/
     percent_match,       /*% match of skeleton types*/
     *att_type_avtrans,/*av length of trans for each att type*/
     *type_fr0s,  /*prop frozen 0s for each skeleton type*/
     *type_fr1s;  /*prop frozen 1s for each skeleton type*/

} sk_att;

/*for v/k trees*/
typedef struct s_node {
  char value; //0 to nhood
  char level; // max = value_range
  unsigned int t_index;
  char num_children;
  struct s_node **children;
  char *childindex;
} s_node;

EXT struct s_node **v_tree; /*for v/k trees*/ 

/* xwindows compatability */

#if __WATCOM__
#   define getx _getcurrentposition().xcoord
#   define gety _getcurrentposition().ycoord
#   define myrand() rand()
    /***for printer***/
#   define ESC	'\x1B'
#   define LPT1	0
#   define LPT2	1
#   define freeimage(a) free(a)
#   define prn_putc(x) _bios_printer(_PRINTER_WRITE,LPT1,(x))
#   define HORIZ_DIR 0  /*Left to right*/
#   define VERT_DIR  1  /*Bottom to top (rotated 90)*/
#   define SOLID_FILL 1       /* Solid fill         */
#   define INTERLEAVE_FILL 9  /* Interleaving lines */
#   define CLOSE_DOT_FILL 11  /* Closely spaced dots*/
#endif

#if __WATCOM__||__UNIX__
/*limitL supersededby  max_exh_lu for exhaustive algo which depends on value_range*/
#   define limitL 31  /*applies to seq-update only*/
#   define limit2d 255
#endif

#if __UNIX__
   /************* redefine fill pattern  *********/
#   define SOLID_FILL FillSolid
#   define INTERLEAVE_FILL FillStippled
#   define CLOSE_DOT_FILL FillSolid
#   if __UNIX__ || __SOLARIS__ || __IRIX__ || __DARWIN__ /* IRIX added by Oscar */
#      ifndef __CYGWIN__
#         define log2(x) (log10(x)*(log((double)10)/log((double)2)))    
#      endif   
#   endif
#endif

/*note (pos)>>3 = pos/8 and (pos)&7 = pos%8, faster*/
#define get_bit(array,pos) ((array[(pos)>>3]>>((pos)&7)) & 1)
#define set_bit(array,pos,bit) {if (bit) array[(pos)>>3] |= 1<<((pos)&7);\
			       else array[(pos)>>3] &= ~(1<<((pos)&7));}
#define set_bit0(array,pos) array[(pos)>>3] &= ~(1<<((pos)&7))
#define set_bit1(array,pos) array[(pos)>>3] |= 1<<((pos)&7)


#ifndef PI 
#   define PI   (4*atan(1)) /*PI Radians = 180 degrees*/
#endif
#define	deg  (PI/180)   /*deg = 1 degree in radians*/

/***** define arrows ********/
#define LeftArrow -75
#define RightArrow -77
#define UpArrow -72
#define DownArrow -80

/***** note co-ords of current viewport - restore viewport  ********/
#define note_viewport tview_x0=view_x0;\
                      tview_y0=view_y0;\
                      tview_x1=view_x1;\
                      tview_y1=view_y1        
#define restore_viewport setviewport(tview_x0,tview_y0,tview_x1,tview_y1,1)
    
/*redefines and functions for watcom*/
#if __WATCOM__
      /******* rededines ***********/
#  define _atold atol
#  define farcoreleft stackavail

#  define COPY_PUT _GPSET  /*Copies source bitmap onto screen */
#  define XOR_PUT  _GXOR   /*Exclusive ORs source image with that already onscreen*/
#  define OR_PUT   _GOR    /*Inclusive ORs image with that already onscreen*/
#  define AND_PUT  _AND    /*ANDs image with that already onscreen */
#  define NOT_PUT  _GRPESET/*Copy the inverse of the source*/

#  define rectangle(left, top, right, bottom) \
	_rectangle(_GBORDER,(left),(top),(right),(bottom))

#  define moverel(dx,dy) _moveto((dx)+getx,(dy)+gety)
#  define linerel(dx,dy) _lineto((dx)+getx,(dy)+gety);

#  define moveto _moveto
#  define lineto _lineto

   /*DOS getimage function*/
#  define getimage _getimage
/*#  define putimage _putimage ..this is now a function in g_set */
#  define imagesize _imagesize
#  define setcolor _setcolor
#  define getcolor _getcolor
#  define getpixel _getpixel
#  define clearviewport() _clearscreen((_GVIEWPORT))
#  define cleardevice()   _clearscreen((_GCLEARSCREEN))
 
#  define circle(xcentre,ycentre,radius) \
   _ellipse(_GBORDER,(xcentre)-(int)ceil(radius),\
		  (ycentre)-(int)ceil(radius),\
		  (xcentre)+(int)ceil(radius),\
		  (ycentre)+(int)ceil(radius))

  /********** functions for watcom  ******************/
    extern void
     putimage(int x, int y, char *image,
	      int drawing_mode, char *which_image),/*April 09*/
     outtext(char *buf),
     line(signed int xpos,signed int ypos,
		  signed int xpos1,signed int ypos1),
     putpixel(signed int xpos, signed int ypos, signed int color),
     setfillstyle(signed int pattern, signed int color),
     bar(signed int left, signed int top,
		  signed int right, signed int bottom),
     bar3d(signed int left, signed int top,
	   signed int right, signed int bottom,
		 signed int depth, signed int topflag),
     fillpoly(signed int numpoints, signed int *polypoints);

  extern signed int
    getmaxx(void),
    getmaxy(void),
    textheight(char *buf),
    textwidth(char *buf);

  extern signed int text_pix_width(char *textbuf);//16 July 2023
  extern unsigned long get_memory(void);
#endif

#if __UNIX__
   /************** redefine various graphics functions  *********/
void reallocate_pixmap(int left, int top, int width,
		 int height, Pixmap *the_pixmap);

/*#   ifndef __SOLARIS__*/
#if !defined(__SOLARIS__) && !defined(__IRIX__) && !defined(__DARWIN__)  /* IRIX added by Oscar */
       /*Declare functions with are not in the headers*/
       /*Simon 1/1/96*/
       extern char     *sprintf();
       extern char     *fprintf();
       extern char     *printf();
#endif
#    ifndef __LINUX__
        extern long int random(); /*linux 5.1 defines this in stdlib.h*/
#    endif

#    if !defined(__IRIX__)            /* IRIX added by Oscar */
         extern int   gettimeofday();
#    endif
     /* extern int   gettimeofday();*/


#  define _atold(a) atol(a)
#  define rectangle(a,b,a1,b1) XDrawRectangle(D,*current_draw,Gc,a,b,(a1)-(a),(b1)-(b))

#  define cleardevice()  XClearWindow(D,W)
#  define circle(x,y,radius) \
     XDrawArc(D,*current_draw,Gc,x-radius,y-radius,radius*2,radius*2,0,360*64)
#  define line(x,y,x1,y1) XDrawLine(D,*current_draw,Gc,x,y,x1,y1)
#  define rand() random()
#  define myrand() random()

#  define COPY_PUT GXcopy   /*Copies source bitmap onto screen */
#  define XOR_PUT  GXxor    /*Exclusive ORs source image with that already onscreen*/
#  define OR_PUT   GXor     /*Inclusive ORs image with that already onscreen*/
#  define AND_PUT  GXand    /*ANDs image with that already onscreen */
#  define NOT_PUT  GXinvert /*Copy the inverse of the source*/

   /*new drawing routines*/
   void getimage(int x, int y, int x1, int y1, Pixmap *image);
   void putimage(int x, int y, Pixmap *image, int drawing_mode, char *which_image);
   void freeimage(Pixmap *image);
   void copy_part_image(Drawable *source_d, Drawable *dest_d,
			int source_x, int source_y,
			int dest_x, int dest_y,
			int width, int height);

   /*new xwindow functions*/
   extern char resize_window(void);
   extern void  show_old_colors(void),
	     revise_graphics(void),
	     close_graphics(void),
             free_fonts(void),
             /*resize_window(void),*/     /*New -- simon*/
	     redraw_window(void),
             setup_fonts(signed int p_size),
             setfillstyle(signed int pattern, signed int color),
	     moveto(signed int xpos, signed int ypos),
	     moverel(signed int xpos, signed int ypos),
	     outtext(char *textbuf),
	     setcolor(unsigned char thiscolor),
	     clearviewport(void),
	     linerel(signed int dx,signed int dy),
	     lineto (signed int x,signed int y),
	     bar(signed int a,signed int b,
		      signed int a1,signed int b1),
	     bar3d(signed int a,signed int b,
		signed int a1,signed int b1,
		     signed int dummy1,signed int dummy2),
	     fillpoly(signed int numpoints,signed int polypoints[]),
	     fillcircle(signed int x,signed int y,
				       signed int radius),
	     putpixel(signed int xpos, signed int ypos,
					    unsigned char color),
	     printimage(void);
   extern signed int textwidth(char *textbuf),
		    getmaxx(void),
		    getmaxy(void);
   extern signed int text_pix_width(char *textbuf);//16 July 2023
   extern unsigned char getcolor(void);		     

    extern unsigned long getpixel(signed int x,signed int y),
                   filelength(signed int fid);
   /*different for DOS*/
   extern void flashing_cursor(signed int startx,signed int endx,
	  signed int starty,signed int endy,
	  signed int xl,signed int yt,signed int xr,signed int yb,
			     unsigned char cursecolor);
#endif

#if __WATCOM__
   extern void flashing_cursor(signed int xl,signed int yt,signed int xr,
		    signed int yb,unsigned char cursecolor);
#endif
extern void setviewport(signed int left,signed int top,
		    signed int right, signed int bottom,
		    signed int clip),
            pieslice(char node_outline,signed int x,signed int y,
		    signed int s_angle,signed int e_angle,signed int radius);

/************* postScript functions *************/
extern void nodetext_ps(char ps_type,char bcolor,
			char *text,signed int px,signed int py);//July2023
extern void line_ps(signed int px0, signed int py0,
			    signed int px1, signed int py1);
extern void right_jtext_ps(signed int px,signed int py,char *text);
extern void resetfont_ps(char *thisfont,signed int newpoint);
extern void rect_outline_ps(signed int startx, signed int starty, 
			    signed int widthx, signed int heighty);
extern void rect_fill_ps(signed int startx, signed int starty, 
			 signed int widthx, signed int heighty);
extern void hex_outline_ps(void);
extern void hex_fill_ps(void);
extern void block_fill_ps(signed int px, signed int py);
extern void block_stroke_ps(signed int px, signed int py);
extern void lineto_ps(signed int px, signed int py);
extern void lineto_stroke_ps(signed int px, signed int py);
extern void moveto_ps(signed int px, signed int py);
extern void color_ps(char thiscolor,char pcolor);/*includes gray*/

extern void circle_ps(signed int px, signed int py, double prad);
extern void circle_fill_ps(signed int px, signed int py, double prad);
extern void smallspot_ps(signed int px, signed int py, double dia);
extern void thick_line_ps(double how_thick, signed int  px0, signed int  py0,
                                            signed int  px1, signed int py1);
extern void line_block_ps(signed int *poly);
extern void arrow_block_ps(signed int *arrow);

extern void prepare_basinPS(char ps_type,char include_all);/*basin=1*/

extern void sp_node_ps(char node2d,char* array,signed int px,signed int py,char color);
/*for space-time patterns*/
extern void save_to_PostScript(char* array, signed int zi,signed int zj,signed int zh,
          unsigned int patch_size,char cellscale,char show_2d_divs,unsigned char divcolor,
	     char show_dots,char post_hex2d,char gaps_in_string);

/**************************new June2020***********************/
extern void set_color_order_nhd(char shuffle); /*/*shuffle nhd colors except white and black*/

/************* new functions *************/
extern void /*these were seperated out from transform_rule(unsigned int cellindex)*/
            complementary_transformation(char *xrule,
					 signed int xtablebytes,signed int xtablemax),
            negative_transformation(char *xrule,
				    signed int xtablebytes,signed int xtablemax),
            reflection_transformation(char *xrule, char xnhood,
			   signed int xtablebytes,signed int xtablemax);

extern void implement_fraction_values(char isrule,char seed_all,
                        char *thisarray,signed int thistotal);
extern void set_fraction_values(char isrule,signed int thistotal);
extern void check_wiring_still_local(void);
extern void draw_rule_box(signed int rule_box_width,
                             char *thistext,char thisnhood); 
  /*smaller top-right box showing new rules, on-the-fly, samples, automatic & etc*/
extern void forward_onthefly_bottom_prompts(void); /*...in the bottom window only if stp active*/
extern unsigned int next_time_step(		    
                    char **thisrule, /*compute the next time-step*/
                    char *state1a, /*current state*/
                    char *state2a, /*next state*/
		    char this_partial_order,/*separated from forxx.c function May07*/
		    char  *net_subset,
		    char forwards_only,
                    unsigned int *pnhood, 
                    unsigned int n,
                    char this_rule_unmixed);
extern void back_onthefly_prompts(void);

/************** multistate functions ************* */
extern void majority_rule(char *thisrule, char thisnhood, 
                                    signed int tablemax);
extern void majority_tcode(char *thistcode, char thisnhood, 
                                 signed int tablemax);
void majority_or_fprintf_vcode(char majority,
			  char *codetable,char this_nhood);
extern void draw_hexagonal_2d_cell(double this_hex_rad,
       float this_cellscale,
       char this_show_2d_divs, char this_dots, unsigned char thiscolor,
                            unsigned char this_divcolor, 
                              signed int x1,signed int y1);
extern void set_up_v_code(void);
extern void free_tree(s_node *root, char *space);
extern void free_v_code_arrays(void);
extern unsigned int load_save_ascii_rule_seed(char load_save, 
              char rule_seed,char* base_buf,unsigned int base_size);
extern unsigned int load_Golly_seed(char load_save,char *seed,unsigned int lineL);
extern unsigned int search_tree(char *input, 
            char length, s_node *root, char index);
extern char post_func(char nhoodz, char *thisrule, char details, char box, 
                             signed int fid, char filedata);
extern void allocate_mem_tcode0_extra(char thisnhood);
extern void free_mem_tcode0_extra(void);
extern void run_forward(char **thisrule);
extern void dec_to_value_line_flex(char* value_line,
	   unsigned long decvalue, signed int size, 
			   signed int vr, signed int vb);


extern unsigned long dec_equiv_flex(char *temparray, char leftpos, 
				signed int vr, signed int vb);
extern signed int check_value_bits(signed int vr);
extern unsigned long max_dec_rule(signed int tablemax, char tvalue_range);
extern void chain_rule(char *thisrule, char thisnhood, 
                   signed int tablemax, unsigned int cindex);
extern void altenberg_rule(char *thisrule, char thisnhood, 
                                 signed int tablemax);
extern void altenberg_kcode(char *thiskcode, char thisnhood, 
                                 signed int tablemax);
extern void isotropic_rule(char show_details, char *thisrule,
       char thisnhood, 
       signed int start_index,signed int end_index,
                      signed int tablemax, char do_what);

extern void reflect_m_ruletable(char nhoodz, char *thisrule, char *revrule);
extern void dec_to_value_line(char* value_line,
		       unsigned long decvalue, signed int size);
extern signed int get_value(char *array, 
                                  unsigned int ct_count); /*get a value*/
extern signed int get_value_flex(char *array, unsigned int ct_count, 
		     signed int vb); /*flexible - specify no of bits needed*/
extern void set_value(char *array, 
      unsigned int ct_count, signed int tempvalue); /*set a value*/
extern void set_value_flex(char *array, /*flexible - specify no of bits needed*/
	       unsigned int ct_count,signed int tempvalue,signed int vb);
extern void show_multistate_color_key(char show_delete);
extern void setup_value_colors(char first_time);
extern void rearange_value_colors(void);
extern void code2rule(char *ruletable, char *codetable, char this_nhood);
extern void v_code2rule(char *ruletable, char *codetable, 
                         char this_nhood, char c2r);
/*recent functions*/
extern char mutate_rule(char nhoodz);
extern void mutant_one_screen_single(void);/*mutant basin on same screen*/

extern char jump_graph_table(unsigned int att_types,sk_att *sk,char this_graph_type);
extern void hist_save_load(unsigned int thismax_histno,/*Seperate function for*/
          unsigned int *this_hist); /*filing .his files*/

extern void draw_k_hist(char in_out); /*k (input) or output frequency histogram*/
extern void new_ant(void);
extern void thickline(char selflink,signed int x1, signed int y1,
	       signed int x2, signed int y2, 
                       unsigned char thiscolor, 
                       double thisthick, double maxthick);
extern unsigned long atolu(char *string);
extern void set_2d_3d_coords(int_stp *it);
extern void set_i2dxj2d(void);
extern void nhood_lb_ub(void);
/*extern void draw_save_3d_frame(char fscale, 
        signed int sboxx, signed int sboxy);*/
extern void change_net_size(unsigned int newL);
extern void set_cellscale(char nhoodz, char isrule);/*changed to void 3/2014*/
extern void reset_stpwidth(ent_eeg *eg,int_stp *it);
extern void erase_memory_box(float showmem);
extern void load_nhoodmix(void);
extern void reset_neutral_buffs(void);
extern void restore_network_buffs(void);
extern unsigned long order_to_index(unsigned int *order,
			       unsigned int thislineL);
extern void index_to_order(unsigned long index,
       unsigned int *thisorder,unsigned int thislineL);
extern unsigned long fact(char num);
# if __UNIX__ /*long long doesnt work for DOS */
   extern unsigned long long longlong_fact(char num,char startnum);
# endif
extern unsigned long long_fact(char num,char startnum); 
extern void set_seq_update(void);
extern void set_small_font(void);
extern void set_medium_font(void);/*new Dec 2001*/
extern void restore_def_font(void);
extern signed int myopen(char *this_filename,
			   char write, char append); /*open file*/
extern void file_error(char *this_filename); 
extern char event_ready(void);
extern char select_stat_filename(auto_ent *ae);
extern void   
   /*frame for graph alongside space-time pattern*/
   draw_stpframe(signed int stpwidth,float eegwidth),
   
   draw_entgraph_frame(char draw_clear,
      signed int stpwidth, char show_edata,char ylabel);   
extern unsigned long
   stat_rule(char autostat,unsigned long statrule_index,
                    int_stp *it,signed int stpwidth);

/* * * * * * * * * * * * * * * * * * * * */
extern void
   interrupt_key_index(ent_eeg *eg,
                       int_stp *it),
   glider_rule(int_stp *it),
   plot_diff_pattern(
       diff_var *dp,
       ent_eeg *eg,
       int_stp *it),

   show_frozen_skel_hist(sk_att *sk,
                         diff_var *dp,
                         int_stp *it,signed int stpwidth),
   show_att_type_hist(sk_att *sk,
                      diff_var *dp,
                      int_stp *it,signed int stpwidth),
   draw_2d_frame(
       ent_eeg *eg,
       int_stp *it),

   interrupt_stp(
       diff_var *dp,
       auto_ent *ae,
       ent_eeg *eg,
       int_stp *it),

   entropy_eeg_plot(
       auto_ent *ae, 
       ent_eeg *eg,
       int_stp *it,
       unsigned char nhdcolor),
   
   setup_diff_plot(diff_var *dp),

   show_diff_plot(char redraw,diff_var *dp),  
   draw_diff_graphframe(diff_var *dp, char first, char xlog, char ylog);

extern char moment( 
	  auto_ent *ae,
	  ent_eeg *eg,
	  int_stp *it,
	  char *thisrule);

/************* declare functions 13 May 1993 ***********/
extern void
     draw_Derrida_plot(char **thisrule),/*changed from (void) May07 to allow
                                   totalistic codes*/
     wire_2d_local(unsigned int poss,unsigned int *pnhood),
     wire_3d_local(unsigned int poss,unsigned int *pnhood),
     draw_Hamming_plot(char draw_clear,signed int stpwidth),
     /********** memory ***********/
     allocate_mem_buffers(void),
     free_mem_buffers(void),
     allocate_mem_CA_states(void),
     free_mem_CA_states(void),
     allocate_mem_rule0(char thisnhood),
     free_mem_rule0(void),
     allocate_mem_iso(char thisnhood),
     free_mem_iso(char thisnhood),
     allocate_mem_rule0_extra(char thisnhood),
     free_mem_rule0_extra(void),
     allocate_mem_rulemix(char thisnhood),
     reallocate_mem_rulemix(char thisnhood,char increace),
     
     free_mem_rulemix(void),
     allocate_mem_tcode0(char thisnhood),
     allocate_mem_tcodemix(char thisnhood),
     reallocate_mem_tcodemix(char thisnhood,char increace),
     free_mem_tcode0(void),
     free_mem_tcodemix(void),
     allocate_mem_diffrules(char thisnhood,signed int nodiffrules),
     allocate_mem_diffcodes(char thisnhood,signed int nodiffrules),
     free_mem_diffrules(signed int nodiffrules),
     free_mem_diffcodes(signed int nodiffrules),
     allocate_mem_all_0s_all_1s_rules(char thisnhood),
     free_mem_all_0s_all_1s_rules(void),
    //allocate_mem_nhood_matrix(char thisnhood),
     free_mem_nhood_matrix(char thisnhood),
     allocate_mem_Z_parameter(void),
     free_mem_Z_parameter(void),
     outof_memory(char *what),

     /******** ca parameters********/
     setpback_x_lines(char xlines),
     select_linelength_singlebasin(void),
     select_linelength_31(void),
     select_linelength_range(void),
     select_nhood_size(char inbox),
     select_totalistic(void),
     /*for tickoffset_bit array*/
     set_bitlong(char *array,unsigned long pos,char bit),
     define_bits(char nhoodz,char isrule,char *array,unsigned int leftpos,
	    unsigned int rightpos),
     random_bits(char nhoodz,char isrule,char seed_all,
		      char hex, char *array, unsigned int leftpos),
     dec_to_bit_line(char* bitline, unsigned long decvalue,
					    signed int size),
     select_pattern_scrolling(void),
     format_draw(void),
     set_mutation(void),
     select_stepforward(void),
     select_foreward_back(void),
     forward_only_para(void),
     wire_rule_extra_cell(char increace),
     upstream_only(void),
     draw_range_single(void),
     draw_range_field(void),
     draw_field(void),
     progress_bar(void),
     print_field_data(void),
     next_line(float chwidth,float lineht),
     
     print_current_state(char *temp, char color),
     print_current_state_h(char *temp, char color),
     print_current_state_twod(char *temp, char color, char zero_color),
     show_rule_bottom(char nhoodz,char printout,char* thisrule,
					  unsigned int cellindex),
     open_graphics(char firstgraphics, char sei),
     setup_plot(void), /*set up viewport and level intervals*/
     amend_layout(void),
     data_att(void),/*set up required data in attractors*/
                    /*split from  setup_plot() Aug 2000*/
     postScript_basin(void), /*set postScript printing for basin*/
     jumpgraph_basinfield(void),/*set jump-graph for basinfield*/
     show_statespace_matrix(char *thisstate),
     run_backward(void),
     prepair_pre_rand(void),
     free_pre_rand(void),
     pre_images_rand(void),
     prestate_successor_pairs(void),/*set up state-successor pairs*/
     draw_basin(void),
     draw_fan(void),
     z_parameter_all(char nhoodz,char showz,char* thisrule), 
     z_parameter_all_mvalue(char nhoodz, char showz, char *thisrule),
     set_canalyzing_net(char forcezero),
     set_canalyzing_rule(unsigned int poss),
     repeating_seg_2d(char *array);

extern char* rotate_array(char nhoodz,char *array,char direction,
			   char isrule,signed int rotinterval);
extern char* rotate_array_2d(char *array,char direction,
			   signed int rotinterval);
			   			   
extern void end_page(char cur_scale, char keyindex);

extern char
     allocate_mem_nhood_matrix(char thisnhood),
     transform_rule(unsigned int cellindex),
     define_hex(char nhoodz,char isrule,
        char *array,
             signed int hexbyteposl,
		signed int hexbyteposr,float thisxtext),
     keycheck(signed int incount), /*before return was signed int ?? */
     canalyzing(char nhoodz,char showz,char* thisrule),
     rot_cycle_equiv_2d(register char *array),
     trans_sym_2d(register char *array),
     final_quit(void),
     get_bitlong(char *array,unsigned long pos),/*for tickoff array*/
     /*return nhood*/
     interrupt_stp_box(signed int ypos, char* thisrule,
               unsigned long this_ittcount, 
               char* current_state,signed int stpwidth,
                   diff_var *dp, 
                   auto_ent *ae, 
                   ent_eeg *eg, 
                   int_stp *it);
extern unsigned char
     random_seed(unsigned char color1,
                 signed int rand_seed_percent,char show_density),
     random_bitflip_state(unsigned char color1),
     bit_flip(char what,unsigned char color1),
     bit_flipback(unsigned char color1),
     wire_move(char what,unsigned char color1);
    
extern signed int
     print_layered_bitstring(char *array,
	     unsigned int leftpos,char thisscale,
		       char thissep, char makerandom, char isrule),
     select_seed(char box_top_only, 
		 char *thisseed, char *text, char restore_box),
     vgax(signed int xcoord),
     vgay(signed int ycoord),
     memory_box(float showmem, char *thistext),
     set_nhdcolor(char nhood, signed int z),
     print_current_bitstring_hexbytes(signed int maxlines,
            char isrule, char *array,char nhoodz,
		  signed int xright,signed int color,char printer),
     rot_cycle_equiv(register char *array),
     repeating_seg(register char *array),
     input_string(char r, char stringtype);

extern unsigned int
     set_central_block(char keep,char *array),
     dec_equiv_sound(char *temparray,
		      signed int leftpos,signed int rightpos);

extern unsigned long
     dec_equiv(char *array, char leftpos),
     print_bit_line(char *temp,unsigned int size,unsigned int color,
			     signed int cellscale, signed int cellsep);

/************ mouse, boxes, graphs, save/load, printing etc ******************/
extern void
     change_drive_dir(char which),
     save_last_rule(char* rule,char thisnhood),
     load_glider_buf(signed int no_of_glider_rules),
     gofE_z_graph(void), /*graph of garden of Eden dencity - Z parameter*/
     draw_lambda_z_graph(char dontbias), /*graph of lambda-Z*/
     allocate_code_mem(void), /*to avoid plotting equiv codes*/     
     show_pre_fansize_freq_hist(void),
     load_save_exhaustive(char load_save),
     save_data(char *buf),
     save_binary_data(unsigned char *buf,unsigned long sizeofbuf),
     save_screen(void),
     load_screen(void),
     /*create mouse*/
     mouse_call(int regeax,int regbx,  /*must be int*/
			  int regcx,int regdx),
     /***for printer*****/
#    if __WATCOM__
        printimage(char Land_Port,
          unsigned char notcolor1,unsigned char notcolor2,
	     signed int x1,signed int y1,signed int x2,
		   signed int y2),
#    endif
     print_out(char *array),
     draw_bottom_title(char resize), /*was void, changed Oct 99*/
     finish_options_box(char alloptions),
     get_prompt_box(signed int bufno,char lines), 
                                     /*gets image of prompt box*/
     uncover_free_prompt_box(signed int bufno),
     erase_prompt_box(char lines),
     
     erase_free_hint_box(signed int startx),
     
     erase_box(signed int xtopleft,signed int ytopleft,
		 signed int xbotright,signed int ybotright),
     finish_options(char alloptions);/*print-save-load-etc options*/
extern char
     draw_hint_box(char pase,char savehintbox,
                        char* thistext,signed int startx),
     select_filename(char *load_save,char *title,
			  char *extention,char *defname),
     select_list_files(char* filespec,signed int leftbox,signed int topbox),
     load_last_rule(char* rule,char thisnhood);

extern unsigned char
     load_save_wrs
	  (char load_save,char* wrsbuf,char wrstype);/*return nhood*/
extern signed int
     inset_prompt_box(signed int vfactor, signed int charlen,
                            char* thistext,char this_font),
                      /*return width of box, inset box within prompt box*/
     draw_prompt_box(char lines),  /*returns start x position of text*/
     draw_box(signed int bufno,signed int xtopleft,signed int ytopleft,
		signed int xbotright,signed int ybotright,
	      char outline,signed int bcolor);
     /*rule sample statistics*/
extern unsigned int load_rule_stats(char repeat_sample, signed int stpwidth);
/************* random Boolean network functions *************/
/************* random wiring *************/
extern void
     allocate_mem_wiring(void),
     reallocate_mem_wiring(char increace),
     free_mem_wiring(void),
     select_wiring_options(void),
     wire_up_network(char net_arch),
     randomly_wire_cell(unsigned int  poss,unsigned int  maxL),
     oneD_local_wire_cell(unsigned int  poss,unsigned int  maxL),
     wireup_2d_nhood(signed int itop,signed int jtop,
			    signed int ibot,signed int jbot),
     wireup_3d_nhood(signed int itop,signed int jtop,signed int htop,
		     signed int ibot,signed int jbot,signed int hbot),
    
     cell_out_freq(void); /*calc cell output-wire frequency*/
     
    /*showout=1..shows output frequency histogram
      parts=1....pause on screen full
      startindex.. L-0
      return.....CA index reached*/
extern unsigned int
     load_save_nhoodmix(char load_save);

/************* mixed rules *************/
extern void
     show_w_r_scheme(void),
     revise_rule_or_code(unsigned int thisposs),
     /*for 2-d space-time patterns*/
     draw_axon_plane(float fscale,signed int tempy,char draw_3d_grid),
     /************* learning algoritm *************/
     shuffle_order(signed int* array, signed int size),     
     setup_ppstack_hist(void);
extern char sculpt_basin_field(char highlight_only);
extern signed int rule_selection(void); /*returns gety()*/
     
/****************************************************************/
