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

/****** network graph, jump-graph (meta-graph 2002) and ibaf-graph, revised Nov 2022********/
#include "edecfunc.h"

/***************  list of functions in this file ************/
/*char jump_graph_table(unsigned int att_types,sk_att *sk,char this_graph_type);*/
void print_exh_pairs(char *this_exh_pairs);
void save_graph_PScript(unsigned int most_recent_node,signed int X1, signed int Y1,
	       signed int X2, signed int Y2,
	       signed int wox, signed int woy);
float draw_predefined_stp(signed int X1, signed int Y1,
	       signed int X2, signed int Y2,
	       signed int wox, signed int woy);
float draw_circle_graph(signed int X1, signed int Y1,
              signed int X2, signed int Y2,
	      signed int wox, signed int woy,
              double w_angle);
float draw_2d_graph(signed int X1, signed int Y1,
              signed int X2, signed int Y2,
	      signed int wox, signed int woy);
float draw_3d_graph(signed int X1, signed int Y1,
              signed int X2, signed int Y2,
	      signed int wox, signed int woy); 
void unscramble_graph(signed int X1, signed int Y1,
              signed int X2, signed int Y2,signed int wox, signed int woy);
void shuffle_order1(unsigned int *shuffarray, unsigned int size);
void reorder_rank(unsigned int *reorder_graph);
char save_load_graph_layout(char save_load);
void show_table(char type, signed int X1, signed int Y1,
		           signed int X2, signed int Y2);
void intest_path(char what);
void prob_ant_prompts(char show_ant, char rand_ant);
void prob_ant(signed int wox, signed int woy,
                    signed int X1,signed int Y1,
		       signed int X2,signed int Y2);
void draw_jump_graph(unsigned int most_recent_node,signed int wox, signed int woy,
                    signed int X1,signed int Y1,
		       signed int X2,signed int Y2);
void jump_graph_vertex(signed int zw,float node_size,
              unsigned char thiscolor,signed int X1,signed int Y1,
			  signed int X2,signed int Y2);
/*void thickline(char selflink,signed int x1, signed int y1,
	       signed int x2, signed int y2, 
                       unsigned char thiscolor, 
                       double thisthick, double maxthick);*/
void manipulate_jump_graph(signed int wox, signed int woy,
                           signed int X1,signed int Y1,
		           signed int X2,signed int Y2,
                           float rot_angle);
void prompt_and_component(char components, char blockset,char link_step,
       unsigned int most_recent_node, unsigned int prev_node);

char block_or_slice(char components,char blockset,unsigned int poss,unsigned int prev);
void rotate_component_graph(char clockwise,float rot_angle,
                            signed int c_x, signed int c_y);
void flip_component_graph(char which,
			  signed int c_x, signed int c_y);
//EC stands for Expand/Contract
void EC_links_component_graph(char which,
			      signed int c_x, signed int c_y);
void EC_nodes_component_graph(char which,unsigned int most_recent_node
			      ,char blockset);
void EC_equalise_component_graph(unsigned int most_recent_node,char components,char blockset);
void nodes_type_component_graph(char which,unsigned int most_recent_node,char blockset);

void disconnect_node(char what,
	 unsigned long *node_outputs, unsigned long *node_inputs,
	 char components, unsigned int poss, unsigned int prev_node);
void node_pair_link(char what,
   char components, unsigned int poss, unsigned int prev_node);
void graph_in_out_components(char components,char link_step,
                               unsigned int poss);
void compute_link_angle(signed int x1, signed int y1,
                        signed int x2, signed int y2);
void reset_nodesize(void);

/*----------------------local variables in this file-------------*/
char show_labels=0; //for creating and placing an arbitrary label at a single node
char **text_label; //array for label at each node

char moving_with_mouse=0; /*to stop vertex changes if not required*/

float start_c_scale,c_scale;
char fragment=0;//acting on just a fragment of a graph fragment was local)
char just_component=0; //to shoe just the component and and manipuale
char just_fragment=0; //to show just the fragment as defined, and manipuale it
char in_manipulate=0;//inside manipulate_jump_graph()
char show_numbers=0;//different node type presentations

signed int start_pointsize,label_pointsize,current_text_size,this_text_size;

//in jump_graph_table
unsigned long *histnodesize; /*to scale histogram nodes according attractor frequency*/
//unsigned int *m_att_period, /*global variable calloced in runxx.c, attractor periods in field, for jump_graph*

/*'f' and 'a' only*/
//local: unsigned int *wnhood
//local: char **att_check,*temppoint,*current_state,
/*'s' only*/
signed int **basin_pos_backup; //for (zw=0;zw<=node_no;zw++) /*copy backup basin positions to re-enter*/
/*all*/
float *m_node_size; /* for scale_m_nodes==1 according to inputs, can be resized (was local)*/
float *s_node_size; /* new jan2021, for standard nodes scale_m_nodes==0, ignoring inputs, can be resized*/

signed int *text_node_size; //added Nov 2021
unsigned char *basin_color;
unsigned int **basinjumps,**b_j; //for (z=1;z<=node_no;z++)

/*for jumpgraph*/
char still_jump_graph=0; //fudge to use the graph_type='n' for the jump-graph without links
float rot_angle,node_factor,link_factor; /*was local in "draw jump-graph"*/

char *frag_node_types;  //to show specific node types in fragnents
 
unsigned int node_no=0,*outside_inputs;
signed int suppress_u_links=0,u_threshold=0,isolate_unreachable=0;

float linkangle,abs_angle,
      w_cyclerad,arrow_size; /*to expand/contract links, and arrows*/
unsigned int m_size;
double m_space;
char graph_type, /*'f','n','s', 't','a'*/
     scale_m_nodes,scale_links,no_links=0,node_numbers=1;
char *linknet; /*to separate components/fragments*/
char *component_linknet; /*to conserve active component if other component suppressed with just_component*/
/*new variables Dec 2001*/
/*m_basin_volume is now unsigned long, global variable, allocated in run*.c*/

unsigned char *netnodesize, /*to scale network nodes according to k*/
     show_arrows,  /*toggle arrows*/
     quick_move=0; /*tog between updating net while dragging or at end*/
char graph_postscript=0,
     *filename_graph_PS, /*to save the network or jump_graph as a vector postscript*/
     graph_hex2d; /*to force hex or square 2d*/
unsigned int startBlock,endBlock;
char network_outputs=0; //toggle scaled network nodes between k and outputs
static int maxLabel=90;
/*********** compute and show jump-graph table, 28 July 2000 ***********/
char jump_graph_table(unsigned int att_types,sk_att *sk,char this_graph_type){
  signed int xbox,z,u,i,temp,bitflip,btarget,btype,attno,
               temp_xoffset,temp_yoffset,value,end_wait_text;
  unsigned int zw,zz,z1,itcount,n,*wnhood,
                 max_period,max_trans;/*for histogram*/
  char **att_check,*temppoint,*current_state,match_found=0,jump_datapause;
  unsigned long total_steps=0, steps_so_far=0;
  float jump_startrad;
  
    //show_numbers=shownumbers; //don't copy start node type from drpara, to complicated
    //if (shownumbers==3 && showbits_1d_as_2d==1) show_numbers=4;
         //-1 none (miss out), 0 spot/disk, 1 dec(lineL<32), 2 hex, 3 1d bits,  3 2d bits    
    show_numbers=0; //start with discs in all cases
    
    start_pointsize=pointsize;
    label_pointsize=pointsize;//to change dec or hex label size
    current_text_size=pointsize;

    graph_type=this_graph_type;
    //fprintf(stderr,"\ngraph_type=%c",graph_type);    
    /*graphtypes*/ 
    /*graph_type=='f' for JUMP-graph, also if jump_layout_only JUMP-graph(nolinks))*/  
    /*graph_type=='n' for NET-graph, also if jump_layout_only==1 JUMP-graph(nolinks)*/
    /*graph_type=='t' for interactive state transition graphs (istr_graph), 
                         fields, single bains/subtrees, similar to 's' but basically 'n'*/    
    /*graph_type=='s' for ibaf graph (interactive basin of attraction field), March 2021*/ 
    /*graph_type=='a' for JUMP-graph(hist)*/
    
    //prompt to initiate ibaf-graph or istr_graph
    if (graph_type=='s' || graph_type=='t' || graph_type=='f'){ //s=ibaf-graph, t=istr-graph, 'f'=jump-graph
          node_numbers=1; //reset node (disc) number to start with white number in disc
          if  (graph_type=='s')
	     node_no=(unsigned int)(pow(value_range,(double)lineL)); //size of state-space
          else if (graph_type=='t')
	     node_no=istr_node_count; //nodes (states) counted sofar
	  else if (graph_type=='f')
	     node_no=basintypeno; /*number of basins*/
          draw_box(23,trboxw,vgay(30)+vgay(9)+vgay(5),
	          Maxx-2,vgay(30)+vgay(9)+vgay(5)+CHeight+vgay(3),1,0);	  
          if (graph_type=='s') sprintf(textb[0],
	      "next-q, %d nodes, ibaf-graph-i:",node_no);
	  else if (graph_type=='t') sprintf(textb[0],
	     "next-q, %d nodes, istr-graph-s:",node_no);
	  else if (graph_type=='f') sprintf(textb[0],
	     "next-q, %d nodes, jump-graph-j:",node_no);
          outtext(textb[0]);
          input_string(1,0);
          erase_box(trboxw,vgay(30)+vgay(9)+vgay(5),
                    Maxx-2,vgay(30)+vgay(9)+vgay(5)+CHeight+vgay(3));
          if (graph_type=='s' && is[0]!='i') return(0);
	  if (graph_type=='t' && is[0]!='s') return(0);
	  if (graph_type=='f' && is[0]!='j') return(0);
	  sprintf(textb[9],"%s","boximage[23]");
          putimage(trboxw,vgay(30)+vgay(9)+vgay(5),
		                           boximage[23],COPY_PUT,textb[9]);
          freeimage(boximage[23]);	  
    }
    if (graph_type=='t'){ //t=istr-graph, s=ibaf-graph, set up index_successor      
      unsigned int z,nc;
      if (dontcopytrees || dontcompress==0){//for suppressed equivalents in att cycles, or try "dontcompress"
         for (z=0;z<=istr_node_count-1;z++) index_successor[z]=-1;
      }	 
      //fprintf(stderr,"\nset up index_successor, istr_node_count=%d",istr_node_count);
      for (nc=0;nc<=istr_node_count-1;nc++){
	  for (z=0;z<=istr_node_count-1;z++){ //check which index state is matched by successor state
	     if (memcmp(pat_state0[z],pat_state1[nc],bytesL)==0){
	         index_successor[nc]=z;
		 //fprintf(stderr,"\nindex(%d:%d)",nc,index_successor[nc]);//????
		 break;
             }		 
	  }
       }
       
       if (direction=='b') index_successor[0]=0; //for upstreem_only subtree
	
       //usefull to show list of istr-graph index->index
       /*for (z=0;z<=istr_node_count-1;z++){
	    fprintf(stderr,"\n%d->%d",z, index_successor[z]);
       }*/
    }
    
    use_preset_basin_pos=0;
    temp_xoffset=xoffset;
    temp_yoffset=yoffset;
    no_links=0;

    jump_startrad=startrad; /*to change scale of basins in jump-graph*/
    jump_datapause=datapause; /*no need for datapause for basins in jump-graph*/
    datapause=0;

    /*reset: suppress links from unreachable basins*/
    suppress_u_links=isolate_unreachable=u_threshold=0;
       
    get_prompt_box(12,4);
    draw_prompt_box(1);
    exh_pairs_in_jump_nodes=0;//to redraw basins within jump-graph nodes if exhaustive_testing
    /*fprintf(stderr,"\nTOP of jump_graph_table, jump_graph=%d dontcompress=%d-- exh_pairs_in_jump_nodes=%d",
      jump_graph,dontcompress,exh_pairs_in_jump_nodes);*/

    if (graph_type=='f' || jump_layout_only){/*jump_layout_only is the jump_graph without links*/
       still_jump_graph=1; //to reconfirm this is a jump graph because for jump_layout_only type=n
       /*close the basin .ps file, otherwise done in main*/
       if (basin_postScript) close(fid_PS); 

       node_no=basintypeno; /*number of basins*/

       //this allows basins to be positioned, with or without compression
       //but nodes can be scaled or standard
       if (jump_layout_only==1){
	   graph_type='n';  //fudge to use the graph_type='n' for the jump-graph without links
           no_links=1;
       }
    }
    /* (graph_type=='f' || graph_type=='n' ||
         graph_type=='t' || graph_type=='s' || graph_type=='a') {*/ // i.e all cases)
    if (1){
       if (graph_type=='a') node_no=att_types; /*attractor types in att histogram*/
       else if (graph_type=='n'){
	  if (jump_layout_only==1) node_no=basintypeno; /*number of basins*/
	  else{
	     node_no=lineL; /*size of network*/
             if (direction=='f' && limitcheck==0){ /*forwards only, for stp*/
                no_links=1;           
                draw_prompt_box(1);
                sprintf(textb[0],
                 "show links -L (caution for large networks), layout only -def:");
                outtext(textb[0]);
                input_string(1,0);
                if (is[0]=='L') no_links=0;
             }
             else{
                draw_prompt_box(1);
                sprintf(textb[0],"no links -N, show links -def:");
                outtext(textb[0]);
                input_string(1,0);
                if (is[0]=='N') no_links=1;
             }
	  }
       }	   
       else if  (graph_type=='s' || graph_type=='t'){		     
          /*copy backup basin positions to re-enter*/
          if ((basin_pos_backup=(signed int**)calloc(node_no+1,
		   sizeof(signed int*)))==NULL) outof_memory("basin_pos_backup");
	  for (zw=0;zw<=node_no;zw++){
	          if ((basin_pos_backup[zw]=(signed int *)calloc(
			2,sizeof(signed int)))==NULL) outof_memory("basin_pos_backup[]");
          }
       
          for (zw=0;zw<=node_no;zw++){
	     //fprintf(stderr,"\n%d: %dx%d",zw,basin_pos[zw][0],basin_pos[zw][1]);//????	     
	     basin_pos_backup[zw][0]=basin_pos[zw][0];
             basin_pos_backup[zw][1]=basin_pos[zw][1];
	  }
       }//else if  (graph_type=='s' || graph_type=='t'){

       /*m_node_size for scale_m_nodes==1, (s_node_size for scale_m_nodes==0*/
       if ((m_node_size=(float *)calloc(node_no+1,sizeof(float)))==NULL) outof_memory("m_node_size");
       if ((s_node_size=(float *)calloc(node_no+1,sizeof(float)))==NULL) outof_memory("s_node_size");
       
       //bufs for text labels
       if ((text_label=(char**)calloc(node_no+1,sizeof(char*)))
				  ==NULL) outof_memory("text_label");
       for (z=0;z<=node_no;z++){ /*textb[9] reserved for putimage()*/
           sprintf(textb[0],"text_label[%d]",z);
           if ((text_label[z]=(char *)calloc(maxLabel,sizeof(char))) //static maxLabel=90
				   ==NULL) outof_memory(textb[0]);
       }
       
       if ((text_node_size=(signed int *)calloc(node_no+1,sizeof(float)))
			       ==NULL) outof_memory("text_node_size");

       for (zw=node_no;zw>=1;zw--){ //initiate node sizes so not = to zero
	  text_node_size[zw]=start_pointsize; //to fix problem of mixed sizes, July2024
       }
       
       if ((basin_color=(unsigned char *)calloc(node_no+1,
		 sizeof(unsigned char)))==NULL) outof_memory("basin_color");

       /*keep count of basin jumps, keep count of directed links in network, 0 to n-1*/
       if ((basinjumps=
              (unsigned int**)calloc(node_no+1,sizeof(unsigned int*)))
			      ==NULL) outof_memory("basinjumps");
       for (z=1;z<=node_no;z++){ 
              if ((basinjumps[z]=
		   (unsigned int *)calloc(node_no+1,sizeof(unsigned int)))
			      ==NULL) outof_memory("basinjumps[z]");
       }
       /*backup of basin jumps*/
       if ((b_j=
              (unsigned int**)calloc(node_no+1,sizeof(unsigned int*)))
			      ==NULL) outof_memory("b_j");
       for (z=1;z<=node_no;z++){ 
              if ((b_j[z]=
                  (unsigned int*)calloc(node_no+1,sizeof(unsigned int)))
			      ==NULL) outof_memory("b_j[z]");
       }
       
       /*no_links=0; 
       if (graph_type=='n' && direction=='f' && limitcheck==0){ //forwards only, for stp
          no_links=1;           
          draw_prompt_box(1);
          sprintf(textb[0],
          "show links -L (caution for large networks), layout only -def:");
          outtext(textb[0]);
          input_string(1,0);
          if (is[0]=='L') no_links=0;
       }
       else if (graph_type=='n'){ 
          draw_prompt_box(1);
          sprintf(textb[0],
          "no links -N, show links -def:");
          outtext(textb[0]);
          input_string(1,0);
          if (is[0]=='N') no_links=1;
       }*/      
    } //if (1){
    
    //to show something is happening for large node_no
    draw_prompt_box(1);
    if (graph_type=='n' && jump_layout_only==1) sprintf(textb[0],
           "computing nodes for layout of %d basins, quit-q, or wait...",node_no);

    else if (graph_type=='f' || graph_type=='a'){
         sprintf(textb[0],
           "computing jump-graph, %d basins, quit-q, or wait...",node_no);
	 //print exh_pairs in terminal
	 /*if (graph_type=='f' && exhaustive_testing){	        
	        print_exh_pairs(exh_pairs_backup); //in the terminal -- to chack if correct
	 }*/
    }
    else if (graph_type=='n') 
       sprintf(textb[0],
           "computing network-graph, %d nodes, quit-q, or wait...",node_no);
    else if (graph_type=='s'){ //for interactive basin of attraction field
       sprintf(textb[0],
           "computing ibaf-graph, %d nodes, quit-q, or wait...",node_no);
       //print_exh_pairs(exh_pairs); //in the terminal -- to chack if correct
    }
    else if (graph_type=='t'){ //for interactive state-transition-graph
       sprintf(textb[0],
           "computing istr-graph, %d nodes, quit-q, or wait...",node_no);
       //do similar as  ... print_exh_pairs(exh_pairs); //in the terminal -- to chack if correct
            
    }   
    outtext(textb[0]);
    end_wait_text=getx;
    inset_prompt_box(0,5,"0%",'d');
   
    /*wont outtext without this - ??*/
    //while(event_ready()==0) break;
    
    if (graph_type=='a'){ /*for a jumpgraph for the attractor histogram*/
      unsigned int zu;
       /*nodesize proportional to attractor type frequency, 0 to n-1*/
       if ((histnodesize=
                (unsigned long*)calloc(node_no+1,sizeof(unsigned long)))
				     ==NULL) outof_memory("histnodesize");
       memmove(histnodesize,sk->att_type_no,
	               (node_no+1)*sizeof(unsigned long));
       
       //was calloced and realloced in runxx.c, but not for graph_type=='a' (histogram)
       if (graph_type=='a'){
          if ((m_att_period=
             (unsigned int*)calloc(node_no+1,sizeof(unsigned int)))
	     ==NULL) outof_memory("m_att_period");
       }
       memmove(m_att_period,sk->att_type_period,
                      (node_no+1)*sizeof(unsigned int));

       max_period=max_trans=0;
       for (zu=0;zu<=node_no;zu++){
	 //fprintf(stderr,"%d",zu);
	 if (m_att_period[zu]>max_period) max_period=m_att_period[zu];
         if (sk->att_type_avtrans[zu]>max_trans) 
                               max_trans=sk->att_type_avtrans[zu]; 
       }
       //jump_graph=1;
    }

    if (graph_type=='f' || graph_type=='a'){  /*JUMP-graph or Jump-graph(hist)*/      
       char *state1m,*state2m;

       m_size=lineL*(value_range-1); 
       if (graph_type=='f') m_space=pow(value_range,(double)lineL);
       else if (graph_type=='a') m_space=sk->att_sample_no;
       
       //not actually relevant required 
       if ((frag_node_types= //to show specific node types in fragnents
	       (char*)calloc(node_no+1,sizeof(char)))
			       ==NULL) outof_memory("frag_node_types*");
          
       /*memory for current state*/
       if ((current_state=(char *)calloc(bytesL,sizeof(char)))
			      ==NULL) outof_memory("current_state");
       /*memory for pseudo-nhood*/
       if ((wnhood=(unsigned int *)calloc(nhood,sizeof(unsigned int)))
			      ==NULL) outof_memory("wnhood");
     
       /*create array of one state in each basin*/
       if ((att_check=(char**)calloc(node_no+1,sizeof(char*)))
			      ==NULL) outof_memory("rcheck");
       for (z=0;z<=node_no;z++){
          if ((att_check[z]=(char *)calloc(bytesL,sizeof(char)))
			      ==NULL) outof_memory("att_check[]");
       } 
          
       for (z=1;z<=node_no;z++) 
                   memmove(att_check[z],m_att[z][1],bytesL);
	  
       

       /*fprintf(stderr,"\n -----------------4 about to run -----------");*/
       if ((state1m=(char *)calloc(bytesL,sizeof(char)))==NULL) outof_memory("state1m");
       if ((state2m=(char *)calloc(bytesL,sizeof(char)))==NULL) outof_memory("state2m");

       
       /*count steps to monitor time*/
       for (btype=1;btype<=node_no;btype++){
	  for (attno=1;attno<=m_att_period[btype];attno++)    
	     total_steps+=1;
       }
       total_steps*=(lineL*value_range-1);

       for (btype=1;btype<=node_no;btype++){
          for (attno=1;attno<=m_att_period[btype];attno++){
             /*copy state*/
             memmove(current_state,m_att[btype][attno],bytesL);
             memmove(state1m,current_state,bytesL); /*copy state*/

             for (bitflip=L;bitflip>=0;bitflip--){ /*flip*/
	       for (value=0;value<=value_range-1;value++){
                      memmove(state1m,current_state,bytesL); /*restore state*/
                if ( get_value(state1m,bitflip)==value ) continue;
                else set_value(state1m,bitflip,value);
                steps_so_far++; 
                if (total_steps>100){              
                   if (steps_so_far%(total_steps/100)==0){
		      sprintf(textb[0],"%d%%",
                            (signed int)((steps_so_far*100)/total_steps));
		      inset_prompt_box(0,5,textb[0],'d');
                   }
		}
                itcount=0;
	        while(1){
		   if (event_ready()){
		      if (is[0]=='q'){
                         if (graph_type=='a'){
			    free(histnodesize);
                            free(m_att_period);
                         }
                         if (graph_type=='f' || graph_type=='a'){
			    free(frag_node_types);
                            free(current_state);
                            free(wnhood);
                            for (z=1;z<=node_no;z++) free(att_check[z]);
                            free(att_check);
                            free(state1m);
	                    free(state2m);
                         }
			 
			 free(m_node_size);//now local-global
			 free(s_node_size);
                         for (z=0;z<=node_no;z++) free(text_label[z]);
			 free(text_label);
			 
			 free(text_node_size);
                         free(basin_color);
			 for (z=1;z<=node_no;z++){
			     free(basinjumps[z]);
			     free(b_j[z]);
			 }    
                         free(basinjumps);
                         free(b_j);
			 
                         # if __UNIX__
                         free_fonts();
                         setup_fonts(start_pointsize);
                         # endif			    
	                 if (graph_type=='f' && exhaustive_testing){
                           //fprintf(stderr,"\nfree exh_pairs_backup -graph return(0)... ");
			   free(exh_pairs_backup);
			   //fprintf(stderr,"freed!");
			 }
			 exh_pairs_in_jump_nodes=0;
			 
			 uncover_free_prompt_box(12); //[12] from get_prompt_box(12,4);
			 //fprintf(stderr,"\nfpb12-l493");
                         return(0);
                      }
                   }                   
                   itcount++;  
                   /*fprintf(stderr," %d",itcount);*/

                   if (exhaustive_testing) 
	               memmove(state2m,exh_pairs_backup+dec_equiv(state1m,L)*bytesL,bytesL);
                   else{
                      for (n=L; n!=Maxu; n--){               
	                 /*local nhood with periodic boundary conditions*/
	                 if (nonlocal==0){
	                    /*i.e. for nhood=9 lineL=3 to work*/
	                    if (L<nhoodm[n]/2){
		               for (i=0;i<=nhoodm[n]-1;i++){
		                  temp=lineL+n-(nhoodm[n]/2)+i;
		                  if (temp<0) temp+=lineL;
		                  wnhood[i]=abs(temp)%lineL;
		               }
	                    }
	                    else{
		               for (i=0;i<=nhoodm[n]-1;i++)
			          wnhood[i]=(lineL+n-(nhoodm[n]/2)+i)%lineL;
	                    }
	                 }    
	                 /*set local 2d wiring*/
	                 else if (loc_twod_fonly){
                            if (twod==2) wire_2d_local(n,wnhood);
                            else if (threed==3) wire_3d_local(n,wnhood); 
                         }
	                 /*nonlocal=1, get psuedo-nhood from wiring scheme*/
	                 else{
	                    for (i=0;i<=nhoodm[n]-1;i++) 
                                      wnhood[i]=wiring[n][i];
	                 }

                         u=0; /*find dec value of actual or pseudo-nhood*/

                         /*xxxxxxxxxxxx next time-step xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
                         if (tot_only==0)
                             u=next_time_step(carule,state1m,state2m,0,NULL,1,wnhood,n,0);
                          else{
			     if (totalistic==1) //run_forward(cacode);
                                u=next_time_step(cacode,state1m,state2m,0,NULL,1,wnhood,n,0); 
                             else if (totalistic==2) //run_forward(v_code);	      
	                        u=next_time_step(v_code,state1m,state2m,0,NULL,1,wnhood,n,0);        
			  }
                         /*xxxxxxxxxxxx end next time-step xxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
                         /*
                         for (i=nhoodm[n]-1;i>=0;i--){
	                    if (value_range==2) u+=get_bit(state1m,wnhood[i])*
                                   (signed int)pow(2,(double)i);
                             else u+=get_value(state1m,wnhood[i])*
                                   (signed int)pow(value_range,(double)i);
	                 }
	                 //set cell next line according to rule look-up table
                         if (!rulemix){
                            if (value_range==2){ 
                                 set_bit(state2m,n,get_bit(carule[0],u));
                            }
                            else set_value(state2m,n,get_value(carule[0],u));
	                 }
                         else{
		            if (value_range==2){
                               set_bit(state2m,n,get_bit(carule[n],u));
                            }
                            else set_value(state2m,n,get_value(carule[n],u));
			 }*/

     
	              }/*for loop*/
                   }
                   /*compare with attractor state*/
                   for (btarget=1;btarget<=node_no;btarget++){
		     if (memcmp(state2m,att_check[btarget],bytesL)==0){
		          basinjumps[btype][btarget]+=1;
                          b_j[btype][btarget]+=1;
                          match_found=1;
                          break;			
                     }
                   }
                   if (graph_type=='a'){
                     /*hist, if no match found in reasonable time*/
		     if (itcount>(max_period+max_trans)*3){
                          basinjumps[btype][0]+=1;
                          b_j[btype][0]+=1;
                          match_found=1;
                          break;			
                     }
                   }
                   if (match_found==1){
                      match_found=0;
                      break;
                   }                                   
                   temppoint=state1m; /*copy F to state1*/
	           state1m=state2m;
	           state2m=temppoint;                 
	        } /*while loop*/	      
               }/*for (value=..*/
             }/*for (bitflip=..*/
          } /*for (attno=..*/ 
       }/*for (btype=..*/
       free(state1m);
       free(state2m);    
       free(current_state);
       free(wnhood);
       for (z=1;z<=node_no;z++) free(att_check[z]);
       free(att_check);
       //if (graph_type=='f' && exhaustive_testing) free(exh_pairs_backup);
    }//if (graph_type=='f' || graph_type=='a'){   
     
    else if (graph_type=='s' || graph_type=='t' || graph_type=='n'){ //'t' is for istr_graph
       unsigned long tot_wire=0;        
        
         if (no_links==0){
	  if ((frag_node_types= //to show specific node types in fragnents
	       (char*)calloc(node_no+1,sizeof(char)))
			       ==NULL) outof_memory("frag_node_types*");
	 if ((netnodesize=	      
		 (unsigned char*)calloc(node_no+1,sizeof(unsigned char)))
				      ==NULL) outof_memory("netnodesize");
     	 if ((m_att_period=
	      (unsigned int*)calloc(node_no+1,sizeof(unsigned int)))
	         ==NULL) outof_memory("m_att_period");
	 
         /*if ((m_att_period=
            (unsigned int*)realloc(m_att_period,
                          (basintypeno+1)*sizeof(unsigned int)))
			  ==NULL) outof_memory("m_att_period");*/
	 
	 if (graph_type=='n'){
	    for (z1=1;z1<=node_no;z1++){
	       for (zz=0;zz<=nhoodm[z1-1]-1;zz++){
		  total_steps+=1;
	       }
	    }
	    total_steps*=lineL;
	 }

	 else if (graph_type=='s' || graph_type=='t') total_steps=node_no;

	 for (zw=1;zw<=node_no;zw++){
	   if (graph_type=='n') tot_wire+=nhoodm[zw-1];
	   if (graph_type=='s' || graph_type=='t') tot_wire+=1;

	   for (z1=1;z1<=node_no;z1++){

	     if (graph_type=='n'){
	      for (zz=0;zz<=nhoodm[z1-1]-1;zz++){
		steps_so_far++;
		if (total_steps>100){
		   if (steps_so_far%(total_steps/100)==0){
		       sprintf(textb[0],"%d%%",
			     (signed int)((steps_so_far*100)/total_steps));
		       inset_prompt_box(0,5,textb[0],'d');
		   }
		} 
		if (event_ready()){ /*chance to give up for very big networks*/
		       if (is[0]=='q'){
			     for (z=1;z<=node_no;z++){
				free(basinjumps[z]);
				free(b_j[z]);
			     }

			     free(basinjumps);
			     free(b_j);
			     free(frag_node_types);
			     free(netnodesize);
			     free(m_node_size);//now local-global
			     free(s_node_size);
			     for (z=0;z<=node_no;z++) free(text_label[z]);
			     free(text_label);
			     free(text_node_size);
                             # if __UNIX__ 
                                free_fonts(); 
                                setup_fonts(start_pointsize);
                             #endif
			     uncover_free_prompt_box(12); //[12] from get_prompt_box(12,4);
			     //fprintf(stderr,"\nfpb12-l672");
			     return(0);
		       }
		}
		
		if (wiring[z1-1][zz]==zw-1){
		   basinjumps[zw][z1]+=1;
		   b_j[zw][z1]+=1;
		}
	      }
	     } //if (graph_type=='n'){
	     
	     /*********************************/
	     if (graph_type=='s' || graph_type=='t'){ //'t' is for istr_graph
		if (node_no>100){
		   if (zw%(node_no/100)==0 && z1==1){
		       sprintf(textb[0],"%d%%",
			     (signed int)((zw*100)/node_no));
		       inset_prompt_box(0,5,textb[0],'d');
		   }
		} 
		if (event_ready()){ /*chance to give up for very big networks*/
		       if (is[0]=='q'){
			     /*if graph_type='s' basin_pos freed in runxx.c*/
			     
                             for (z=0;z<=node_no;z++) free(basin_pos_backup[z]);
			     free(basin_pos_backup);
                             for (z=1;z<=node_no;z++){
				free(basinjumps[z]);
				free(b_j[z]);
			     }
			     free(basinjumps);
			     free(b_j);
			     free(frag_node_types);
			     free(netnodesize);
			     free(m_node_size);//now local-global
			     free(s_node_size);
			     for (z=0;z<=node_no;z++) free(text_label[z]);
			     free(text_label);
			     free(text_node_size);
			     # if __UNIX__
                                free_fonts();
                                setup_fonts(start_pointsize);
                             #  endif
			     uncover_free_prompt_box(12); //[12] from get_prompt_box(12,4);
			     //fprintf(stderr,"\nfpb12-l717");
			     return(0);
		       }
		} 
		if (graph_type=='s'){
		  memmove(state2,exh_pairs+(zw-1)*bytesL,bytesL);
		  if (z1-1 == dec_equiv(state2,L)){
		     basinjumps[zw][z1]+=1;
		     b_j[zw][z1]+=1;
		     //fprintf(stderr,"%d>%lu ",zw-1,dec_equiv(state2,L));//show exhaustive list
		     netnodesize[z1]+=1;//inputs for each node from basin of attraction field
		     //fprintf(stderr,"%d ",netnodesize[z1]);
		  }
		}
		
		//else if (graph_type=='t') memmove(state2,pat_state1[zw-1],bytesL); //check this
		else if (graph_type=='t'){ //for istr_graph
		  
		  // memmove(state2,pat_state1[zw-1],bytesL); //check this
		  if (z1-1 == index_successor[zw-1]){
		      //if (zw-1==0) fprintf(stderr,"\n");
		      //fprintf(stderr,"\ngraph>%d:%d",z1-1,index_successor[zw-1]);
		      //if (dec_equiv(pat_state0[zw-1],bytesL)  == dec_equiv(state2,L)){
		      basinjumps[zw][z1]+=1;
		      b_j[zw][z1]+=1;
		      //fprintf(stderr,"\nb_j[%d][%d]=%d",zw-1,z1-1,b_j[zw][z1]);
		      //fprintf(stderr,"\nindex>next %d>%d ",zw-1,index_successor[z1-1]);//show exhaustive list
		      netnodesize[z1]+=1;
		      //fprintf(stderr,"nodesize=%d ",netnodesize[z1]);
		   }
		 }		 
	     }//if (graph_type=='s' || graph_type=='t'){
	     /*********************************/
	   }//for (z1=1;z1<=node_no;z1++){	   
	 }//for (zw=1;zw<=node_no;zw++){
	 
	 if (graph_type=='t'){ //check node and its successor
	   unsigned int nc;
	    if (direction=='b'){//for upstreem_only subtree, so origin has no output
	       basinjumps[1][1]=0;
	       b_j[1][1]=0;
	       netnodesize[1]-=1;
	    }
	    
	    if (dontcopytrees){ //check if output exists, for suppressed equivalents in att cycles
	      //fprintf(stderr,"\noutput existance check");
	       for (nc=0;nc<=istr_node_count-1;nc++){
	          for (z=0;z<=istr_node_count-1;z++){
		     //fprintf(stderr,"\n[%d][%d]",nc,z);
	             if (index_successor[nc]==-1){
	                basinjumps[nc+1][z+1]=0;
	                b_j[nc+1][z+1]=0;
	                netnodesize[nc+1]-=1;
		        //fprintf(stderr,"\n%d:%d, is=%d",nc+1,z+1,index_successor[nc]);
		        break;
                     }
	           }  
	        }
	        //fprintf(stderr,"\noutput existance check complete");
	    }
	 }

         /*if (graph_type=='t'){
	   unsigned int z; //note: for trees not copied, netnodesize[]=255 (unsigned char)
	    //check netnodesize[z];
	    for (z=0;z<=istr_node_count-1;z++){
               fprintf(stderr,"\n%d->%d",z, netnodesize[z]);
	    }
	 }*/
	 
         //fprintf(stderr,"\nnetnodesize:");
	 for (zw=1;zw<=node_no;zw++){  
	    if (graph_type=='n') netnodesize[zw]=nhoodm[zw-1]; //inputs for each node from wiring,
	                                                   //for graph_type=='s' -- different -- done above
	   
	    text_node_size[zw]=label_pointsize; //initial text sizes for any graph_type	    
	    m_att_period[zw]=celloutfreq[zw-1];
	 }
	}//if (no_links==0){
	 
	else if (no_links==1 && graph_type=='n'){
	   if ((netnodesize=	      
		 (unsigned char*)calloc(node_no+1,sizeof(unsigned char)))
				      ==NULL) outof_memory("netnodesize");
	   for (zw=1;zw<=node_no;zw++) netnodesize[zw]=nhoodm[zw-1];
	   if ((frag_node_types= //to show specific node types in fragnents
	       (char*)calloc(node_no+1,sizeof(char)))
			       ==NULL) outof_memory("frag_node_types*");
	}      
	
	/*m_att_period .. celloutfreq*/
	/*m_lineL .. 1*/
	if (jump_layout_only==1){ 
	   m_size=lineL*(value_range-1); 
	   m_space=pow(value_range,(double)lineL);         
	}
	else if (no_links==1){
	   m_size=lineL*(value_range-1); 
	   m_space=pow(value_range,(double)lineL); //for no_links m_space is a nominal value to fix bug        
	}
	else{ 
	   m_size=1;
	   m_space=(double)tot_wire;
	}
	
    }//end: else if (graph_type=='s' || graph_type=='t' || graph_type=='n'){
    
    { /*start: draw jump-graph*/   
	    double w_angle;
	    //float rot_angle,node_factor,link_factor;
	    //float c_scale; //now a locally-global variable
	    //double this_f,av_f; //nowlocal in void reset_nodesize(void)
	    //float *m_node_size; //now locally-global variable
	    signed int X1,Y1,X2,Y2,wox,woy,promptx,prompty;
	    char tog_window=0;
	    char tog_rank=0;
	    unsigned int *reorder_graph;
	    signed int **temp_basin_pos;
	    char show_numbers_nolinks=0; //for nolinks either discks or numbers

	    /*keep track of rank order*/
	    if ((reorder_graph=(unsigned int*)
		       calloc(node_no+1,sizeof(unsigned int)))
					 ==NULL) outof_memory("reorder_graph");
	    /*keep track of previous positions*/
	    if ((temp_basin_pos=(signed int**)calloc(node_no+1,
		      sizeof(signed int*)))==NULL) outof_memory("temp_basin_pos");
		  for (zw=0;zw<=node_no;zw++)
		     if ((temp_basin_pos[zw]=(signed int *)
			  calloc(2,sizeof(signed int)))
			       ==NULL) outof_memory("basin_pos[]");

	    /*create array of basin positions
		       [node_no][0]=x, [node_no][1]=y*/

	    //if (exhaustive_testing==0 && graph_type!='s'){
	    if (graph_type!='s' && graph_type!='t'){
	      /*calloc and free basin_pos now done in main for both istr and ibaf graphs 19/06/25
	       if ((basin_pos=(signed int**)calloc(node_no+1,
		   sizeof(signed int*)))==NULL) outof_memory("basin_pos");
	       for (zw=0;zw<=node_no;zw++){
	          if ((basin_pos[zw]=(signed int *)calloc(
			2,sizeof(signed int)))
			       ==NULL) outof_memory("basin_pos[]");
	       }*/
	    }
	    
	    if ((outside_inputs=(unsigned int *)calloc(node_no+1,
		 sizeof(unsigned int)))==NULL) outof_memory("outside_inputs");

	    /*default 2d hex or square -- then 2d-2 toggles between hex/square*/
	    if (graph_type=='n' && twod && nhood_mixed==0 &&
		    (nhood==6 || nhood==7 || nhood==10 || nhood==15 ||
		     nhood==18 || nhood==19 || nhood==22) 
			   && i2d%2==0 && j2d%2==0){
		    graph_hex2d=1;
	    }
	    else graph_hex2d=0;

	    w_cyclerad=100+node_no/4;
	    if (w_cyclerad>=133) w_cyclerad=133;
	    w_cyclerad=vgax(w_cyclerad);

	    /*whole box*/
	    X1=vgax(5);
	    X2=Maxx-vgax(5);
	    Y1=CHeight*5; /*higher box for networks or att hist jump graph
			    otherwise leave space for b-of-a field*/
	    //if (graph_type=='f' || jump_layout_only) Y1+=(CHeight*7); //keep all boxes same
	    Y2=vgay(430);
	    //if (graph_type=='a') Y2-=(CHeight*7); /*to keep att hist visible -- but keep boxes same for simplicity*/

	    draw_box(22,X1,Y1,X2,Y2,1,0);

	    wox=Maxx/2;
	    woy=Y1+(Y2-Y1)/2;
	    /*woy=bottom-w_cyclerad-vgax(10);*/

	    w_angle=2*PI/node_no;
	    if (graph_type=='f' || jump_layout_only){
	        scale_m_nodes=1;
                scale_links=1;
            }		
	    if (graph_type=='s' || graph_type=='t' || no_links==1){
		scale_m_nodes=1; //initially for basins of attraction
		scale_links=1;
	    }
	    else{
	        scale_m_nodes=1;
                scale_links=1;
	    }
            if (jump_layout_only) scale_m_nodes=1; /*scale nodes for layout-graph*/
	    
	    show_arrows=1;
	    rot_angle=2*PI/24; /*default rotation angle=15 degrees*/
	    node_factor=1.1; /*to expand/contract nodes*/
	    link_factor=1.1; /*to expand/contract links, and arrows*/
	    if (graph_type=='s' || graph_type=='t') arrow_size=0.03;/*for stg start with smaller arrows*/
	    else  arrow_size=0.07;
	    /*note total inputs from outside, 
	      to check unreachable basins*/
	    if (no_links==0){
	       for (zw=1;zw<=node_no;zw++){
		  for (btarget=1;btarget<=node_no;btarget++){
		     if (btarget!=zw) 
		     outside_inputs[zw]+=basinjumps[btarget][zw];
		  }
	       }
	    }
	    	    
            /*set scale node sizes m_node_size[zw]*/
	    c_scale=PI*w_cyclerad/(node_no*1.2);
	    if (c_scale>w_cyclerad/5) c_scale=w_cyclerad/5;
	    if (node_no>100)
		     c_scale*=(node_factor*(pow(node_no,0.5)/pow(100,0.5)));
	    if (c_scale<vgax(1)) c_scale=vgax(1);

	    if (graph_type=='s' || graph_type=='t'){
	       if (c_scale>vgax(3)) c_scale=vgax(3); //limit initial size of 2d,3d patterns
	    }
	    reset_nodesize();
	    
            start_c_scale=c_scale; //expand self_links for disks only, not for numbers etc.
	    if (no_links==1) oned=1;
	    
	    // draw default graph and reset node scale, c_scale           
            if (graph_type=='s' || graph_type=='t') //draw stp according to basin_pos saved in drawbxx.c
	        c_scale=draw_predefined_stp(X1,Y1,X2,Y2,wox,woy);
	    else if (oned==1) c_scale=draw_circle_graph(
		    X1,Y1,X2,Y2,wox,woy,w_angle);
	    else if (twod==2) c_scale=draw_2d_graph(
		    X1,Y1,X2,Y2,wox,woy);
	    else if (threed==3) c_scale=draw_3d_graph(
		    X1,Y1,X2,Y2,wox,woy);
	    else{
	       c_scale=PI*w_cyclerad/(node_no*1.2);
	       if (c_scale>w_cyclerad/5) c_scale=w_cyclerad/5;
	       if (node_no>100)
		     c_scale*=(node_factor*(pow(node_no,0.5)/pow(100,0.5)));
	       if (c_scale<vgax(1)) c_scale=vgax(1);
	    }
	    
	   startprompt:
	    //fprintf(stderr,"\nstartprompt: is[0]=%c",is[0]);
	    graph_postscript=0;/*to save the network or jump_graph as a vector postscript*/ 
	    /*save area under prompt box in buf 3, 4 lines*/
	    setcolor(white);
	                
            this_text_size=current_text_size;
	    //fprintf(stderr,"\ncts=%d start=%d",current_text_size,start_pointsize);
          # if __UNIX__ 
            free_fonts();
            setup_fonts(start_pointsize);//to preserve normal prompt font
          # endif 
	    	    
	    xbox=draw_prompt_box(4);
	    
	    //--------initial prompts: title in red
	    setcolor(lightred);
	    if  (graph_type=='n'){
	         if (jump_layout_only==1) outtext("JUMP-graph(nolinks): ");
	         else if (no_links==0) outtext("NET-graph: ");		 
		 else outtext("NET-graph(nolinks): ");
	    }	 
	    else if (graph_type=='s') outtext("IBAF-graph: ");
	    else if (graph_type=='t') outtext("ISTR-graph: ");
	    else if (graph_type=='f'){
		if (jump_layout_only) outtext("JUMP-graph(nolinks): ");
		else outtext("JUMP-graph: ");
	    }
	    else if (graph_type=='a') outtext("JUMP-graph(hist): ");
		     		     
	    //--------initial prompts: first line
	    setcolor(white);
	    
	    if (graph_type=='n' && jump_layout_only){ //the jump-graph-with no edges is treated as a network-graph
	          sprintf(textb[0],  //rank%d-k is relevant rank is based on because basin
			  "drag-(def) PScript-P win-w rank%d-k",tog_rank);
	    }
	    else if (graph_type=='n'){	      
	        if (no_links==1) sprintf(textb[0],"drag-(def) PScript-P win-w"); //rank%d-k",tog_rank is irrelevant if nolinks
	        else if (no_links==0) sprintf(textb[0],"drag-(def) PScript-P net-# ant-a unscram-u win-w rank%d-k",tog_rank);
                else sprintf(textb[0],"drag-(def) PScript-P win-w"); //net-# is irrelevant
            }				       
	    else if (graph_type=='f' || graph_type=='s' || graph_type=='t' || graph_type=='a')
	                sprintf(textb[0],"drag-(def) PScript-P net-# ant-a unscram-u win-w rank%d-k",tog_rank);
	    outtext(textb[0]);
	    	    
	    //--------initial prompts: 2nd line
	    moveto(xbox,gety+CHeight);
	    if (graph_type=='n'){
	        if (jump_layout_only) outtext("settings-S rot-x/X flip-h/v nodes-(/) links-{/} both-[/]");//discs only
                else if (no_links==0) outtext("settings-S rot-x/X flip-h/v nodes-(/)/= links-{/} both-[/]");
		else outtext(                 "settings-S rot-x/X flip-h/v nodes-(/)/= links-{/} both-[/]");//discs only
	    }
	    else if (graph_type=='s' || graph_type=='t') // E removed -- so prompts are the same
	         outtext("settings-S rot-x/X flip-h/v nodes-(/)/= links-{/} both-[/]");//=discs,numbers,(patterns),none
	    else if (graph_type=='f' || graph_type=='a') //discs only
	         outtext("settings-S rot-x/X flip-h/v nodes-(/)/= links-{/} both-[/]");

	    //--------initial prompts: 3nd line
	    moveto(xbox,gety+CHeight);
            if (graph_type=='n' && jump_layout_only) outtext("basins-i/I/s nodes-n/N Labels-+");
	    else if (graph_type=='n' && no_links==1) outtext("nodes-N Labels-+");
	    
	    else if (graph_type=='s' || graph_type=='t')
	                  outtext("Unreach-U table-t/T nodes-n/N links-l Labels-+ arrows-A/</>");
	    
            else if (graph_type=='f'){
	       if (jump_layout_only==0) outtext("basins-i/I/s Unreach-U table-t/T nodes-n/N links-l Labels-+ arrows-A/</>");
	       else outtext("basins-i/I/s nodes-n/N Labels-+");
            }
            else if (graph_type=='a') outtext(
	       "Unreach-U table-t/T nodes-n/N links-l Labels-+ arrows-A/</>");//no basins inside
	    else if (graph_type=='n'){
	      if (network_outputs==0) outtext(             
		  "Unreach-U matrix-t/T nodes-n/N links-l Labels-+ arrows-A/</> in/out-z");//z toggles scaled inputs or outputs
		else outtext(            
		  "Unreach-U matrix-t/T nodes-n/N links-l Labels-+ arrows-A/</> out-in-z");//z toggles scaled inputs or outputs	                     
            }	      

            //--------initial prompts: 4th line
	    moveto(xbox,gety+CHeight);
            if (graph_type=='s' || graph_type=='t') outtext(
	       "layout: file-f graph-g circle/spiral-o/O 1d/2d(tog)/3d-1/2/3 rnd-r/R quit-q:");//graph-g restore start layout
            else outtext(
               "layout: file-f circle/spiral-o/O 1d/2d(tog)/3d-1/2/3 rnd-r/R quit-q:");


	    promptx=getx;
	    prompty=gety;
	    
            
	    current_text_size=this_text_size;
            # if __UNIX__
                  free_fonts();
                  setup_fonts(current_text_size);
            # endif
	   
	    
	  startbox:
	    //fprintf(stderr,"\nstartbox: is[0]=%c",is[0]);
	    use_preset_basin_pos=0;
	    just_component=0;
	    just_fragment=0;
	    moveto(promptx,prompty);
 #          if __UNIX__
	       /*while(event_ready()==0);*/ /*255 to suppress flashing cursor*/
	       flashing_cursor(0,0,0,0,0,-1,CWidth,1+CHeight/2,255);
 #          elif __WATCOM__
	       if (mouse_found) mouse_call(1,0,0,0); /*display mouse*/
	       flashing_cursor(0,CHeight-vgay(3),CWidth,CHeight,green);
 #          endif
	    if (button=='l' || button=='r') is[0]=13;
	    else{
		char test=0;
		 test=keycheck(0);
		 is[0]=test;
		 //fprintf(stderr,"\n %c %d",is[0],is[0]);
	    }

	    /* jump-graph, layout-graph and network graph: on-the-fly options
	       gGjJKLmMPqQRsTVWyYzZ - unused 
            + Labels -- tog to show  
            # net-# to restore to original network, if multiple links cut or added
            = if (f__or_n=='s') 6-way node-toggle, otherwise 3-way toggle, id nolinks 2-way
	    > expand arrows
	    < contract arrows
	    1 1d layout
	    -----------
	    2 2d layout
	    2x override 2d hex layout
	    2s override 2d square layout
	    -----------
	    3 3d layout
	   13 (return or left-click) drag
	    a launch probabilistic ant in jumpgraph
	    A toggle arrows on links
	    [ contract both links and nodes (was b)
	    ] expand both links and nodes (was B)
	    ( contract nodes (was c)
            ) expand nodes (was e)
	    { contract links (was C)
            } expand links (was E)
	    d redraw current graph	   
      	    f save/load the graph layout
	    h flip accos horizontal axis
	    i redraw the field with basins at node positions - without nodes
	    I redraw the field with basins at node positions - inside nodes
	    k rank and reposition in descending order or links or basin volume
	    l toggle links: same thin or scaled
	    n toggle nodes: same or scaled according to basin volume or k for networks
	    N toggle node numbers in nodes
	    o circle layout
	    O spiral layout
  removed - p hortest path (or small world distance)
	    P vector postScipt of graph
	    r randomize the existing layout by a small amount
	    R random layout
	    S various settings
            s if (graph_type=='f'|| jump_layout_only==1) settings for basins inside, i.e rescale
	    t show table - numbers, for ibaf list exh-pairs
	    T show table - fractions, not for ibaf
	    u unscramble graph automatically
	    U suppress links from unreachable nodes/basins
	    v flip accoss vertical axis
	    w redraw current graph
	    x rotate clockwise
	    X rotate anti-clockwise
            z toggle scaled network nodes between k and outputs
	    */

	    /*any key to restore jump-graph or ibaf-graph after
	      showing original basins beneath*/
	    if (tog_window==1){
	          draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
		  tog_window=0;
		  goto startprompt;
	    }
	    is[1]=0;	    
            fragment=0;
	     
	    switch(is[0]){
	     case 13: /*change to dragging nodes etc*/
	       //?? sprintf(textb[9],"%s","boximage_prompt[3]");
	       //?? putimage(trboxw,2,boximage_prompt[3],COPY_PUT,textb[9]);
		 
                 in_manipulate=1;		 
		 manipulate_jump_graph(wox,woy,X1,Y1,X2,Y2,rot_angle);
		 in_manipulate=0;
		 draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);//redraw fragment=0 graph
		 is[0]=0;
		 goto startprompt;
		 
	    case '#':{//in case links were cut or added --- restore original
	        unsigned int zu;
		 suppress_u_links=0; //incase linke were suppressed
	         for (zu=node_no;zu>=1;zu--) memmove(basinjumps[zu],b_j[zu],
                                                (node_no+1)*sizeof(unsigned int));
		 draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	         goto startprompt; 
	     }
	       
	     case 'P':{ /*save the graph as a vector postScript file*/ 
		 this_text_size=current_text_size;
	            //fprintf(stderr,"current_text_size=%d",current_text_size);
                 # if __UNIX__
                       free_fonts();
                       setup_fonts(start_pointsize);//to preserve normal prompt font
                 # endif 
		 
		 erase_prompt_box(4);		  
		 draw_prompt_box(1);
		 outtext("initial: PostScript: greyscale-P color-p:");
		 input_string(1,0);
		 
                 current_text_size=this_text_size;
                 # if __UNIX__
                       free_fonts();
                       setup_fonts(current_text_size);
                 # endif
		 
		 if (is[0]=='p'|| is[0]=='P'){
		   save_graph_PScript(1,X1,Y1,X2,Y2,wox,woy);		   
		 }
		 goto startprompt;
	     }
 
	     case 'f':{ /*save/load the graph layout*/
		 char ok,save_load;

		 this_text_size=current_text_size;
                  # if __UNIX__
                          free_fonts();
                          setup_fonts(start_pointsize);//to preserve normal prompt font
                  # endif
			  
		  erase_prompt_box(4);
		  draw_prompt_box(1); 
		  outtext("graph layout file: save-s load-l:");
		  input_string(1,0);
		  if (is[0]=='s' || is[0]=='l'){
		    save_load=is[0];
		    ok=save_load_graph_layout(is[0]);		
		    if (save_load=='l' && ok==1){
		       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
		    }
		    is[0]=0;
		  }
		  tog_rank=0;
		  current_text_size=this_text_size;
                  # if __UNIX__
                          free_fonts();
                          setup_fonts(current_text_size);
                  # endif
		  goto startprompt;
	     }
	     case 'z': //toggle scaled network nodes between k and outputs, network-graph only
	       if (jump_layout_only==1)  break;
	       if (graph_type!='n' || no_links==1) break;
	       //if (scale_m_nodes==0 ||  scale_links==0) break; if no scaling: both switched on	       
	       scale_m_nodes=1;
	       scale_links=1;
	       
	          network_outputs=abs(network_outputs-1);


		  this_text_size=current_text_size;
                  # if __UNIX__
                          free_fonts();
                          setup_fonts(start_pointsize);//to preserve normal prompt font
                  # endif
			  
		  reset_nodesize();
		    
		  draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
		  
		  current_text_size=this_text_size;
                  # if __UNIX__
                          free_fonts();
                          setup_fonts(current_text_size);
                  # endif

		  goto startprompt; //redo the prompt
		  
		  //tog_rank=0; ??
	          break;
		  		  
	     case 'w': /*tog window to see basins*/
	       /*if tog_window==1 any key will restore - see above switch(is[0])*/
	       if (tog_window==0){ 
		  sprintf(textb[9],"%s","boximage[22]");
		  putimage(X1,Y1,boximage[22],COPY_PUT,textb[9]);/*below the jump-box*/
		  //shows image below graphs:network/ibaf/attractor histogram/jump
		  
		  if (graph_type=='f' || still_jump_graph==1 || graph_type=='s' || graph_type=='t'){
		        putimage(trboxw,2,boximage_prompt[12],COPY_PUT,textb[9]);
		        //the field info box, for graps:istr, ibaf and jump
			//otherwise the previous top-right box
		  }
		  inset_prompt_box(0,26,"restore graph -any key:",'d');
		  tog_window=1;
	       }              
	       break;
	       
	     case 'a': /*launch probabilistic ant in jumpgraph*/
	       if (jump_layout_only==1)  break;
	       if (no_links==1) break; // goto startprompt;              
	       erase_prompt_box(4);
	       //draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);

	       
               //note: text in nodes will revert to start, and start will overite lone text
               this_text_size=current_text_size;
               # if __UNIX__
                       free_fonts();
                       setup_fonts(start_pointsize);
               # endif
	       
	       prob_ant(wox,woy,X1,Y1,X2,Y2);

               current_text_size=this_text_size;
               # if __UNIX__
                       free_fonts();
                       setup_fonts(current_text_size);
               # endif
		       
	       is[0]=0;
	       // break; //goto startprompt;
               goto startprompt;
	       
	     /*case 'p': 
	       erase_prompt_box(4);               
	       xbox=draw_prompt_box(2);
	       outtext(
	"intest path or small world distance, between all pairs of nodes");
	       moveto(xbox,gety+CHeight);
	       outtext("directed intest path -p, non-directed distance-d:");
	       input_string(1,0);
	       if (is[0]=='p') intest_path('p');
	       else if (is[0]=='d') intest_path('d');
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       goto startprompt;*/

	     case 't': case 'T':  /*show table - numbers - fractions*/
	       if (jump_layout_only==1)  break;

	       if ((graph_type=='s' || graph_type=='t') && is[0]=='T'){//show the adjacency list in terminal
                 //print_exh_pairs(b_j);
		 
		 unsigned int zu,zz;
                 unsigned int poss;
		 
		 if (graph_type=='t'){ //was set up earlier, see: "set up index_successor"
		   unsigned int nc;
		   for (nc=0;nc<=istr_node_count-1;nc++){ //print list (d>ds) s>ss
		      fprintf(stderr,"\n(%d>%d)",nc,index_successor[nc]);//????
		      fprintf(stderr," %lu>%lu",dec_equiv(pat_state0[nc],L),
			                   dec_equiv(pat_state0[index_successor[nc]],L));
		    }
		 }  
		 else{
		   unsigned int zu,zz;
                   unsigned int poss;
                    for (zu=1;zu<=node_no;zu++){
		      fprintf(stderr,"\n%d ",zu-1);
		      dec_to_value_line(state1,zu-1,lineL);
                      for (poss=L;poss!=Maxu;poss--) fprintf(stderr,"%d",get_value(state1, poss));
		      fprintf(stderr," ");
		      for (zz=1;zz<=node_no;zz++){
			 if (b_j[zu][zz]==1){
                            dec_to_value_line(state1,zz-1,lineL);
                            for (poss=L;poss!=Maxu;poss--) fprintf(stderr,"%d",get_value(state1, poss));
			    fprintf(stderr," %d",zz-1); //amended network, if links cut,added etc
			 }   
		      }	 
		    }
		  }
	       }
	       else{	       
                  //fonts dealt with in show_table()	       	           
	          erase_prompt_box(4);	       
	          show_table(is[0],X1,Y1,X2,Y2);

	          current_text_size=this_text_size;
                  # if __UNIX__
                       free_fonts();
                       setup_fonts( current_text_size);
                  # endif	   	       
		       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	          is[0]=0;
	       }
	       goto startprompt;
	       
	     case 'U': /*suppress links from unreachable basins*/
	          if (jump_layout_only==1)  break;
	          if ((graph_type=='n' && no_links==1) ||
		      (graph_type=='f' && jump_layout_only)) break; //goto startprompt;
		  
		  restore_def_font();
		  erase_prompt_box(4);               
		  xbox=draw_prompt_box(3);
		  suppress_u_links=0;
		  u_threshold=0;
		  if (graph_type=='n') u_threshold=1; //because network-graph nodes have at lease 1 input
		  outtext("unreachable nodes: xterm-x suppress-u restore-(ret):");
		  input_string(1,0);
		  if (is[0]=='u') suppress_u_links=1;
		  if (is[0]=='x'){
		      suppress_u_links=1;
		      for (zw=1;zw<=node_no;zw++){
		         //show a list of inputs to each node in terminal
		         if (graph_type=='f' || graph_type=='a') fprintf(stderr,"\n%d:%d",zw,outside_inputs[zw]);
		         else fprintf(stderr,"\n%d:%d",zw-1,outside_inputs[zw]);
	              }
		      suppress_u_links=0;
		      goto skipU;
		  }
		  if (suppress_u_links==1){ /*unreachable nodes*/
		     isolate_unreachable=0;
		     moveto(xbox,gety+CHeight);
		     outtext("isolate unreachable -i:");
		     input_string(1,0);
		     if (is[0]=='i') isolate_unreachable=1;
		     moveto(xbox,gety+CHeight);
		     sprintf(textb[0],
		       "change unreachable threshold (now %d):",u_threshold);
		     outtext(textb[0]);
		     input_string(3,0);
		     if (is[0]!=13 && atoi(is)>=0) u_threshold=atoi(is);

		     if (isolate_unreachable==1){
			for (zw=node_no;zw>=1;zw--){
			   if (outside_inputs[zw]<=u_threshold){
			      /*position at random on left 1/5 window*/
			      basin_pos[zw][0]=rand()%((X2-X1-vgax(60))/5) 
							     + X1+vgax(30);
			   }
			}
		     }
		  }
		  draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
		 skipU: 
		  goto startprompt;
		  
	     case 'n': /*toggle nodes: same or scaled according to basin volume, 
					    or k for networks*/
	       if (graph_type=='n' && no_links==1 && jump_layout_only==0) break;  //goto startprompt;
	       
	       scale_m_nodes=abs(scale_m_nodes-1);
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       break;

   	     case 'N': /* toggle node numbers in nodes */
	       //node_numbers=abs(node_numbers-1);
	       if (node_numbers==0) node_numbers=1; //3-way toggle, 
	       else if  (node_numbers==1) node_numbers=2;
	       else if  (node_numbers==2) node_numbers=0;
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       break;
	     case 'l': /*toggle links: same thin or scaled according to fraction outputs and
				   node size (basin volume, or k for networks)*/
	       if (jump_layout_only==1)  break;
	       if (no_links==1) break; //goto startprompt;
	       scale_links=abs(scale_links-1); 
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       break;
	       
	     case '+':{
	        show_labels=abs(show_labels-1); //tog showing labels
		draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	        break;
	     }
	       
	     case 'A': /*toggle arrows on links*/
	       if (jump_layout_only==1) break;
	       if (no_links==1)  goto startprompt;              
	       show_arrows=abs(show_arrows-1);
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       break;
	     case '<': case '>': /*expand/contract arrows*/
	       if (jump_layout_only==1) break;
	       if (no_links==1 || show_arrows==0) break; // goto startprompt;
	       if (is[0]=='>') arrow_size*=1.1;	       
	       else if (is[0]=='<') arrow_size*=0.9;
	       //if (arrow_size<.03) arrow_size=.03;
	       if (arrow_size<.01) arrow_size=.01; //
	       if (arrow_size>1.0) arrow_size=1.0;
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       break;
             case 'g': /*original graph layout layout*/
                  /*copy basin positions from backup to re-enter*/
	       if (graph_type=='s' || graph_type=='t'){
                  for (zw=0;zw<=node_no;zw++){
	              basin_pos[zw][0]=basin_pos_backup[zw][0];
                      basin_pos[zw][1]=basin_pos_backup[zw][1];
	          }
                  c_scale=draw_predefined_stp(X1,Y1,X2,Y2,wox,woy);
		     //draw stp according to basin_pos saved in drawbxx.c
               }
               break;
	     case 'o': /*circle layout*/
	       c_scale=draw_circle_graph(X1,Y1,X2,Y2,wox,woy,w_angle);
	       tog_rank=0;
	       break;
	     case 'O':{ /*spiral: set and remember initial basin positions*/
	       float start_spiral, start_angle,s_s,s_a;
	       signed int bcount=0;

	       /*adjust size, angle and nodes for spiral*/
	       start_spiral=40 * (pow(100,0.3)/pow(node_no,0.3));
	       s_s=vgax(start_spiral);
	       start_angle=2*PI/(node_no/10);            
	       s_a=start_angle;
	       
	       for (zw=node_no;zw>=1;zw--){
		  
		  bcount++;	     
		  basin_pos[zw][0]=(cos(-(s_a*zw))*s_s)+wox;
		  basin_pos[zw][1]=-(sin(-(s_a*zw))*s_s)+woy;
		  s_s*=(1+0.2/pow(bcount,0.9));
		  s_a/=(1+0.01/pow(bcount,0.7));
	       }
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       tog_rank=0;
	       break;           
	     } 
	     case 'k':{	          
	          //if (graph_type=='s'  || graph_type=='t') break;//otherwize would confuse basins
		  /*rank and reposition in descending order or links or basin volume*/
		  //if (jump_layout_only==1 || graph_type=='f' || graph_type=='a'); //for jump-graph allow rank-k even if no_links
		  //else if (no_links==1 && jump_layout_only==0)  break; //goto startprompt;

	          //if  (scale_m_nodes==0) break;
	          if (graph_type=='n' && no_links==1 && still_jump_graph==0) break;
	          scale_m_nodes=1;//make sure scaled nodes are on
		  
		  //fprintf(stderr,"\ntog_rank=%d",tog_rank);
		  if (tog_rank==1){ /*tog to previous*/
		     for (zw=0;zw<=node_no;zw++)           
		       memmove(basin_pos[zw],
			   temp_basin_pos[reorder_graph[zw]],2*sizeof(signed int));
		  }
		  
		  else if (tog_rank==0){ /*tog to rank order*/
		     for (zw=1;zw<=node_no;zw++) reorder_graph[zw]=zw;
		     reorder_rank(reorder_graph);

		     for (zw=node_no;zw>=1;zw--){     
			temp_basin_pos[reorder_graph[zw]][0]=basin_pos[zw][0];
			temp_basin_pos[reorder_graph[zw]][1]=basin_pos[zw][1];
		     }    
		     for (zw=1;zw<=node_no;zw++)           
			    memmove(basin_pos[zw],temp_basin_pos[zw],2*sizeof(signed int));
		  }
		  draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
		  tog_rank=abs(tog_rank-1);
		  goto startprompt; //redo the prompt
		  break;
	    }

	    case 'u': /*unscramble graph automatically*/
	       if (no_links==1) break;; //there must be links because algorithm counts links
	       scale_m_nodes=1;//make sure scaled nodes are on
		  
	       unscramble_graph(X1,Y1,X2,Y2,wox,woy);
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       is[0]=0;
	       break;
	    case 'x': case 'X': /*rotate clockwise anti-clockwise*/
	        fragment=0;
	       rotate_component_graph(is[0],rot_angle,wox,woy);	     
	       draw_box(-1,X1,Y1,X2,Y2,1,0);//clear box
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       break;
	    case 'v': case 'h':{ /*flip accoss vertical or horizontal axis*/
	       fragment=0;
	       flip_component_graph(is[0],wox,woy);
	       draw_box(-1,X1,Y1,X2,Y2,1,0);//clear box
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       break;
	    }
	    case 'S':{ /*various settings*/
	      signed int this_angle;

               this_text_size=current_text_size;
	            //fprintf(stderr,"current_text_size=%d",current_text_size);
               # if __UNIX__
                       free_fonts();
                       setup_fonts(start_pointsize);//to preserve normal prompt font
               # endif 
	      
	       xbox=draw_prompt_box(4);
	       sprintf(textb[0],
	       "settings: rotation angle (start=15), now %.2f degrees:", 
						  (rot_angle*57.2958));
	       outtext(textb[0]);
	       input_string(4,1);
	       if (is[0]!=13){
		  this_angle=atoi(is);
		  rot_angle=2*PI*(float)this_angle/360;
	       } 
	       moveto(xbox,gety+CHeight);
	       sprintf(textb[0],
		  "expand/contract nodes: factor (1.0 to 2.0, start=1.2), now %.2f:", 
								  node_factor);
	       outtext(textb[0]);
	       input_string(4,1);
	       if (is[0]!=13 && atof(is)<1 && atof(is)<=2) node_factor=atof(is);
	       moveto(xbox,gety+CHeight);
	       sprintf(textb[0],
		  "expand/contract links: factor (1.0 to 2.0, start=1.1), now %.2f:", 
								  link_factor);
	       outtext(textb[0]);
	       input_string(4,1);
	       if (is[0]!=13 && atof(is)<1 && atof(is)<=2) node_factor=atof(is);
	       moveto(xbox,gety+CHeight);
	       sprintf(textb[0],
		    //"change arrow size: (.03 to 1.0 start=0.07), now %.2f:",arrow_size);
		    "change arrow size: (.01 to 1.0 start=0.07), now %.2f:",arrow_size);   
	       outtext(textb[0]);
	       input_string(4,1);
	       if (is[0]!=13 && atof(is)>=.03 && atof(is)<=1.0) arrow_size=atof(is); 
	       is[0]=0;

	       current_text_size=this_text_size;
               # if __UNIX__
                       free_fonts();
                       setup_fonts(current_text_size);
               # endif
	       goto startprompt;
	    }
	    /*case 'e': case 'c': supeceeded: expand - contract nodes*/
	    case '(': case ')': /*expand - contract nodes*/ 
	       //fprintf(stderr,"\nlabel_pointsize=%d c_scale=%f node_factor=%f",label_pointsize,c_scale,node_factor);
	       if (show_numbers==-1) break;//dont change node size if not showing nodes
	       if (is[0]==')'){
		  if (show_numbers==1 || show_numbers==2){
		    label_pointsize+=1;
		    if (label_pointsize>40) label_pointsize+=1; //2 steps step for bigger font
		    if (label_pointsize>80) label_pointsize+=2; //4  steps for bigger font
		    if (label_pointsize>=150){ //was 50
                         label_pointsize=150;			 
                        //new_weight=1;
                    }
		  }
		  
		  else{
		     c_scale*=node_factor;
		     if (c_scale>119) c_scale=119;
		  }			
	       }	 
	       else if (is[0]=='('){ 		   
		   if (show_numbers==1 || show_numbers==2){
		      label_pointsize-=1;
		      if (label_pointsize>40) label_pointsize-=1; //2step for bigger font
		      if (label_pointsize>80) label_pointsize-=2; //4 step for bigger font
		      if (label_pointsize<=6){ 
                         label_pointsize=6;
                         //new_weight=1;
                      }
		   }
		   else{
		      c_scale/=node_factor; 
		      //if (c_scale<2.5) c_scale=2.5;
		      if (c_scale<vgax(1)) c_scale=vgax(1);
		   }		   
	       }
	       /*for basin postSript, if selected later*/
	       if (show_numbers==1 || show_numbers==2) psize_ps=label_pointsize; 
	       
	       reset_nodesize();
	       
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       break;            
	    /*case 'E': case 'C': case 'B': case 'b':{*/ /*supeceeded: expand/contract links, 
						      or both links and nodes*/
	    case '}': case '{': case ']': case '[':{ 
	       float this_angle,this_rad;
	     if (show_numbers!=-1){ 
	       if (is[0]==']'){
		  if (show_numbers==1 || show_numbers==2){
		    label_pointsize+=1;
		    if (label_pointsize>40) label_pointsize+=1; //2 steps step for bigger font
		    if (label_pointsize>80) label_pointsize+=2; //4  steps for bigger font
		    if (label_pointsize>=150){ //was 50
                        label_pointsize=150;
                        //new_weight=1;
                    }
		  }
		  else{
		    c_scale*=node_factor;
		    if (c_scale>119) c_scale=119;
		  }
	       }	 
	       else if (is[0]=='['){ 		   
		   if (show_numbers==1 || show_numbers==2){
		      label_pointsize-=1;
		      if (label_pointsize>40) label_pointsize-=1; //2step for bigger font
		      if (label_pointsize>80) label_pointsize-=2; //4 step for bigger font
		      if (label_pointsize<=6){ 
                         label_pointsize=6;
                         //new_weight=1;
                      }
		   }
		   else{
		      c_scale/=node_factor; 
		      //if (c_scale<2.5) c_scale=2.5;
		      if (c_scale<vgax(1)) c_scale=vgax(1);
		   }
	       }
	       
	       if (is[0]=='[' || is[0]==']'){
		  //set up scaled node sizes
	 
		  reset_nodesize();
		  
	       }
	     }//if (show_numbers!=-1){//dont change node size if not showing nodes
	     
	       if (is[0]=='}' || is[0]==']') w_cyclerad*=link_factor;
	       else if (is[0]=='{' || is[0]=='[') w_cyclerad/=link_factor;
	       
	       for (zw=node_no;zw>=1;zw--){
		  compute_link_angle(wox,woy,basin_pos[zw][0],
					     basin_pos[zw][1]);
		  this_angle=linkangle;

		  if (!(wox==basin_pos[zw][0] && woy==basin_pos[zw][1])){
		     this_rad=pow((pow(abs(wox-basin_pos[zw][0]),2)+
				 pow(abs(woy-basin_pos[zw][1]),2)),.5);
		     if (is[0]=='}' || is[0]==']')  this_rad*=link_factor;
		     else if (is[0]=='{' || is[0]=='[') this_rad/=link_factor;
	             
		     basin_pos[zw][0]=(cos(-(this_angle))*this_rad)+wox;
		     basin_pos[zw][1]=(sin(-(this_angle))*this_rad)+woy;
		  }
	       } 
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2 );
	       break;      
	    }
	    	      
	    case '1':{ /*1d layout, set and remember initial basin positions*/
	      double gap;
	      
		 gap=0.9*(double)(X2-X1)/node_no;
		 for (zw=node_no;zw>=1;zw--){	    
		    basin_pos[zw][0]=wox-gap*node_no/2+gap*(node_no-zw)+gap/2;
		    basin_pos[zw][1]=woy;
		 }
		 draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
		 tog_rank=0;
		 break;
	     }
	     case '2':{ /*2d layout: set and remember initial basin positions*/
	       /*toggle between hex/square*/
	       graph_hex2d=abs(graph_hex2d-1);
	       c_scale=draw_2d_graph(X1,Y1,X2,Y2,wox,woy);
	       tog_rank=0;
	       break;
	     }
	     case '3':{ /*3d layout: set and remember initial basin positions*/
		c_scale=draw_3d_graph(X1,Y1,X2,Y2,wox,woy);
		tog_rank=0;
	        break;
	     }
	     case 'r': case 'R': 
	       /* r - randomize the existing layout by a small amount*/
	       /* R - random layout*/ 
	       for (zw=node_no;zw>=1;zw--){
		   if (is[0]=='r'){
			basin_pos[zw][0]+=
			  (rand()%(vgax(10)) - rand()%(vgax(10)) );
			basin_pos[zw][1]+=
			  (rand()%(vgax(10)) - rand()%(vgax(10)) );
		   }
		   else if (is[0]=='R'){
		      basin_pos[zw][0]=rand()%(X2-X1-vgax(240)) + X1+vgax(120);
		      basin_pos[zw][1]=rand()%(Y2-Y1-vgay(60)) + Y1+vgay(30);
		   }
	       }
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       tog_rank=0;
	       break;

	    case '=':
		if (no_links==1  || jump_layout_only){//if no_links skip blank)
		     show_numbers_nolinks=abs(show_numbers_nolinks-1);
		     show_numbers=show_numbers_nolinks;
		     //fprintf(stderr,"\nnolinks:show_numbers2=%d",show_numbers);
		     draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
		     break;
		}
		
		else{    
		  //nt for graphs with no_links
		  //toggle node presentation, show_numbers:
                  //-1 none (miss out, blank) , 0 spot, 1 dec(lineL<32), 2 hex, 3 1d bits,  4 2d bits
		  	
		   if (show_numbers==-1) show_numbers=0; 
		   else if (show_numbers==0) show_numbers=1; //1 dec(lineL<32)
		   else if ((graph_type=='s' || graph_type=='t') && show_numbers==1) show_numbers=2; //2 hex
		   else if ((graph_type=='s' || graph_type=='t') && show_numbers==2){
		                                     //note : no 1d or 2d patterns for graph_type=='n'
		         show_numbers=3; //1d bits
	           }
		   else if ((graph_type=='s' || graph_type=='t') && show_numbers==3){//3 2d bits
		          show_numbers=4; //4 2d bits
	           }
	           else show_numbers=-1;		   
		   //fprintf(stderr,"\n=show_numbers=%d",show_numbers);
		   draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);                   
	           break;
		}
	      case 's':
	          if (graph_type=='f'|| jump_layout_only==1){ //rescale basins for the field inside nodes*/		 
	             xbox=draw_prompt_box(2);

		     /*outtext("change basin scale for graph (rad main window=%.1f)", jump_startrad);
	             moveto(xbox,gety+CHeight);
	             sprintf(textb[0],"(rad main window=%.1f, in graph=%.1f)", 
		          jump_startrad,startrad);*/

		     
		     sprintf(textb[0],"change basin scale for graph (rad main window=%.1f)", jump_startrad);
	             outtext(textb[0]);
	             moveto(xbox,gety+CHeight);
	             sprintf(textb[0],
		        "select attractor rad (min %.2f def %.1f):",220.0/Maxx,startrad);
	             outtext(textb[0]);                 
	             input_string(4,0);
	             if (is[0]!=13 && atof(is)>=220.0/Maxx){
		       float r; 
		       signed int z;  
		       startrad=atof(is);
		       /*set up array of levels*/
		       for (z=1;z<=lastlevel;z++){    /*lastindex=lastlevel-1*/
		          if (z==1) r=startrad;
		          else r += (startrad/(trans_shrink_fact)/trans_shrink_fact)/log(pow(z,2));
		          rad[z-1]=r;
		       }
	             }
	             erase_prompt_box(2);
	             goto startprompt;
	          }
	          else break;
		  
	    /*redraw the field with basins in new positions
	    I'=inside nodes, 'i' without nodes*/
	    case 'i': case 'I':{ 
	       float node_size;
	       signed int state_space;
	       unsigned char *graph_pos;
	       unsigned int thisbyte,zw;
               char file_ret,fid2,ok=1,save_layout=0;

	       if (exhaustive_testing)
		   exh_pairs_in_jump_nodes=1;//to redraw basins within jump-graph nodes if exhaustive_testing

               /*fprintf(stderr,"\nstart 'i': case 'I' jump_graph=%d ep_in_jump_nodes=%d",
		 jump_graph,exh_pairs_in_jump_nodes);*/
	       /*if (graph_type!='f') goto startbox;*/
	       if (graph_type=='s' || graph_type=='t') break;
	       if (graph_type=='n' && jump_layout_only==0) break;
	       if (graph_type=='a') break;
	       //graph_type!='f' and jump_layout_only allowed
	       
	       //if ((graph_type=='n' && jump_layout_only==0) || graph_type=='a') goto startbox;

	       this_text_size=current_text_size;
               # if __UNIX__
                       free_fonts();
                       setup_fonts(start_pointsize);
               # endif	
	       
	       if (basin_postScript) prepare_basinPS(1,1); /*to draw basin field to postScript*/
	       use_preset_basin_pos=1;
	       if (is[0]=='I'){ /*empty circles inside nodes*/      
		  for (zw=node_no;zw>=1;zw--){	     
		     /*remembered positions*/
		     moveto(basin_pos[zw][0],basin_pos[zw][1]);
		     setfillstyle(SOLID_FILL,black);
		     if (scale_m_nodes==1)
			  node_size=0.9*m_node_size[zw];    
		     else node_size=0.9*c_scale;  
		     pieslice(1,getx,gety,0,360,(signed int)node_size);

		     if (basin_postScript){ /*empty circles in postscript*/
			color_ps(basin_postScript-1,black);
			circle_fill_ps(basin_pos[zw][0],basin_pos[zw][1],
				       (double)node_size);/*filled circle*/
			color_ps(basin_postScript-1,white);
			circle_ps(basin_pos[zw][0],basin_pos[zw][1],
				       (double)node_size);/*outline*/
		     }
		  }
	       }
	       else if (is[0]=='i') draw_box(-1,X1,Y1,X2,Y2,1,0);/*clear box*/
	       erase_prompt_box(4);
	       
               if (lineL<=max_exh_lu){ //limit state-space as allowed
		 //state-space positions for basin inside jump-graph nodes		 
	          state_space=(unsigned int)(pow(value_range,(double)lineL)); //size of state-space
                  if ((basin_pos_injump=(signed int**)calloc(state_space+1,
		      sizeof(signed int*)))==NULL) outof_memory("basin_pos_injump");
	          for (zw=0;zw<=state_space;zw++){
		     //fprintf(stderr,"%d ",zw);
	             if ((basin_pos_injump[zw]=(signed int *)calloc(
			   2,sizeof(signed int)))==NULL) outof_memory("basin_pos_injump[]");
                  }
               }
	       
	       /*if (graph_type=='f' && exhaustive_testing){
		   memmove(exh_pairs,exh_pairs_backup,state_space*bytesL);
		   exh_pairs_in_jump_nodes=1;//to redraw basins within jump-graph nodes if exhaustive_testing
	       }*/

	       
	       draw_field(); /*redraw the field with basins in new positions*/
	       //fprintf(stderr,"\nafter  draw_field()");
	       print_field_data();
	       
	       //save uncompessed baf or rndom_map layout for ibag-graph 
	       if (dontcompress==1 || exhaustive_testing){ 
                  sprintf(textb[3],"  setcolor(lightred)");
	          setcolor(lightred);
	          sprintf(textb[3]," cont-ret, savelayout-s:");
	          outtext(textb[3]);
	       }	  
	       input_string(1,0);
	       if (is[0]=='s' && (dontcompress==1 || exhaustive_testing)) save_layout=1;
	       setcolor(white);
	       
	       /*note: to save basins inside jumpgraph nodes as a postPcript file,
                       (saving the basin ps file is first activated)
		       in the directory with the .ps files, enter the following in xterm,
		       concatenate: cat my_jgPS.ps my_bPS.ps > my_temp.ps or similar,
		       first the jumpgraph.ps file,then the basin.ps file*/
		       
               if (lineL<=max_exh_lu){ //limit state-space as allowed
	          if (save_layout==1 && dontcompress==1){
		     if ((graph_pos=(unsigned char*)calloc((state_space+1)*4,
		         sizeof(unsigned char)))==NULL) outof_memory("graph_pos");

                     for (zw=1;zw<=state_space;zw++){
		        /*fprintf(stderr,"\n%dx%d ",basin_pos[z][0],basin_pos[z][1]);*/
		        thisbyte=zw*4;                 
		        graph_pos[thisbyte]=(unsigned char)(basin_pos_injump[zw][0] & 0x00ff); 
		        graph_pos[thisbyte+1]=(unsigned char)(basin_pos_injump[zw][0] >> 8);
		        graph_pos[thisbyte+2]=(unsigned char)(basin_pos_injump[zw][1] & 0x00ff); 
		        graph_pos[thisbyte+3]=(unsigned char)(basin_pos_injump[zw][1] >> 8);
	             }

	             file_ret=select_filename("SAVE","GRAPH LAYOUT","*.grh","my_grh");

	             fid2=myopen(filename,1,0);
	             if (fid2==-1){
		        ok=0;
		        file_error(filename);
		        close(fid2);
		        goto exitSave;
	             }
	             vret=write(fid2, graph_pos, (state_space+1)*4*sizeof(unsigned char));
	             close(fid2);
		     exitSave:
	             free(graph_pos);
		  }//if (save_layout==1){
		  
		  save_layout=0;

		  //fprintf(stderr,"\nfree(basin_pos_injump ... ");
		  for (zw=0;zw<=state_space;zw++){
		    //fprintf(stderr," %d",zw);
                    free(basin_pos_injump[zw]);
                  }
	          free(basin_pos_injump); 
		  //fprintf(stderr,"freed");
		  
               }//if (lineL<=max_exh_lu){
	       
	       if (basin_postScript) close(fid_PS);/*close the postScript file -- for DOS to work*/

	       current_text_size=this_text_size;
               # if __UNIX__
                       free_fonts();
                       setup_fonts(current_text_size);
               # endif
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       
	       is[0]=0;
	       if (basin_postScript) prepare_basinPS(1,1); /*to reset postScript*/
	       //fprintf(stderr,"\nredraw inside jomp node complete");
		       
	       goto startprompt;          
	     }//case 'i': case 'I':{ 	     	      
	   }//switch(is[0]){
	   /*------------------------------------------------------*/
	    
	   if (is[0]!='q') goto startbox;
	   /*for space-time patterns according to graph*/
	   if (att_types==1 && graph_type=='n'){
	      for (zw=0;zw<=node_no;zw++) /*copy node positions*/
		memmove(stp_graph_layout[zw],basin_pos[zw],
					   sizeof(signed int)*2);
	      /*acopy node sizes*/                      
	      memmove(stp_graph_node_size,m_node_size,(node_no+1)*sizeof(float));
	   }
	   free(reorder_graph);
	   for (zw=0;zw<=node_no;zw++) free(temp_basin_pos[zw]);
	   free(temp_basin_pos);
	   	   
	   //calloc and free basin_pos now done in main for both istr and ibaf graphs 19/06/25
	   
	   if (graph_type=='s' || graph_type=='t'){ /*free basin_pos_backup only for graph_type=='s'*/
	      //fprintf(stderr,"\nabout to free(basin_pos_backup) graphxx"); 
              for (zw=0;zw<=node_no;zw++){
                    free(basin_pos_backup[zw]); 
              }
              free(basin_pos_backup);
           }
        
	   //free(m_node_size); now freed on return graph (jump_graph_table)
	   free(outside_inputs);
	   sprintf(textb[9],"%s","boximage[22]");   
	   putimage(X1,Y1,boximage[22],COPY_PUT,textb[9]); //?? caused segfault	   
	   //uncover_free_prompt_box(12);
	   erase_prompt_box(4);//just erase (4 lines), dont free
	   //fprintf(stderr,"\nfpb12-l2009");

     }/******* end: draw jump-graph *****/

     if (no_links==0){
	   for (zw=1;zw<=node_no;zw++){ 
	      free(basinjumps[zw]);
	      free(b_j[zw]);
	   }
	   free(basinjumps);
	   free(b_j);
     }
     
     free(basin_color);
     if (graph_type=='f' || jump_layout_only==1){
	   for (zz=0;zz<=node_no;zz++){                 
	     for (z=0;z<=m_att_period[zz];z++) free(m_att[zz][z]);
	   }
	   for (zz=0;zz<=node_no;zz++) free(m_att[zz]);
	   free(m_att);
     }
     
     if (jump_layout_only==1) free(m_basin_volume);          
     else if (no_links==0){
	  
	   if (graph_type=='f') free(m_basin_volume);
	   if (graph_type=='a'){
	      free(m_att_period);
	      free(histnodesize);
	   }  
	   if (graph_type=='s' || graph_type=='t' || graph_type=='n'){
             free(frag_node_types);
	     free(netnodesize);
	   }
     }
     
     if (no_links==1 && graph_type=='n'){
       free(netnodesize);
       free(frag_node_types);
     } 
     
     {    float r; 
	  signed int z; 
	   startrad=jump_startrad;
	   /*set up array of levels*/
	   for (z=1;z<=lastlevel;z++){    /*lastindex=lastlevel-1*/
	      if (z==1) r=startrad;
	      else r+= startrad/log(pow(z,2));
	      rad[z-1]=r;
	   }
      }
      datapause=jump_datapause; /*restore datapause for main basins;*/

      xoffset=temp_xoffset;
      yoffset=temp_yoffset;

      
      # if __UNIX__
            free_fonts();
            setup_fonts(start_pointsize);
      # endif

      if (graph_type=='f' && exhaustive_testing){
	//fprintf(stderr,"\nfree exh_pairs_backup  -graph return(1)... ");
	 free(exh_pairs_backup);
	 //fprintf(stderr,"freed!");
      }  
      exh_pairs_in_jump_nodes=0;	    
      //uncover_free_prompt_box(12); //[12] from get_prompt_box(12,4)
      erase_prompt_box(4);//just erase (4 lines), dont free
      //fprintf(stderr,"\nfpb12-l2078");
      
      //fprintf(stderr,"\n%c:final return-graph",graph_type);//check_crash
      return(1); /*graph completed, otherwise return(0)*/
 } /*********** complete jump-graph table  ***********/

void print_exh_pairs(char *this_exh_pairs){ //to check if correct
    unsigned long state_space,prestate;
    unsigned int poss;
    
       state_space=(unsigned long)(pow(value_range,(double)lineL));
       for (prestate=0;prestate<=state_space-1;prestate++){
         memmove(state2,this_exh_pairs+prestate*bytesL,bytesL);

         fprintf(stderr,"\n %lu ",prestate);
         if (value_range==2) dec_to_bit_line(state1,prestate,lineL);
         else dec_to_value_line(state1,prestate,lineL);
         for (poss=L;poss!=Maxu;poss--) fprintf(stderr,"%d",get_value(state1, poss));
         fprintf(stderr," ");
         memmove(state2,this_exh_pairs+prestate*bytesL,bytesL);
         for (poss=L;poss!=Maxu;poss--) fprintf(stderr,"%d",get_value(state2, poss));
         fprintf(stderr," %lu",dec_equiv(state2,L));
      }
}

/*** redraw and save the graph as a Postscript file, separate function for initial graph or fragmented *****/
     //to view the .ps file use ghostview, enter  gv&
     //to convert to pdf retaining the whole .ps image, enter ps2pdf -dEPSCrop my_tgPS.ps (optional myfile.pdf)
void save_graph_PScript(unsigned int most_recent_node,signed int X1, signed int Y1,
	       signed int X2, signed int Y2,
	       signed int wox, signed int woy){
  
	       signed int temp_psize_ps;
               signed int temp_fid_PS,temp;
	       char file_ret,temp_basin_postScript,tempscale;

	            //temp_psize_ps=psize_ps;
	       
		    /*disable basin_postScript*/
		    temp_fid_PS=fid_PS; /*to restore fid_PS (global variable) afterwards*/
		    temp_basin_postScript=basin_postScript;
		    basin_postScript=0;
		    temp=basin_postScript=basin_postScript;
		    tempscale=scale;
                    scale=(char)c_scale;
		    if (is[0]=='p') graph_postscript=basin_postScript=1;
		    else if (is[0]=='P') graph_postscript=basin_postScript=2;
		    
		    this_text_size=current_text_size;
                    # if __UNIX__
                          free_fonts();
                          setup_fonts(start_pointsize);//to preserve normal prompt font
                    # endif
		    
		    /*select filename for graph_postScript ascii file*/		    
		    if (graph_type=='a' || //includes attractor histogram
			 graph_type=='f' || jump_layout_only==1) /*for jump-graph with/without links*/
		      file_ret=select_filename("SAVE","PostScript file","*.ps","my_jgPS");//for jump graph
		    else if (graph_type=='s'  || graph_type=='t') /*for jump-graph of basin of attraction field*/
		      file_ret=select_filename("SAVE","PostScript file","*.ps","my_bgPS");//for ibaf graph
		    else /*igraph_type=='n' for network-graph with/without links*/		      
		       file_ret=select_filename("SAVE","PostScript file","*.ps","my_ngPS");//for network graph
		    
		    if (file_ret=='q') goto skip_ps0;
		    if ((filename_graph_PS=(char *)calloc(13,sizeof(char)))
				    ==NULL) outof_memory("filename_graph_PS");
		    memmove(filename_graph_PS,filename,13);

		    /*delete previous*/
		    fid_PS=myopen(filename_graph_PS,1,0);
		    vret=write(fid_PS, "",0);
		    close(fid_PS);
		    
		    /*start new*/		    		    
		    fid_PS=myopen(filename_graph_PS,1,1);		    
		    if (fid_PS==-1){ 
			file_error(filename_graph_PS);
			goto skip_ps;
		    }
                    	    
                    prepare_basinPS(2,1); /*write/define postScipt for graph, default text size*/
		    
		    //restore previous textsize changed by prompt		    
                    current_text_size=this_text_size;
                    # if __UNIX__
                          free_fonts();
                          setup_fonts(current_text_size);
                    # endif
                    if (in_manipulate==0){
		           //resetfont_ps("Times-Roman",current_text_size);//in case fontsize was changed
		           resetfont_ps("Times-Bold",current_text_size);//in case fontsize was changed
		           psize_ps=current_text_size;
		    }

		    if (in_manipulate==0) draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
		    else if (in_manipulate==1) draw_jump_graph(most_recent_node,wox,woy,X1,Y1,X2,Y2);
		    
		   skip_ps:
		    
		    close(fid_PS); 
		    graph_postscript=0;
		    free(filename_graph_PS);
                   skip_ps0:
		    fid_PS=temp_fid_PS; /*to restore fid_PS (global variable) afterwards*/
		    basin_postScript=temp_basin_postScript;/*to restore basin_postScript*/
		    scale=tempscale;
}                   //psize_ps=temp_psize_ps;

/******* stp layout: predefined node positions April  2021*******/
float draw_predefined_stp(signed int X1, signed int Y1,
	       signed int X2, signed int Y2,
   	       signed int wox, signed int woy) {

                unsigned int zw;

		/*for (zw=node_no;zw>=1;zw--){		  
		 fprintf(stderr,"\n>>>%d:%d,%d",zw,basin_pos[zw][0],basin_pos[zw][1]); 
		 }*/

               draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       return(c_scale);
 }

/******* circle layout: set and remember initial basin positions *******/
float draw_circle_graph(signed int X1, signed int Y1,
	       signed int X2, signed int Y2,  
	       signed int wox, signed int woy,
	       double w_angle){
  
              unsigned int zw;

	       for (zw=node_no;zw>=1;zw--){		  
                  basin_pos[zw][0]=(cos(-(w_angle*zw))*w_cyclerad)+wox;
	          basin_pos[zw][1]=-(sin(-(w_angle*zw))*w_cyclerad)+woy; 
	       }	       
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       return(c_scale);
 }

 /****** 2d layout: set and remember initial basin positions *******/
 float draw_2d_graph(signed int X1, signed int Y1,
	       signed int X2, signed int Y2,
	       signed int wox, signed int woy) {

   signed int tempi2d,i2d_m,j2d_m,xz,yz;
   unsigned int poss;
   double gap;
   
	       /*To represent jumpgraph roughly 2d*/ 
	       if (graph_type=='f' || graph_type=='a' || oned || threed)
		 i2d_m=j2d_m=(signed int)ceil(pow((double)node_no,.5));
	       else if (twod){
		  i2d_m=i2d;
		  j2d_m=j2d;
	       }
	       else if (threed){
		  i2d_m=i3d;
		  j2d_m=j3d*h3d;
	       }
	       /*make sure i is bigger*/
	       if (!twod && (graph_type=='s' || graph_type=='t' || graph_type=='n') && j2d_m>i2d_m){ 
		  tempi2d=i2d_m;
		  i2d_m=j2d_m;
		  j2d_m=tempi2d;
	       }
	       gap=2*w_cyclerad/j2d_m;              
	       if (i2d_m*gap>X2-X1) gap=(X2-X1)/i2d_m;

	       for (yz=j2d_m;yz>=1;yz--){
		 for (xz=i2d_m;xz>=1;xz--){                                 
		     poss=i2d_m*(yz-1) + xz;
		     if (poss>node_no) continue;
		     basin_pos[poss][0]=(wox-gap*i2d_m/2)+gap*(i2d_m-xz)+gap/2;
		     basin_pos[poss][1]=(woy-gap*j2d_m/2)+gap*(j2d_m-yz)+gap/2;
		  }
	       }
	       /*show hex layout triangular grid for 2d CA, even sides, and k=6 or 7*/
	       /*if (graph_type=='n' && twod && nhood_mixed==0 
			 && (nhood==6 || nhood==7) && i2d%2==0 && j2d%2==0){*/
		 if (graph_hex2d==1){
		     double gap60;
		     gap60=gap/cos(PI/6); /*PI/2=90 degrees*/                   
		     for (yz=j2d_m;yz>=1;yz--){
			for (xz=i2d_m;xz>=1;xz--){
			   poss=i2d_m*(yz-1) + xz;
			   if (poss>node_no) continue;

			   if (yz%2==1)
			      basin_pos[poss][0]=(wox-gap60*i2d_m/2)+
					   gap60*(i2d_m-xz)+gap60;
			   else basin_pos[poss][0]=(wox-gap60*i2d_m/2)+
					   gap60*(i2d_m-xz)+gap60/2;
			   basin_pos[poss][1]=
			     (woy-gap*j2d_m/2)+gap*(j2d_m-yz)+gap/2;
			}
		     }
	       } 
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       return(c_scale);
 }

 /******* 3d layout: set and remember initial basin positions *******/
 float draw_3d_graph(signed int X1, signed int Y1,
	       signed int X2, signed int Y2,
	       signed int wox, signed int woy) {

   //double this_f, av_f;
  signed int i3d_m,j3d_m,h3d_m,xz,yz,hz;
  unsigned int poss;
  double gap;

	       /*To represent jumpgraph roughly 3d*/
	       if (graph_type=='f' || graph_type=='a' || threed==0)
		 i3d_m=j3d_m=h3d_m=
			(signed int)ceil(pow((double)node_no,1.0/3));
	       else if (threed){
		  i3d_m=i3d;
		  j3d_m=j3d;
		  h3d_m=h3d;
	       }
	       gap=w_cyclerad/h3d_m;  
	       if (i3d_m*gap>X2-X1) gap=(X2-X1)/i3d_m;            
	       for (hz=h3d_m;hz>=1;hz--){
		  for (yz=j3d_m;yz>=1;yz--){
		     for (xz=i3d_m;xz>=1;xz--){
			poss=i3d_m*j3d_m*(hz-1)+i3d_m*(yz-1)+xz;
			if (poss>node_no) continue;			
			basin_pos[poss][0]=wox+gap*(i3d_m-xz)+gap/2-sin(PI/4)*yz*gap;
			basin_pos[poss][1]=(woy-0.5*gap*h3d_m*(1+sin(PI/4)))
				              +gap*(h3d_m-hz)+gap/2+sin(PI/4)*yz*gap;
		     }
		  }
	       }
	       draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	       return(c_scale);
 } 


 /********************** unscramble the graph  ************************/
 void unscramble_graph(signed int X1, signed int Y1,
              signed int X2, signed int Y2,signed int wox, signed int woy){
   unsigned int zw,zu,*node_outputs,*node_inputs,*shuford,
     con_to,ord,bytes_size,tot_out=0,tot_in=0,zero_in=0,zero_out=0;
   float av_out,av_in;
   signed int dist_from_center;      
   float this_angle,rand_angle1,rand_angle2,this_rad;
   char *in_check,*out_check,in_out_order,count=0;

   if (no_links==1) return; //there must be links because algoryth counts links
	 if ((node_outputs=(unsigned int*)calloc(node_no+1,
		   sizeof(unsigned int)))==NULL) outof_memory("node_outputs");    

	 if ((node_inputs=(unsigned int *)calloc(node_no+1,
		    sizeof(unsigned int)))==NULL) outof_memory("node_inputs");
	 /*shuffle order*/
	 if ((shuford=(unsigned int *)calloc(node_no+1,
		    sizeof(unsigned int)))==NULL) outof_memory("shuford");

	 bytes_size=(signed int)ceil((double)(node_no+1)/8);
	 //bytes_size=node_no+1;
	 
	 if ((out_check=(char *)calloc(bytes_size+1,sizeof(char)))
					 ==NULL) outof_memory("out_check");
	 if ((in_check=(char *)calloc(bytes_size+1,sizeof(char)))
					 ==NULL) outof_memory("in_check");
         
	 for (zu=1;zu<=node_no;zu++){
		 for (zw=1;zw<=node_no;zw++){
		    //if (zw!=zu ){ //don't count self outputs -- why not count?		     
		         node_outputs[zu]+=basinjumps[zu][zw];			   
		         node_inputs[zu]+=basinjumps[zw][zu];			     
		    //}
		 }
		 tot_out+=node_outputs[zu];
		 tot_in+=node_inputs[zu];
	 }
         for (zu=1;zu<=node_no;zu++){
	   if (node_outputs[zu]==0) zero_out+=1;
           if (node_inputs[zu]==0) zero_in+=1;
         }
	 
	 //the positive average excluding zero in or out--- must be the same ?
	 av_out=(float)tot_out/(node_no-zero_out);
	 av_in=(float)tot_in/(node_no-zero_in);
	 
	 /*fprintf(stderr,"\nav_out=%d/%d=%f av_in=%d/%d=%f",tot_out,node_no-zero_out,av_out,
	                                                     tot_in,node_no-zero_in,av_in);*/
	 
	 in_out_order=myrand()%2; /*0 or 1*/

	 while(count<=2){
	   float coord0=0,coord1=0;
	    count+=1;
	    if (in_out_order==0){//outputs
	       //fprintf(stderr,"\noutputs\n");
	       if (graph_type=='s' || graph_type=='t') goto skip_outputs; //skip utputs for ibaf-graph because allway=1
	       shuffle_order1(shuford,node_no);
	       
	       for (zu=1;zu<=node_no;zu++){
		  ord=shuford[zu];  /*1 output and wasnt a target before*/		  
		  if (node_outputs[ord]<av_out && get_bit(out_check,ord)==0){
		
		    compute_link_angle(wox,woy,basin_pos[ord][0],basin_pos[ord][1]);
                    set_bit1(out_check,ord);
		    
		        this_angle=linkangle;
			//fprintf(stderr,"%d=%.2f ",ord,this_angle);
		        rand_angle1=rand()%100 * (PI/6)/100;  /*10 degrees each side*/
		        rand_angle2=rand()%100 * (PI/6)/100;
		        this_rad=w_cyclerad*0.15;
		        dist_from_center=pow((pow(abs(wox-basin_pos[ord][0]),2)+
			                 pow(abs(woy-basin_pos[ord][1]),2)),.5);
			
		        /*limit rad*/
		        if (dist_from_center>w_cyclerad*1.5) this_rad*=-1;                        
			coord0=(cos(-(this_angle+rand_angle1-rand_angle2))*this_rad)
						       +basin_pos[ord][0];
		        coord1=(sin(-(this_angle+rand_angle1-rand_angle2))*this_rad)
			                               +basin_pos[ord][1];
			
		        //if (coord0<=X1 || coord1<=Y1 || coord0>=X2 || coord1>=Y2); //dont do
		        //else{
		           basin_pos[ord][0]=coord0;
		           basin_pos[ord][1]=coord1;
			 //}	
		  }
		}
	       
	       skip_outputs:
	       in_out_order=1;
	    }
	 
	    else if (in_out_order==1){//inputs
	      float coord0,coord1;
	      //fprintf(stderr,"\ninputs\n");
	      
	       shuffle_order1(shuford,node_no);
	       for (zu=1;zu<=node_no;zu++){
		  ord=shuford[zu];  /*1 output and wasnt a source before*/
		  if (node_inputs[ord]<av_in && get_bit(out_check,ord)==0){		    
		    compute_link_angle(wox,woy,basin_pos[ord][0],basin_pos[ord][1]);
		    set_bit1(in_check,ord);
		    
		        this_angle=linkangle;		
			//fprintf(stderr,"%d=%.2f ",ord,this_angle);
		        rand_angle1=rand()%100 * (PI/6)/100; /*30 degrees each side*/
		        rand_angle2=rand()%100 * (PI/6)/100;

		        this_rad=w_cyclerad*0.15;
		        dist_from_center=pow((pow(abs(wox-basin_pos[ord][0]),2)+
		                         pow(abs(woy-basin_pos[ord][1]),2)),.5);
		        /*limit rad*/
		        if (dist_from_center>w_cyclerad*1.5) this_rad*=-1;
                        
		        coord0=(cos(-(this_angle+rand_angle1-rand_angle2))*this_rad)
						       +basin_pos[ord][0];
		        coord1=(sin(-(this_angle+rand_angle1-rand_angle2))*this_rad)
						       +basin_pos[ord][1];
			
		        //if (coord0<=X1 || coord1<=Y1 || coord0>=X2 || coord1>=Y2); //dont do
		        //else{
		           basin_pos[ord][0]=coord0;
		           basin_pos[ord][1]=coord1;
			//}
		     }
	       }                 
	       
	       in_out_order=0;
	    }
	 }
         //fprintf(stderr,"\nabout to free unscramble_graph");
	 free(node_outputs);
	 free(node_inputs);
	 free(shuford);
	 free(out_check);
	 free(in_check);
	 //fprintf(stderr,"\nfreed unscramble_graph");
 }

 /************************* shuffle the order 1 to n ************************/
 void shuffle_order1(unsigned int *shuff_array, unsigned int size){
   unsigned int zu,zz;
	      for (zu=1;zu<=size;zu++){
		  reorder:
		  shuff_array[zu]= myrand()%(size+1);
		  if (shuff_array[zu]==0) goto reorder;
		  if (zu>1){
		     for (zz=1;zz<=zu-1;zz++){
			if (shuff_array[zu]==shuff_array[zz]) goto reorder;
		     }
		  }
	       };
 }
 /***************** reorder according to rank  ************************/
 void reorder_rank(unsigned int *reorder_graph){
     unsigned int zw,temp_order;
     char sortneeded;
               
	       while(1){
		    sortneeded=0;
		    for (zw=2;zw<=node_no;zw++){
		      
		         /*reorde smallest to biggest basin
		          for network-graph reorder by node size based on inputs or outputs, whiever is active
			  for jump-graph,reorder by basin volume*/

			 if (graph_type=='n' || graph_type=='s' || graph_type=='t'){
                             if (m_node_size[reorder_graph[zw]]
				   < m_node_size[reorder_graph[zw-1]]){
				 temp_order=reorder_graph[zw-1];
				 reorder_graph[zw-1]=reorder_graph[zw];
				 reorder_graph[zw]=temp_order;
				 sortneeded=1;
			     } 
			  }			   
			  else if (graph_type=='f'){
			     if (m_basin_volume[reorder_graph[zw]]
				   < m_basin_volume[reorder_graph[zw-1]]){
				 temp_order=reorder_graph[zw-1];
				 reorder_graph[zw-1]=reorder_graph[zw];
				 reorder_graph[zw]=temp_order;
				 sortneeded=1;
			     } 
			  }
			  else if (graph_type=='a'){
			     if (histnodesize[reorder_graph[zw]]
				   < histnodesize[reorder_graph[zw-1]]){
				 temp_order=reorder_graph[zw-1];
				 reorder_graph[zw-1]=reorder_graph[zw];
				 reorder_graph[zw]=temp_order;
				 sortneeded=1;
			     } 
			  }
			 
		       
		    }
		    if (sortneeded==0) break;
	       }
 }

 /***************** rotate graph or component ************************/
 void rotate_component_graph(char clockwise,float rot_angle,
			    signed int c_x, signed int c_y){
   unsigned int zw;
   float this_angle,this_rad,this_rot_angle;

   if (clockwise=='x') this_rot_angle=-rot_angle;
   else if (clockwise=='X') this_rot_angle=rot_angle; 
	       //rotate whole jumpgraph by 10 degrees, or new angle set
	       for (zw=node_no;zw>=1;zw--){
		  compute_link_angle(c_x,c_y,basin_pos[zw][0],
					     basin_pos[zw][1]);
		  this_angle=linkangle;

		  if (!(c_x==basin_pos[zw][0] && c_y==basin_pos[zw][1])){
		    if (fragment==1 && get_bit(linknet,zw)==0) continue;
		    this_rad=pow((pow(abs(c_x-basin_pos[zw][0]),2)+
				 pow(abs(c_y-basin_pos[zw][1]),2)),.5);
		    basin_pos[zw][0]=(cos(-(this_angle+
					     this_rot_angle))*this_rad)+c_x;
		    basin_pos[zw][1]=(sin(-(this_angle+
					     this_rot_angle))*this_rad)+c_y;
		  }
	       }
 }

 /***************** flip graph or component ************************/
 void flip_component_graph(char which,
			    signed int c_x, signed int c_y){

   signed int flip;
   unsigned int zw;

	       for (zw=node_no;zw>=1;zw--){
		 if (fragment==1 && get_bit(linknet,zw)==0) continue;
		 if (which=='h'){ 
		     flip=c_x-basin_pos[zw][0];
		     basin_pos[zw][0]+=(flip*2);
		 }  
		 else if (which=='v'){ 
		     flip=c_y-basin_pos[zw][1];
		     basin_pos[zw][1]+=(flip*2);
		 }                 
	       }
 }

 /***************** Expand/Contract links -- graph or component, March2021************************/
 void EC_links_component_graph(char which,
			    signed int c_x, signed int c_y){
   unsigned int zw;
   float this_angle,this_rad;

              //fprintf(stderr,"\n f=%d, w=%c\n",fragment,which);
	      for (zw=node_no;zw>=1;zw--){
		 //fprintf(stderr,"%d",get_bit(linknet,zw));

		 if (fragment==1 && get_bit(linknet,zw)==0) continue;

		 compute_link_angle(c_x, c_y,basin_pos[zw][0],
					     basin_pos[zw][1]);
		  this_angle=linkangle;

		  if (!(c_x==basin_pos[zw][0] && c_x==basin_pos[zw][1])){
		     this_rad=pow((pow(abs(c_x-basin_pos[zw][0]),2)+
				 pow(abs(c_y-basin_pos[zw][1]),2)),.5);
		     if (which=='}') this_rad*=link_factor;
		     else if (which=='{') this_rad/=link_factor;
		     //fprintf(stderr,"\n this_rad=%f",this_rad);
			     
		     basin_pos[zw][0]=(cos(-(this_angle))*this_rad)+c_x;
		     basin_pos[zw][1]=(sin(-(this_angle))*this_rad)+c_y;
		  }
	       }
              
}

/***************** Expand/Contract nodes -- graph or component, March2021************************/
void EC_nodes_component_graph(char which,unsigned int most_recent_node,char blockset){
   unsigned int zw;
   
   //fprintf(stderr,"\n f=%d, w=%c node_no=%d\n",fragment,which,node_no);
   /*for (zw=node_no;zw>=1;zw--)
     fprintf(stderr,"%d",get_bit(linknet,zw));*/

   /*fprintf(stderr,"\nnode_factor=%f c_scale=%f show_numbers=%d",
     node_factor,c_scale,show_numbers);*/

              /*fprintf(stderr,"\n type: no_links=%d jump_layout_only=%d blockset=%d",
		no_links,jump_layout_only,blockset);*/
	      
              for (zw=node_no;zw>=1;zw--){
		 if (frag_node_types[zw]==-1) continue;//dont change node size if not showing nodes
		     
		 if (most_recent_node!=-1){//for all nodes
		      //for unlinked graph
		      if ((no_links==1 || jump_layout_only==1) && blockset==0){
			 if (zw==most_recent_node){ //act on single node
			   //fprintf(stderr,"\nsize: zw=%d most_recent_node=%d",zw,most_recent_node);
			 }  
		         else continue;
		      } 
		      else{
		         if (most_recent_node==zw){//include most_recent_node, i.e. selectednode , in fragment
		            //fprintf(stderr,"\nmost_recent_node=%d zw-1=%d",most_recent_node,zw-1);
		         }
		         else if (fragment==1 && get_bit(linknet,zw)==0 /*&& most_recent_node*/){
                            //fprintf(stderr,"\n skip node %d",zw);
			    continue;
                         }
		      }	 
		 }		
                 if (which==')'){
		   if (in_manipulate==0 && (show_numbers==1 || show_numbers==2) ||
		       (in_manipulate==1 && (frag_node_types[zw]==1 || frag_node_types[zw]==2) ) ){
		       text_node_size[zw]+=1;
		       if (text_node_size[zw]>40) text_node_size[zw]+=1; //2 steps step for bigger font
		       if (text_node_size[zw]>80) text_node_size[zw]+=2; //4  steps for bigger font
		       if (text_node_size[zw]<=start_pointsize){ 
			    text_node_size[zw]=start_pointsize;
                            //new_weight=1;
                       }
		       if (text_node_size[zw]>=150){ //was 50
                           text_node_size[zw]=150;
			   
                           //new_weight=1;
                       } 
		       //fprintf(stderr,"\ntext_node_size[%d]=%d",zw,text_node_size[zw]);
		   }
		   else{
		     //fprintf(stderr,"\nm=%f, s=%f",m_node_size[zw],s_node_size[zw]);
		     m_node_size[zw]*=node_factor;
		     s_node_size[zw]*=node_factor;
		   }  
	        }
		 
	        else if (which=='('){ 		   
		  if ((in_manipulate==0 && (show_numbers==1 || show_numbers==2)) ||
		      ((in_manipulate==1 && (frag_node_types[zw]==1 || frag_node_types[zw]==2)) ) ){
		        text_node_size[zw]-=1;
			if (text_node_size[zw]>40) text_node_size[zw]-=1; //2step for bigger font
		        if (text_node_size[zw]>80) text_node_size[zw]-=2; //4 step for bigger font
		        if (text_node_size[zw]<=6){ 
			    text_node_size[zw]=6;
                            //new_weight=1;
                        }
			//fprintf(stderr,"\ntext_node_size[%d]=%d",zw,text_node_size[zw]);
		  }
		  else{
		      m_node_size[zw]/=node_factor;
		      s_node_size[zw]/=node_factor;
	          }
	       }	 
	       if (m_node_size[zw]>119) m_node_size[zw]=119; //unscaled:to limit within signed char
	       if (s_node_size[zw]>119) s_node_size[zw]=119; //scaled:to limit within signed char

	       //if (m_node_size[zw]<2.5) m_node_size[zw]=2.5; //unscaled:to limit within signed char	       
	       //if (s_node_size[zw]<2.5) s_node_size[zw]=2.5; //scaled:to limit within signed char

               if (m_node_size[zw]<vgax(1)) m_node_size[zw]=vgax(1); //unscaled:to limit within signed char
	       if (s_node_size[zw]<vgax(1)) s_node_size[zw]=vgax(1); //scaled:to limit within signed char
	       
	       /*fprintf(stderr,"\nm_node_size[%d]=%f s_node_size[%d]=%f",
		                         zw,m_node_size[zw],zw,s_node_size[zw]);*/
	   }	 
}

/*** Equalise nodes size/type in component Dec2021, or in whole graph June 2022 ******/
void EC_equalise_component_graph(unsigned int most_recent_node, char components, char blockset){
   unsigned int zw;
   char temp_components;  
   double this_f,av_f;
   
   //for weighted nodes restores the default sizes
   //otherwise this copies the node type, size, text size, to the fragement (ar all nodes)
   
          for (zw=node_no;zw>=1;zw--){
	     if (components=='a'){
	         if (graph_type=='t'){
		    //otherwise default nodes for can be too bof for single or special cases
		    av_f= m_space / (unsigned int)(pow(value_range,(double)lineL));
		 }   
		 else av_f= m_space / node_no;
		 
		 if (graph_type=='f' || jump_layout_only) this_f=(double)m_basin_volume[zw];
		 else if (graph_type=='a') this_f=(double)histnodesize[zw];
		 else if (graph_type=='s' || graph_type=='t') this_f=(double)netnodesize[zw];
		 else if (graph_type=='n'){			   
		     if (network_outputs==1) this_f=(double)m_att_period[zw]; //outputs
		     else this_f=(double)netnodesize[zw];
		 }
		 m_node_size[zw]=c_scale*(float)pow(this_f/av_f,.5);
		 //if (m_node_size[zw]<vgax(2.5)) m_node_size[zw]=vgax(2.5);
		 if (m_node_size[zw]<vgax(1)) m_node_size[zw]=vgax(1);
	         s_node_size[zw]=s_node_size[most_recent_node];

		 text_node_size[zw]=text_node_size[most_recent_node];		 
		 frag_node_types[zw]=frag_node_types[most_recent_node];		 
             }
	     else{
	         if (components!='a' && fragment==1 && get_bit(linknet,zw)==0) continue;
		 
                 if (graph_type=='t'){
		    //otherwise default nodes for can be too bof for single or special cases
		    av_f= m_space / (unsigned int)(pow(value_range,(double)lineL));
		 }
                 else av_f= m_space / node_no;

		 if (graph_type=='f' || jump_layout_only) this_f=(double)m_basin_volume[zw];
		 else if (graph_type=='a') this_f=(double)histnodesize[zw];
		 else if (graph_type=='s' || graph_type=='t') this_f=(double)netnodesize[zw];
		 else if (graph_type=='n'){			   
		     if (network_outputs==1) this_f=(double)m_att_period[zw]; //outputs
		     else this_f=(double)netnodesize[zw];
		 }
		 m_node_size[zw]=c_scale*(float)pow(this_f/av_f,.5);
		 //if (m_node_size[zw]<vgax(2.5)) m_node_size[zw]=vgax(2.5);
		 if (m_node_size[zw]<vgax(1)) m_node_size[zw]=vgax(1);
	         s_node_size[zw]=s_node_size[most_recent_node];
                 if (s_node_size[zw]<vgax(1)) s_node_size[zw]=vgax(1);
		 
		 text_node_size[zw]=text_node_size[most_recent_node];		 
		 frag_node_types[zw]=frag_node_types[most_recent_node];
		 	 
		
	     }
	     //for no_link in a network graph
	     if (still_jump_graph==1); //ignore jump_graph
	     else if (no_links==1) m_node_size[zw]=s_node_size[zw]; //no_links for network-graph only
	  }
	
}


/***************** define node type in fragment Dec2021************************/
void nodes_type_component_graph(char which,unsigned int most_recent_node,char blockset){
   unsigned int zw;
                 /*fprintf(stderr,"\n type: no_links=%d jump_layout_only=%d blockset=%d",
		   no_links,jump_layout_only,blockset);*/
	      
              for (zw=node_no;zw>=1;zw--){
		if (most_recent_node!=-1){ //for all nodes
                   if ((no_links==1 || jump_layout_only==1) && blockset==0){
		       if (most_recent_node==zw){ //act on single node
		         //fprintf(stderr,"\ntype: zw=%d most_recent_node=%d",zw,most_recent_node);
	               }		 
		       else continue;
		    } 
		    else{
		        if (most_recent_node==zw){//include most_recent_node, i.e. selectednode , in fragment
		           //fprintf(stderr,"\nmost_recent_node=%d zw-1=%d",most_recent_node,zw-1);
		        }
		        else if (fragment==1 && get_bit(linknet,zw)==0 /*&& most_recent_node*/) continue;
		    }  
		 }
		 frag_node_types[zw]=which;
		 //fprintf(stderr,"\nzw=%d:which=%d",zw,which);
	      }
	      
}

/**************** save or load  graph layout ************************/
 char save_load_graph_layout(char save_load){
      unsigned char *graph_pos;
      unsigned int thisbyte,filebytes,zw;
      char file_ret,fid,ok=1;

	 if ((graph_pos=(unsigned char*)calloc((node_no+1)*4,
		   sizeof(unsigned char)))==NULL) outof_memory("graph_pos");

	 if (save_load=='s'){ /*save node  positions*/
	       for (zw=1;zw<=node_no;zw++){
		  /*fprintf(stderr,"\n%dx%d ",basin_pos[z][0],basin_pos[z][1]);*/
		  thisbyte=zw*4;                 
		  graph_pos[thisbyte]=(unsigned char)(basin_pos[zw][0] & 0x00ff); 
		  graph_pos[thisbyte+1]=(unsigned char)(basin_pos[zw][0] >> 8);
		  graph_pos[thisbyte+2]=(unsigned char)(basin_pos[zw][1] & 0x00ff); 
		  graph_pos[thisbyte+3]=(unsigned char)(basin_pos[zw][1] >> 8);
	       }

	       file_ret=select_filename("SAVE","GRAPH LAYOUT","*.grh","my_grh");
	       if (file_ret=='q') goto exitFunc;

	       fid=myopen(filename,1,0);
	       if (fid==-1){
		  ok=0;
		  file_error(filename);
		  close(fid);
		  goto exitFunc;
	       }
	       vret=write(fid, graph_pos, (node_no+1)*4*sizeof(unsigned char));
	       close(fid);
	       goto exitFunc;
	 }
	 else if (save_load=='l'){ /*load node positions*/
	       file_ret=select_filename("LOAD","GRAPH LAYOUT","*.grh","my_grh");
	       if (file_ret=='q'){
		    ok=0;
		    goto exitFunc;
	       }
	       fid=myopen(filename,0,0);
	       filebytes= filelength(fid);
	       if (fid==-1 || filebytes!=(node_no+1)*4*sizeof(unsigned char)){
		  ok=0;  
		  if (fid==-1) file_error(filename);
		  else{
		     draw_prompt_box(1);
		     sprintf(textb[1],
		       "can't load: file nodes=%d,  graph nodes=%d, cont-ret:",
			   filebytes/((signed int)(4*sizeof(unsigned char))),
						   node_no+1);
		     outtext(textb[1]);
		     input_string(1,0);
		  }
		  close(fid);
		  goto exitFunc;
	       }
	       vret=read(fid, graph_pos, (node_no+1)*4*sizeof(unsigned char));
	       for (zw=1;zw<=node_no;zw++){
		  thisbyte=zw*4;
		  basin_pos[zw][0]=graph_pos[thisbyte]+
			       (((unsigned int)graph_pos[thisbyte+1])<<8);
		  basin_pos[zw][1]=graph_pos[thisbyte+2]+
			       (((unsigned int)graph_pos[thisbyte+3])<<8);
		  /*fprintf(stderr,"\n%dx%d ",basin_pos[z][0],basin_pos[z][1]);*/
	       }
	       close(fid);      
	 }
       exitFunc:
	 free(graph_pos); 
	 return(ok); 
 }

 /****** intest paths (directed) or small world distances (non-directed) ******/
 /** something wrong here -- excluded for now -- 1 Jan 2010 **/

 void intest_path(char what){
   signed int bytesT,xbox;
   unsigned int count_starts,count_starts_temp,
		  zu,dis,snode,fnode,
		  *start_nodes,*start_nodes_temp,**swdis;
   char *d_levels;
   unsigned long matrix_size,in_paths=0,in_path_tsteps=0,
		 out_paths=0,out_path_tsteps=0;

    bytesT=(signed int)ceil((double)node_no/8);  
    if ((d_levels=(char*)calloc(bytesT,sizeof(char)))
	     ==NULL) outof_memory("d_levels");
    if ((start_nodes=(unsigned int*)calloc(node_no+1,
	     sizeof(unsigned int)))==NULL) outof_memory("start_nodes");
    if ((start_nodes_temp=(unsigned int*)calloc(node_no+1,
	     sizeof(unsigned int)))==NULL) outof_memory("start_nodes_temp");

    if ((swdis=(unsigned int**)calloc(node_no+1,
	     sizeof(unsigned int*)))==NULL) outof_memory("swdis");
    for (zu=1; zu<=node_no; zu++){
       if ((swdis[zu]=(unsigned int*)calloc(node_no+1,
	     sizeof(unsigned int)))==NULL) outof_memory("swdis[]");
    }

    for (snode=1; snode<=node_no; snode++){ /*start node*/
       /*fprintf(stderr,"\n snode=%d",snode);*/
       count_starts=1;
       start_nodes[1]=snode;
       /*count_bits=1;*/

       for (dis=1; dis<=node_no; dis++){ /*final node*/
	      count_starts_temp=0;
	      for (zu=1; zu<=count_starts; zu++){
		 /*fprintf(stderr," %d", start_nodes[zu]);*/ 
		 for (fnode=1; fnode<=node_no; fnode++){ /*final node*/
		   if (what=='p'){ /*directed intest path outputs/inputs*/
		       if (basinjumps[start_nodes[zu]][fnode]>0 && 
				    get_bit(d_levels,fnode)==0){
			   count_starts_temp+=1;
			   start_nodes_temp[count_starts_temp]=fnode;
			   swdis[snode][fnode]=dis;
			   set_bit1(d_levels,fnode);
		       }
		   }
		   if (what=='d'){ /*outputs->*/
		       if ((basinjumps[fnode][start_nodes[zu]]>0 ||
			    basinjumps[start_nodes[zu]][fnode]>0 ||
			    start_nodes[zu]==fnode)
				  && get_bit(d_levels,fnode)==0){
			   count_starts_temp+=1;
			   start_nodes_temp[count_starts_temp]=fnode;
			   swdis[snode][fnode]=dis;
			   set_bit1(d_levels,fnode);
		       }
		   }     
		 }
	      }
	      memmove(start_nodes,start_nodes_temp,
		     (node_no+1)*sizeof(unsigned int));
	      count_starts=count_starts_temp; 
       }

       free(d_levels);
       if ((d_levels=(char*)calloc(node_no,sizeof(char)))
				 ==NULL) outof_memory("d_levels");
    }          

    for (snode=1; snode<=node_no; snode++){ /*start node*/ 
	  /*fprintf(stderr,"\n %2d.",snode-offset);*/        
	  for (fnode=1; fnode<=node_no; fnode++){ /*final node*/
	    if (swdis[snode][fnode]>0){
	       in_paths+=1;
	       in_path_tsteps+=swdis[snode][fnode];
	    }
	    if (swdis[fnode][snode]>0){
	       out_paths+=1;
	       out_path_tsteps+=swdis[fnode][snode];
	    }
	  }
    }
    matrix_size=node_no*node_no;
    if (what=='p'){
       sprintf(textb[1],
    "finite intest paths (%lu/%lu=%.2f) av=%.2f",
	     out_paths,matrix_size,
		  (float)out_paths/matrix_size,(float)out_path_tsteps/in_paths);
    }
    else if (what=='d'){
       sprintf(textb[1],
	  "finite distances (%lu/%lu=%.2f), small world distance (av)=%.2f",
	     out_paths-node_no,matrix_size-node_no,
		  (float)(out_paths-node_no)/(matrix_size-node_no)
			,(float)(out_path_tsteps-node_no)/in_paths);
    }
    xbox=draw_prompt_box(2);
    outtext(textb[1]);
    moveto(xbox,gety+CHeight);
    outtext("cont-ret:");

    input_string(1,0);

    free(d_levels);
    for (zu=1; zu<=node_no; zu++) free(swdis[zu]);
    free(swdis);
 }

 /********** prompts for probabilistic ant in jumpgraph  *******************/
 void prob_ant_prompts(char show_ant, char rand_ant){
   signed int xbox;

	    xbox=draw_prompt_box(3);
	    outtext("probabilistic ant: quit-q speed-</> pause-p");
	    moveto(xbox,gety+CHeight);
	    outtext("rndnode-r redraw-d");
	    moveto(xbox,gety+CHeight);
	    if (show_ant==1) sprintf(textb[1],"%s","ON");
	    else sprintf(textb[1],"%s","OFF");
	    if (rand_ant==1) sprintf(textb[2],"%s","ON");
	    else sprintf(textb[2],"%s","OFF");
	    sprintf(textb[0],
		"showhits/options-h showant(%s)-a rndant(%s)-s",
				   textb[1],textb[2]);
	    outtext(textb[0]);
 }


/********** launch probabilistic ant in jumpgraph  *******************/
void prob_ant(signed int wox, signed int woy,
                    signed int X1,signed int Y1,
		       signed int X2,signed int Y2){

  signed int xbox,current_node,temp_current_node;
  char test,exitwhile=0, show_ant=1, rand_ant=0, enter_switch=0,new_current_set=0;;
  unsigned char tempcolor;
  unsigned int zw,btarget,wcount=0,*prob_target,*target,pick,range;
  signed int target_no=0,new_target;
  float av_hits,angle,x,y,
    oldx,oldy,dx,dy,distance,start_distance,hit_node_size;
  unsigned long zu,speed,max_speed,*hit_count,hit_total=0,s_space;


  if (no_links==1) return;

  /*fprintf(stderr,"\n in ants \n"); //checking exh_pairs are stable 
  for (zw=1;zw<=node_no;zw++){
     memmove(state2,exh_pairs+(zw-1)*bytesL,bytesL);
     fprintf(stderr,"%d->%d ",zw-1,(unsigned int)dec_equiv(state2,L));
  }*/

  s_space=(unsigned long)(m_space-1);
  tempcolor=getcolor();
  speed=(unsigned long)((unsigned short)(-1));
  max_speed=((unsigned long)(-1))/2;;//max loop to slow down
  //fprintf(stderr,"\nspeed=%lu max=%lu\n",speed,max_speed);
  //fprintf(stderr,"Maxlu-1=%lu\n",Maxlu-1);

  //speed=speed*8; //mke the initial speed slow to see ant moving -- then can be increased

 top_start:
   wcount=0;/*reset count*/

   if ((prob_target=(unsigned int *)calloc(node_no+1,
            sizeof(unsigned int)))==NULL) outof_memory("prob_target");
   if ((target=(unsigned int *)calloc(node_no+1,
            sizeof(unsigned int)))==NULL) outof_memory("target");
   /*count hits*/
   if ((hit_count=(unsigned long *)calloc(node_no+1,
            sizeof(unsigned long)))==NULL) outof_memory("(hit_count");
      

   prob_ant_prompts(show_ant,rand_ant);
	 
   hit_total=0;

 start:
   //fprintf(stderr,"\n(rand_ant=%d new_current_set=%d current_node=%d",rand_ant,new_current_set,current_node);
   /*select node at random*/
   if (rand_ant==0){ 
      hit_total=0;
      if (new_current_set==1){ //retain new current_node set in pause 'p'
	  current_node+=1;//+1 because numbers start at 0
          //fprintf(stderr,"\nstart- current_node=%d",current_node);
          new_current_set=0;//reset
      }
      else current_node=rand()%node_no+1; //rand_ant=1 jumps randomly and advances 1 step
   }
   //else if (graph_type=='s' || graph_type=='t') current_node=rand()%node_no+1;
  
   else{
              /*select node at random, biased by nodesize*/  
              range=0;
              pick=rand()%10000+1;
              for (zw=1; zw<=node_no; zw++){
                 if (graph_type=='f') range+=(unsigned int)
                        (10000*((double)m_basin_volume[zw]/s_space));
                 else if (graph_type=='a') range+=(unsigned int)
                        (10000*((double)histnodesize[zw]/s_space));
                 else if (graph_type=='s' || graph_type=='t' || graph_type=='n' ) range+=(unsigned int)
                        (10000*((double)netnodesize[zw]/s_space));

                 if (pick<=range){
                    current_node=zw;
                    break;
                 }      
              }
   }

   x=(float)basin_pos[current_node][0];
   y=(float)basin_pos[current_node][1];
   moveto(x,y);

   while(1){
     wcount+=1;
     if (event_ready() || enter_switch){
        /*if a key is hit, or enter_switch=1  allows option without keyhit*/
        enter_switch=exitwhile=0;
	test=is[0];

	switch(test){
           case 'q':
           /*key 'q' - exit ants*/
           /*clear and redraw graph*/
	   draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	   exitwhile=1;
	   break;
           case '>': /*faster*/
	      speed=speed/2;
              if (speed<=1) speed=1;
	      //fprintf(stderr,"%lu ",speed);
              break; 
           case '<':  /*slower*/
	      speed=speed*2;
              if (speed>=max_speed) speed=max_speed;
	      //fprintf(stderr,"%lu ",speed);
              break; 
           case 'p':
              /*key 'p' - pause until another key press
	      this also allows ant to take single steps*/
	      //while (!event_ready());
	      //break;

              draw_box(-1,Maxx-2-CWidth*30,vgax(2),
		      Maxx-2,vgax(4)+CHeight,1,0);
              moveto(Maxx-2-CWidth*30+3,vgax(3));
              temp_current_node=current_node;              
	      sprintf(textb[0],"node=%d, new:",current_node-1);
              outtext(textb[0]);
              input_string(5,0);
              if (is[0]==13){ //ant continues
                  current_node=temp_current_node-1;
                  //fprintf(stderr,"return=%d",current_node);
              }
              else if (atoi(is)<(signed int)node_no){ //ant starts from new node
		  current_node=atoi(is);
                  //fprintf(stderr,"\ncurrent_node=%d",current_node); 
              }
              erase_box(Maxx-2-CWidth*30,vgax(2),Maxx-2,vgax(4)+CHeight);
              wcount=0;
              exitwhile=3;
              new_current_set=1;
              is[0]=0;
	      break;
           case 'r':
	      /*start at new random node*/
	      wcount=0;
	      hit_total=0;
              //exitwhile=2;
              //if (graph_type=='s' || graph_type=='t') exitwhile=3;
	      exitwhile=3;
	      break;
           case 'd':
	      /*clear and redraw graph*/
	      draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
	      break;
           case 'a':
	      show_ant=abs(show_ant-1);
              prob_ant_prompts(show_ant, rand_ant);
              wcount=0;
	      break;
           case 's':
	      rand_ant=abs(rand_ant-1);
              draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
              hit_total=0;
              exitwhile=3; /*start new run*/
	      break;
           case 'h':
	      /*show hits*/
	         //fprintf(stderr,"\n%c-show hits-3, exitwhile=%d",is[0], exitwhile);
		 //this is a hack because hit_total was cutting out/eratic, but ok for other graph_types
                 if (graph_type=='n' && rand_ant==1){ 
		      hit_total=0;
                      for (zw=node_no;zw>=1;zw--){
			hit_total+=hit_count[zw];
		      }
		      //fprintf(stderr,"\nhit_total recalculated=%lu",hit_total);
		 }
		 
	         draw_box(-1,X1,Y1,X2,Y2,1,0);/*clear box*/
                 av_hits=(float)hit_total/node_no;
                 for (zw=node_no;zw>=1;zw--){
                    moveto(basin_pos[zw][0],basin_pos[zw][1]);            
	            hit_node_size=c_scale*
                        (float)pow((double)hit_count[zw]/av_hits,.5);
                    jump_graph_vertex(zw,hit_node_size,
                        basin_color[zw],X1,Y1,X2,Y2);          
                 }
	        start_hit_prompts:
                 xbox=draw_prompt_box(3);
		 if (rand_ant==1) sprintf(textb[2],"%s","ON");
	         else sprintf(textb[2],"%s","OFF");
                 if (graph_type=='n' || graph_type=='s' || graph_type=='t'){ 
                    outtext("showing % hits on each node");
                    if (target_no==0){ 
                       sprintf(textb[0],
                          " - no targets, ant stuck at node %d",current_node-1);
                       outtext(textb[0]);
                    }
                 }
                 else { 
                    outtext("showing % hits on each basin");
                    if (target_no==0){ 
                       sprintf(textb[0],
                          " - no targets, ant stuck at basin %d",current_node);
                       outtext(textb[0]);
                    }
                 }
                 			 
                 moveto(xbox,gety+CHeight);
                 sprintf(textb[0],"total hits so far=%lu",hit_total);
                 outtext(textb[0]);
		 
                 sprintf(textb[0]," rndnode-r rndant(%s)-s",textb[2]);
		 outtext(textb[0]);
		 
                 moveto(xbox,gety+CHeight);
		 outtext("show % frequency-n noNodes-N quit-q cont-ret:");
                 input_string(1,0);

		 if (is[0]=='s'){ //sets a random ant
		    rand_ant=abs(rand_ant-1);
                    hit_total=0;
                    exitwhile=3; /*start new run*/
		 }
		 else if (is[0]=='r'){/*start at new random node*/
		    wcount=0;
		    hit_total=0;
                    //exitwhile=2;
		    //if (graph_type=='s' || graph_type=='t') exitwhile=3;
		    exitwhile=3;
		 }
		 
                 else if (is[0]=='q' || target_no==0){
                    /*clear and redraw graph*/
		    draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);            
	            exitwhile=1;
	            break;
                 }
                 
		 
                 if (is[0]=='n' || is[0]=='N'){
		   signed int wbox;
                    draw_box(-1,X1,Y1,X2,Y2,1,0);/*clear box*/
                    for (zw=node_no;zw>=1;zw--){
                       if (is[0]=='n'){
                          moveto(basin_pos[zw][0],basin_pos[zw][1]);
	                  hit_node_size=c_scale*
                              (float)pow((double)hit_count[zw]/av_hits,.5);
                         jump_graph_vertex(zw,hit_node_size,
                             basin_color[zw],X1,Y1,X2,Y2);
                       }
                       moveto(basin_pos[zw][0],basin_pos[zw][1]);
               
                       if (hit_count[zw]==0){ 
                          sprintf(textb[0],"0");
                          wbox=CWidth+CWidth/3;
                       } 
                       else{
                          sprintf(textb[0],"%.1f",
                            100*(float)hit_count[zw]/hit_total);
                          wbox=textwidth(textb[0])-CWidth/3; 
                       }
                       moverel(CWidth/2,0); 
                       setfillstyle(SOLID_FILL,black);
                       bar3d(getx-CWidth/3,gety,
                         getx-CWidth/3+wbox,gety+CHeight,0,0);
                       outtext(textb[0]);                    
                    }
                    goto start_hit_prompts;
                 }              
                 draw_box(-1,X1,Y1,X2,Y2,1,0);/*clear box*/
                 if (hit_total==Maxlu-1) exitwhile=3; /*restart*/
                 else{             
		    draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
                    /*restore prompts*/
                    prob_ant_prompts(show_ant, rand_ant);
                 }
                 if (hit_total==Maxlu-1){
		    hit_total=0; /*in case max sample was reached*/
		 }   
	         break;
	}//switch(test){
	
        if (exitwhile==1) break;
        if (exitwhile==2) goto start;
        if (exitwhile==3){
	  //fprintf(stderr,"exitwhile=%d",exitwhile);
           free(prob_target);
           free(target);
           free(hit_count);
           goto top_start;
	}
     }  /*if (event_ready() || enter_switch){    if a key is hit.....*/

     //input_string(1,0); /*to move ant with return key*/
     //if (is[0]=='q') return;

     if (wcount==1){

       //fprintf(stderr,"\nwcount=%d",wcount);
       if (graph_type=='s' || graph_type=='t'){
	       //there is always just one target with b_J, but with basinjumps could be more or none
	   target_no=0;
	   //fprintf(stderr,"\ncurrent_node=%d",current_node);
           for (btarget=1;btarget<=node_no;btarget++){ //this alternative works
	          //if (basinjumps[current_node][btarget]>0){
	          if (b_j[current_node][btarget]>0){
		  target_no++;
                  new_target=btarget;
		  //fprintf(stderr,"\ncurrent_node=%d>%d",current_node,new_target);
                  break;
              }	      
	   }
        }
       
       else{ //there may be 0 or nore targets --- pick one*/
           target_no=0; 
           /*calc prob in possible directions*/ 
           for (btarget=1;btarget<=node_no;btarget++){
	     //if (basinjumps[current_node][btarget]>0){
	     if (b_j[current_node][btarget]>0){
	         target_no++;
                 target[target_no]=btarget;
                 prob_target[target_no]=(unsigned int) (10000*
                   ( (double)b_j[current_node][btarget]/
		                 (m_att_period[current_node]*m_size) ));
              }           
           }
           /*choose direction*/
           if (target_no>0){ /*in case no targets}*/
              range=0;
              pick=rand()%10000+1;

              for (zw=1; zw<=target_no; zw++){
                 range+=prob_target[zw];
                 if (pick<=range){
                    new_target=target[zw];
                    break;
                 } 
              }     
           }//if (target_no>0){ /*in case no targets}*/

           if (target_no==0){ //if no exit contine with hits	     
	      if (rand_ant==0){		 
                 xbox=draw_prompt_box(3);
                 if (graph_type=='n' || graph_type=='s' || graph_type=='t') sprintf(textb[0],
						       "no exit from node %d",current_node-1);
		 else sprintf(textb[0],"no exit from node %d",current_node);	 
                 outtext(textb[0]);
		 moveto(xbox,gety+CHeight);
		 outtext("showhits/options-h, pick another random start node-ret");
		 moveto(xbox,gety+CHeight);
		 //outtext("restart-ants-a quit-ants-q:");
		 outtext("quit-ants-q:");
		 input_string(1,0);
		 
		 if (is[0]=='h'){ //show hits
		   exitwhile=0;
		   //fprintf(stderr,"\n%c-show hits-1, exitwhile=%d",is[0], exitwhile);
		   enter_switch=1;
                   continue;
		 }
		 
		 else if (is[0]=='q'){
		    draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
		    is[0]=0;
		    break;
		 }
	         
		 else{ //pick another random start node-ret
		    draw_jump_graph(1,wox,woy,X1,Y1,X2,Y2);
		    wcount=0;
		    hit_total=0;
		    is[0]=0;
                    goto start;
                 }
		 
              }
              else{ //pick another start node
		 wcount=0;
		 hit_total=0;
                 goto start;
	      }
           }       
        }//else{ //there may be 0 or nore targets --- pick one

        /*suppress graphics to speed up sample*/
        if (show_ant==0){
	   if (hit_total<Maxlu){
              hit_count[new_target]++;
              hit_total++;
              //fprintf(stderr," %lu",hit_total);
           }
           wcount=0;/*reset count*/
           if (rand_ant==0) current_node=new_target; 
           else{
              /*select node at random*/ 
	      /*current_node=rand()%node_no+1;*/
              /*select node at random, biased by nodesize*/  
              range=0;
              pick=rand()%10000+1;
              for (zw=1; zw<=node_no; zw++){
                 if (graph_type=='f') range+=(unsigned int)
                        (10000*((double)m_basin_volume[zw]/s_space));
                 else if (graph_type=='a') range+=(unsigned int)
                        (10000*((double)histnodesize[zw]/s_space));
                 else if (graph_type=='n' || graph_type=='s' || graph_type=='t'
			  ) range+=(unsigned int)
                        (10000*((double)netnodesize[zw]/s_space)); 
                 if (pick<=range){
                    current_node=zw;
                    break;
                 }      
              }       
           }
           if (hit_total==Maxlu-1){ /*in case max sample was reached*/
	       enter_switch=1;               
               is[0]='h';
           } 
           continue;
        }//if (show_ant==0){
	
        /*set heading*/
        compute_link_angle(basin_pos[current_node][0],
                           basin_pos[current_node][1],
                           basin_pos[new_target][0],
                           basin_pos[new_target][1]);
                    
        angle=linkangle;
       
        start_distance=pow((
           pow(abs(basin_pos[current_node][0]-basin_pos[new_target][0]),2)+
           pow(abs(basin_pos[current_node][1]-basin_pos[new_target][1]),2)),.5);

        //fprintf(stderr,"\nend wcount=%d",wcount);
     }//if (wcount==1){
     
     if (wcount>1){
        //fprintf(stderr,"\nwcount>1=%d",wcount);

        /*delete ant*/
        thickline(0,(signed int)oldx,(signed int)oldy,
                   (signed int)(oldx+dx*vgax(8)),
                   (signed int)(oldy+dy*vgay(8)),
                                        white,vgax(2),0);
     }
     oldx=x;
     oldy=y;
  
     /*ant moves forward (acc to where it points)
     by the equivalent of one pixel, by step dx,dy*/		
     dx=cos(angle);
     dy=-sin(angle);
                
     distance=pow((
             pow(abs(basin_pos[current_node][0]-(signed int)x),2)+
             pow(abs(basin_pos[current_node][1]-(signed int)y),2)),.5);
     /*draw ant as thick red? line*/
     thickline(0,(signed int)x,(signed int)y,
               (signed int)(x+dx*vgax(8)),(signed int)y+dy*vgay(8),
			                       lightred,vgax(2),0);
     x+=dx;
     y+=dy;
     /*if ant reaches target, set new origin and target*/	 
     if (abs((signed int)distance)>=
                    abs((signed int)start_distance)-vgax(8)  ||
                  current_node==new_target){
        if (hit_total<Maxlu){
           hit_count[new_target]++;
           hit_total++;
           //fprintf(stderr," %lu",hit_total);//monitor hit_total
        }
        wcount=0;/*reset count*/
        /*redraw target node*/
        moveto(basin_pos[new_target][0],
                           basin_pos[new_target][1]);
        jump_graph_vertex(new_target,m_node_size[new_target],
                      basin_color[new_target],X1,Y1,X2,Y2);
        
        if (rand_ant==0) current_node=new_target; 
        else{
              /*select node at random*/ 
	      /*current_node=rand()%node_no+1;*/
              /*select node at random, biased by nodesize*/  
              range=0;
              pick=rand()%10000+1;
              for (zw=1; zw<=node_no; zw++){
                 if (graph_type=='f') range+=(unsigned int)
                        (10000*((double)m_basin_volume[zw]/s_space));
                 else if (graph_type=='a') range+=(unsigned int)
                        (10000*((double)histnodesize[zw]/s_space));
                 else if (graph_type=='n' || graph_type=='s' || graph_type=='t') range+=(unsigned int)
                        (10000*((double)netnodesize[zw]/s_space)); 
                 if (pick<=range){
                    current_node=zw;
                    break;
                 }      
              }
        }
        x=(float)basin_pos[current_node][0];
        y=(float)basin_pos[current_node][1];
     }
     /*slow down*/
     //fprintf(stderr,"%lu ",speed);
     for (zu=0;zu<=speed;zu++);
   }//while

   free(prob_target);
   free(target);
   free(hit_count);
   setcolor(tempcolor);
}

/********** show jump_table as numbers or fractions *******************/
void show_table(char type, signed int X1, signed int Y1,
		           signed int X2, signed int Y2){

  unsigned int btarget,btype;
  signed int xleft,startV=1,startH=1;
  unsigned char tempcolor;
  char save_list_con_elements=0,/* file for neato */
       xterm_print=0; /*print to xterm*/
  signed int count_list,xbox,maxno,minno;
  char colwidth,this_colwidth;//to set wariable width for 't' (numbers), not for 'T' (fractions)

       if (no_links==1) return;
       //change text size for prompts, may be necessary, restore at end
       this_text_size=current_text_size;
       # if __UNIX__
            free_fonts();
            setup_fonts(start_pointsize);//to preserve normal prompt font
       # endif
       erase_prompt_box(4);//in case its still there
       
       /*to save list of connected elements, 2 columns*/
       //save_list_con_elements=1;
       if (save_list_con_elements==1){ //name the file
          signed int fid;
          char file_ret;           
 	       file_ret=select_filename("SAVE","DATA","*.dat","my_data");
	       if (file_ret!='q'){
	          memmove(filename_data,filename,13);
                  fid=myopen(filename_data,1,1);
                  if (fid==-1) file_error(filename_data);
	          close(fid);
               }
               if (file_ret=='q' || fid==-1) save_list_con_elements=0;
       }

       tempcolor=getcolor();
       //initial column width -- cn be changed with on-the-fly e and c
       if (graph_type=='s' || graph_type=='t') colwidth=0;//0 confine matrix in a fixed size square
       else if (type=='t') colwidth=4;	   
       else if (type=='T') colwidth=6;

        if (graph_type=='n' || graph_type=='s' || graph_type=='t'){
	       maxno=node_no-1;
	       minno=0;
       }	       
       else{	       
	 maxno=node_no;
	 minno=1;
       }
	
     start_prompt:
       if (graph_type=='s' || graph_type=='t') this_colwidth=colwidth;
       else this_colwidth=colwidth-2;
	  
       restore_def_font();
       setcolor(white);
       xbox=draw_prompt_box(2);
#      if __UNIX__
       sprintf(textb[0],"adjacency-matrix: exit-ret xterm-x  exp/cntr(%d)-e/c",this_colwidth);
         outtext(textb[0]);
	 moveto(xbox,gety+CHeight);
	 sprintf(textb[0],"jump(%d-%d)-j down/up/right/left-d/u/r/l origin-o",minno,maxno);
	  outtext(textb[0]);
#      elif __WATCOM__
         sprintf(textb[0],"adjacency-matrix: exit-ret  exp/cntr(%d)-e/c",this_colwidth);
         outtext(textb[0]);
	 moveto(xbox,gety+CHeight);
	 sprintf(textb[0],"jump(%d-%d)-j down/up/right/left-d/u/r/l origin-o",minno,maxno);
	 outtext(textb[0]);
#      endif

         if (node_no>=19){
#     if __UNIX__
            XSetFont(D,Gc,smallnonpropfont->fid);
#     elif __WATCOM__
            _setcharsize((signed int)((ceil)((float)(.6*ty1))),
	              (signed int)((ceil)((float)(.6*tx1))));
#     endif
	    CHeight*=.6;
	    CWidth*=.6;
         }
         else if (node_no>=14){
#     if __UNIX__
            XSetFont(D,Gc,mediumnonpropfont->fid);
#     elif __WATCOM__
            _setcharsize((signed int)((ceil)((float)(.8*ty1))),
	              (signed int)((ceil)((float)(.8*tx1))));
#     endif
	    CHeight*=.8;
	    CWidth*=.8;
         }
         else{
#     if __UNIX__ 
            XSetFont(D,Gc,nonpropfont->fid);
#     endif
	 }

     start_table:
         
      draw_box(-1,X1,Y1,X2,Y2,1,0);/*clear box*/   
      setviewport(X1,Y1,X2,Y2,1); /*clip in rectangle*/
      setcolor(lightred);
      moveto(X1+CWidth/2,Y1+CHeight/2);
      
      xleft=getx;

      if (graph_type=='s'|| graph_type=='t' ){ //adjacency matrix shown as pixels or blocks, 0-0 is top left
	      moveto(X1,Y1);
              xleft=getx;
	      
	      if (colwidth==0){
		float side;		
		 //side=Maxy/2;
		 side=(Y2-Y1)/2;
		 if (side>node_no) side=node_no;
		 fillcolor=yellow;
		 setcolor(lightred);
		 rectangle(xleft,gety,xleft+side,gety+side);
		 setcolor(yellow); 
                 for (btype=startV;btype<=node_no;btype++){
		    for (btarget=startH;btarget<=node_no;btarget++){
		       moveto(X1+((float)btarget/node_no)*side,Y1+((float)btype/node_no)*side);
		       if (b_j[btype][btarget]==1) putpixel(getx,gety,fillcolor);
		      
		    }
	         }
	      }
	      else{
		 fillcolor=yellow;
		 setcolor(yellow);
                 for (btype=startV;btype<=node_no;btype++){		
		    if (btype>=startV+1) moveto(xleft,gety+colwidth);
		    for (btarget=startH;btarget<=node_no;btarget++){
		       moveto(xleft+colwidth*(btarget-startH),gety);
		       if (b_j[btype][btarget]==1){
		          if (colwidth==1) putpixel(getx,gety,fillcolor);
		          else bar(getx,gety,getx+colwidth,gety+colwidth);
		       }   
		    }
	         }
	         setcolor(lightred);  
	         line(xleft,Y1+colwidth*node_no,xleft+colwidth*node_no,Y1+colwidth*node_no);
	         line(xleft+colwidth*node_no,Y1,xleft+colwidth*node_no,Y1+colwidth*node_no);
              }		 
       }    

       /*print numbers*/
       else{
         if (type=='t'){
	    if (xterm_print==1) fprintf(stderr,"\n\n%*s",colwidth+1," ");//was 4
            for (btype=startH;btype<=node_no+1;btype++){
	       moveto(xleft+CWidth*colwidth*(btype-startH+1),gety);
               if (btype<=node_no){
		  if (graph_type=='n' || graph_type=='s') sprintf(textb[0],"%*d",colwidth,btype-1);
		  else sprintf(textb[0],"%*d",colwidth,btype);
                  outtext(textb[0]);
                  if (xterm_print==1) fprintf(stderr,"%s",textb[0]);
               }
               else{
                  if (graph_type=='n' || graph_type=='s'){
                     sprintf(textb[0],"    out  k");
                     sprintf(textb[1],"    out  k");
                  }
                  else{ 
                     sprintf(textb[0],"      P     J      Volume       Self");
                     sprintf(textb[1],"      P       J          Volume        Self");
                  }
                  outtext(textb[0]);
                  if (xterm_print==1)  fprintf(stderr,"%s",textb[1]);
               }	       
               
            }            
            for (btype=startV;btype<=node_no;btype++){
               if (graph_type=='n' || graph_type=='s') sprintf(textb[0],"%*d:",colwidth,btype-1);
               else sprintf(textb[0],"%*d:",colwidth,btype);
               
	       moveto(xleft,gety+CHeight);
               outtext(textb[0]);
               if (xterm_print==1) fprintf(stderr,"\n%s",textb[0]);
               for (btarget=startH;btarget<=node_no+1;btarget++){
                 moveto(xleft+CWidth*colwidth*(btarget-startH+1),gety);
		 if (btarget<=node_no){
		       setcolor(white);
                       if (b_j[btype][btarget]==0){
			   sprintf(textb[0],"%*s",colwidth,".");
			    outtext(textb[0]);
			    if (xterm_print==1) fprintf(stderr,"%s",textb[0]);
                       }
                       else{
                          if (save_list_con_elements==1){
                             fprintf(stderr,"%d %d\n",btype,btarget);
                             sprintf(textb[0],"%d %d\n",btype,btarget);
                             save_data(textb[0]);
                             count_list+=1;
                          }
                          //sprintf(textb[0],"%4lu",b_j[btype][btarget]);
			  sprintf(textb[0],"%*d",colwidth,b_j[btype][btarget]);
			  
                          outtext(textb[0]);
                          if (xterm_print==1) fprintf(stderr,"%s",textb[0]);
                       }
		       //moveto(xleft+CWidth*colwidth*(btarget-startH+1),gety);
                       //setcolor(lightred);  
		 }
                 else{
		     setcolor(lightred);  
                     if (graph_type=='n' || graph_type=='s'){
		       sprintf(textb[0],"    %d    %d",
			       m_att_period[btype],netnodesize[btype]);
                        outtext(textb[0]);
                        if (xterm_print==1) fprintf(stderr,"%s",textb[0]);
                     }
                     else{
                        sprintf(textb[0],"%7d",m_att_period[btype]);
                        outtext(textb[0]);
                        if (xterm_print==1) fprintf(stderr,"%s",textb[0]);
                        sprintf(textb[0],"%9d",m_att_period[btype]*m_size);
                        outtext(textb[0]);
                        if (xterm_print==1) fprintf(stderr,"%s",textb[0]);
                        if (graph_type=='f') sprintf(textb[0],"%10lu=%.2f%%",
			       m_basin_volume[btype],
                                    (double)(m_basin_volume[btype]*100)/m_space);
                        else if (graph_type=='a') sprintf(textb[0],"%10lu=%.2f%%",
				histnodesize[btype],(double)(histnodesize[btype]*100)/m_space);
                        outtext(textb[0]);
                        if (xterm_print==1) fprintf(stderr,"%s",textb[0]);

                        sprintf(textb[0],"%10.2f%%",
				(double)(b_j[btype][btype]*100)/(m_att_period[btype]*m_size));
                        outtext("         ");
                        outtext(textb[0]);
                        if (xterm_print==1) fprintf(stderr,"%s",textb[0]);
                     }
                  }
	       }
            }
         }
         if (save_list_con_elements==1)
                     fprintf(stderr,"total links=%d\n",count_list);
         /*print fractions*/
         if (type=='T'){
	    if (xterm_print==1) fprintf(stderr,"\n\n%*s",colwidth+1," ");//was 4
            for (btype=startH;btype<=node_no+1;btype++){
               moveto(xleft+CWidth*colwidth*(btype-startH+1),gety);
               if (btype<=node_no){
		   if (graph_type=='n' || graph_type=='s') sprintf(textb[0],"%*d",colwidth,btype-1);
		   else sprintf(textb[0],"%*d",colwidth,btype);
                   outtext(textb[0]);
                   if (xterm_print==1) fprintf(stderr,"%s",textb[0]);
               }
               else{
                  if (graph_type=='n' || graph_type=='s'){
                     sprintf(textb[0],"    out  k");
                     sprintf(textb[1],"    out  k");
                  }
                  else{ 
                     sprintf(textb[0],"      P     J      Volume      Self");
                     sprintf(textb[1],"      P       J          Volume       Self");
                  }
                  outtext(textb[0]);
                  if (xterm_print==1) fprintf(stderr,"%s",textb[1]);
               }               
            }
            for (btype=startV;btype<=node_no;btype++){
	       if (graph_type=='n' || graph_type=='s') sprintf(textb[0],"%*d:",colwidth,btype-1);
	       else sprintf(textb[0],"%*d:",colwidth,btype);
               moveto(xleft,gety+CHeight);
               outtext(textb[0]);
               if (xterm_print==1) fprintf(stderr,"\n%s",textb[0]);
               for (btarget=startH;btarget<=node_no+1;btarget++){
                  moveto(xleft+CWidth*colwidth*(btarget-startH+1),gety);
		  if (btarget<=node_no){
                    setcolor(white); 
		    if (b_j[btype][btarget]==0){
		       //outtext("    .");
		       sprintf(textb[0],"%*s",colwidth,".");
		       outtext(textb[0]);
                       if (xterm_print==1) fprintf(stderr,"%s",textb[0]);
                    }                    
		    
                    else if (b_j[btype][btarget]==
			     m_att_period[btype]*m_size){
		      //outtext("    1");
		       sprintf(textb[0],"%*s",colwidth,"1");
		       outtext(textb[0]);
                       //if (xterm_print==1) fprintf(stderr,"    1");
		       if (xterm_print==1) fprintf(stderr,"%s",textb[0]);
                    }
		    else{
                       sprintf(textb[0],"%*.*f",
			       colwidth,colwidth-colwidth/2,(float)b_j[btype][btarget]/
                                     (m_att_period[btype]*m_size));
                       //sprintf(textb[1]," %s",textb[0]+1);
		       //sprintf(textb[1],"%*s",colwidth,textb[0]+2);//omit "0."
		       sprintf(textb[1],"%*s",colwidth,textb[0]+colwidth-(colwidth-colwidth/2));//omit "0."
                       outtext(textb[1]);
                       if (xterm_print==1) fprintf(stderr,"%s",textb[1]);
		    }
		    
                    setcolor(lightred);
                  }
                  else{
                     if (graph_type=='n' || graph_type=='s'){
                        sprintf(textb[0],"    %d    %d",
			       m_att_period[btype],netnodesize[btype]);
                        outtext(textb[0]);
                        if (xterm_print==1) fprintf(stderr,"%s",textb[0]);
                     }
                     else{
                        sprintf(textb[0],"%7d",m_att_period[btype]);
                        outtext(textb[0]);
                        if (xterm_print==1) fprintf(stderr,"%s",textb[0]);
                        sprintf(textb[0],"%9d",m_att_period[btype]*m_size);
                        outtext(textb[0]);
                        if (xterm_print==1) fprintf(stderr,"%s",textb[0]);
                        if (graph_type=='f') sprintf(textb[0],"%10lu=%.2f%%",
			     m_basin_volume[btype],(double)(m_basin_volume[btype]*100)/m_space);
                        else if (graph_type=='a') sprintf(textb[0],"%10lu=%.2f%%",
				 histnodesize[btype],(double)(histnodesize[btype]*100)/m_space);
                        outtext(textb[0]);
                        if (xterm_print==1) fprintf(stderr,"%s",textb[0]);

                        sprintf(textb[0],"%10.2f%%",
				(double)(b_j[btype][btype]*100)/(m_att_period[btype]*m_size));
                        outtext("         ");
                        outtext(textb[0]);
                        if (xterm_print==1) fprintf(stderr,"%s",textb[0]);     
                     }
                  }
	       }
            }
         }
       }
      
       xterm_print=0;      
       while(event_ready()==0);               
       switch(is[0]){
              case 'x':
                xterm_print=1;
		if (graph_type=='s' || graph_type=='t'){
                   unsigned int zu,zz;
                    for (zu=1;zu<=node_no;zu++){
		        fprintf(stderr,"\n%d: ",zu-1);
		           for (zz=1;zz<=node_no;zz++){
			     if (b_j[zu][zz]==1) fprintf(stderr,"%d ",zz-1); //original network
			     //amended network, if links cut,added etc
			     //if (basinjumps[zu][zz]==1) fprintf(stderr,"%d ",zz-1); 
		        }	 
		    }
		}  
                goto start_table;        
              case 'o'://restore the origin
		 startV=1;
                 startH=1;
                 goto start_table;
	      case 'j':
                 setcolor(white);
                 restore_def_font();
                 setviewport(0,0,Maxx,Maxy,0);
                 draw_prompt_box(1);                 
                 outtext("jump: row:");
                 input_string(5,0);
                 if (is[0]!=13 && atoi(is)>=1 && atoi(is)<=node_no)
                                 startV=atoi(is);
                 outtext("  column:");         
                 input_string(5,0);
                 if (is[0]!=13 && atoi(is)>=1 && atoi(is)<=node_no)
                                 startH=atoi(is);  
                 goto start_prompt;
	      case 'e':
                 colwidth+=1;
		 if (graph_type=='s' || graph_type=='t'){
		   if (colwidth>=30) colwidth=30;
		 }  
		 else if (type=='t' && colwidth>=11) colwidth=11; //4+7
                 else if (type=='T' && colwidth>=14) colwidth=13; //6+7
                 goto start_prompt;
	      case 'c': 
                 colwidth-=1;
		 if (graph_type=='s' || graph_type=='t'){
		   if (colwidth<=0) colwidth=0;
		 }  
                 else if (type=='t' && colwidth<=2) colwidth=2;
		 else if (type=='T' && colwidth<=4) colwidth=4;
                 goto start_prompt;
	      case 'd': 
                 startV+=1;
                 if (startV>node_no) startV=node_no;
                 goto start_table; 
	      case 'u':
                 startV-=1;
                 if (startV<=1) startV=1;
                 goto start_table; 
	      case 'r': 
                 startH+=1;
                 if (startH>node_no) startH=node_no;
                 goto start_table; 
	       case 'l':
                   startH-=1;
                   if (startH<=1) startH=1;
                   goto start_table; 
            
       }
       //restore previous textsize changed by prompt		    
       current_text_size=this_text_size;
       # if __UNIX__
            free_fonts();
            setup_fonts(current_text_size);
       # endif
			  
       setcolor(tempcolor);
       restore_def_font();
       setviewport(0,0,Maxx,Maxy,0);
         
}

/********** draw links and ring of vertices, Aug 2000 *******************/
void draw_jump_graph(unsigned int most_recent_node,signed int wox, signed int woy,
                         signed int X1,signed int Y1,
			  signed int X2,signed int Y2){

  unsigned int zw, btarget;
  signed int outerx,outery;
  unsigned char tempcolor,thiscolor,startcolor;
  double thisthick,maxthick;
  float self_length,this_node_size;

  signed int temp_pointsize,temp_text_size;
  signed int thisnode;
  
     //fprintf(stderr,"\ndnet\n");
     //note : no 1d or 2d patterns or hex for graph_type=='n', dec and none ok
      
     draw_box(-1,X1,Y1,X2,Y2,1,0);/*clear box*/
     setviewport(X1,Y1,X2,Y2,1); /*clip in rectangle*/        
     tempcolor=getcolor();

     if (bground=='w') startcolor=red;
     else startcolor=blue;
     thiscolor=startcolor;

     for (zw=node_no;zw>=1;zw--){
       //fprintf(stderr,"\n%d:x-y=%d-%d",zw,basin_pos[zw][0],basin_pos[zw][1]);
       
        //draw/move/manipulate the network with s,e,i,o + linksteps
        //or isolate the component or fragment
       
	//to draw just the component (with "j"), within it single works, and  e,i,o + linksteps
        if (just_component==1 && fragment==1
	    && get_bit(component_linknet,zw)==0  && most_recent_node!=zw) continue;//component only

	/*to draw just the fragment (or block) with "J",
	within it a fragment single "s" works, and  e,i,o + linksteps changes the fragement.
	for a block, single retains retains isolation but deactivates the block, 
	e,i,o deactivates the block and show the whole network*/
	else if (just_fragment==1 && fragment==1
	    && get_bit(component_linknet,zw)==0 && most_recent_node!=zw) continue;//frag only
           	
        /*change color for each new attractor cycling through 6 colors*/
        if (thiscolor==lightred) thiscolor=lightcyan;
	 else if (thiscolor==lightcyan) thiscolor=green;
         else if (thiscolor==green){
            if (bground=='w') thiscolor=magenta;//was lightmagenta
            else thiscolor=lightmagenta;
         } 
	 else if (thiscolor==magenta && bground=='w') thiscolor=yellow;//was lightmagenta
         else if (thiscolor==lightmagenta && bground=='b') thiscolor=yellow;//was lightmagenta
         else if (thiscolor==yellow) thiscolor=startcolor;
         else if (thiscolor==startcolor) thiscolor=lightred;
        setcolor(thiscolor);
        basin_color[zw]=thiscolor;
 
	if (no_links==1) goto skip;

	if (scale_m_nodes==1)
             this_node_size=m_node_size[zw];//scale discs for in-or-out  
        else this_node_size=s_node_size[zw];//same-size discs
        maxthick=this_node_size*.8; //limit thickness, proportional to node size (variable if scale_m_nodes==1)
	
        //establish selflink length
	if (graph_type=='s' || graph_type=='t' || graph_type=='n'){ //for nodes as discs, scaled and normal	  
	  if  ((in_manipulate==0 && show_numbers==0) || (in_manipulate==1 && frag_node_types[zw]==0))
	                                                                      self_length=this_node_size*2;
	  else self_length=vgax(20);
	}	
        else self_length=this_node_size*2;  //for other graph types
	
        for (btarget=node_no;btarget>=1;btarget--){
	   /*if (zw!=btarget && basinjumps[zw][btarget]>0){
	      fprintf(stderr,"\nzw=%d btarget=%d suppress_u_links=%d u_threshold=%d outside_inputs[btarget]=%d outside_inputs[zw]=%d",
		  zw,btarget,suppress_u_links,u_threshold,outside_inputs[btarget],outside_inputs[zw]);
	   }*/  
	   /* draw_jump_lines */
	   if (just_component==1 && fragment==1
	       && get_bit(component_linknet,zw)==0 && most_recent_node!=zw) continue;//component only
           else if (just_fragment==1 && fragment==1
	       && get_bit(component_linknet,zw)==0 && most_recent_node!=zw) continue;//frag only

	   //fprintf(stderr,"\nbasinjumps[%d][%d]=%d",zw,btarget,basinjumps[zw][btarget]);
	   
           if (basinjumps[zw][btarget]>0){             
	     if (suppress_u_links==1 && zw!=btarget &&
		 (outside_inputs[btarget]<=u_threshold ||
		       outside_inputs[zw]<=u_threshold)) continue;
	     
              //thickness depends on node inputs (k for 'n', predecessors for 's ')
	      if (graph_type=='s' || graph_type=='t') thisthick=maxthick/2;
	      else if (graph_type=='n') thisthick=maxthick/3;
              else thisthick=//thickness depends on propotion of outputs
		     (double)maxthick*(double)basinjumps[zw][btarget]/(m_att_period[zw]*m_size);
	      //jump probability = link actual jumps / total of possible jumps
	      //total of possible jumps = attroacto period *length of state (in bits or values)

              if (zw==btarget){
                 /*jumping to itself, same basin*/
		 compute_link_angle(wox,woy,basin_pos[zw][0],basin_pos[zw][1]);
                 /*find outer positions*/
		 
                 outerx=basin_pos[zw][0]+cos(linkangle)*self_length;
                 outery=basin_pos[zw][1]-sin(linkangle)*self_length;
                 if (scale_links==0) thisthick=maxthick=1;
                 thickline(1,basin_pos[zw][0],basin_pos[zw][1],outerx,outery,
		                thiscolor,thisthick,maxthick);
		 
              }
	      else{
                /*jumping to another basin*/
                if (scale_links==0) thisthick=maxthick=1;
                thickline(0,basin_pos[zw][0],basin_pos[zw][1],
		     basin_pos[btarget][0],basin_pos[btarget][1],
                                        thiscolor,thisthick,maxthick);

		//fprintf(stderr,"\n(%d:%dx%d)->(%d:%dx%d)",zw,basin_pos[zw][0],basin_pos[zw][1],
		//	btarget,basin_pos[btarget][0],basin_pos[btarget][1]);
              }  
          }	   
        }
        skip:;
     }//end loop for (zw=node_no;zw>=1;zw--){

     setcolor(white);
     //if (no_links==1) show_numbers=0;//limit to disks only: changed for toggle disks/numbers only

     /*draw vertices, disk or points*/
       
     if (in_manipulate==0 && moving_with_mouse==0 && fragment==0
	   && (show_numbers==1 || show_numbers==2) &&
	        (label_pointsize!=start_pointsize || label_pointsize!=current_text_size)){
       
           /*fprintf(stderr,"\n changing the initial label_pointsize=%d current_text_size=%d",
	                            label_pointsize,current_text_size);*/
	   # if __UNIX__
	      free_fonts(); 
              setup_fonts(label_pointsize);//resize fonts
           # endif
	   current_text_size=label_pointsize;
	   if (graph_postscript==1){ 
	        //resetfont_ps("Times-Roman",label_pointsize);//in case fontsize was changed
	        resetfont_ps("Times-Bold",label_pointsize);//in case fontsize was changed
	        psize_ps=label_pointsize;//for size of blankout rectangles
           }
     }
     
     //temp_text_size=text_node_size[node_no];
     //if (temp_text_size==0) temp_text_size=start_pointsize;
     temp_text_size=start_pointsize;

     /* fprintf(stderr,"\ntemp_text_size=%d\n",temp_text_size);
     for (zw=node_no;zw>=1;zw--){
        fprintf(stderr,"%d ",text_node_size[zw]);
     }*/
     
     for (zw=node_no;zw>=1;zw--){
      
        if (just_component==1 && fragment==1
	   && get_bit(component_linknet,zw)==0 && most_recent_node!=zw) continue;//component only
        else if (just_fragment==1 && fragment==1
	   && get_bit(component_linknet,zw)==0 && most_recent_node!=zw) continue;//frag only

        if (graph_type=='s' || graph_type=='t' || graph_type=='n') thisnode=zw-1;
        else thisnode=zw; //for labels at nodes
             
        if (scale_m_nodes==1 && (in_manipulate==0 || frag_node_types[zw]==0))
                this_node_size=m_node_size[zw];//scale for disks only
	else  this_node_size=s_node_size[zw];
	
        moveto(basin_pos[zw][0],basin_pos[zw][1]);
	//if (in_manipulate==1 && (graph_type=='s'  || graph_type=='t' || graph_type=='n')){
	
	
	if (in_manipulate==1){
	  signed int fragment_pointsize;
	  	    
	    fragment_pointsize=text_node_size[zw];
	    if (fragment_pointsize==0) fragment_pointsize=start_pointsize;
	    
	    //fprintf(stderr,"\n(1):fragment_pointsize=%d",fragment_pointsize);
	    //resize fonts
	    if (frag_node_types[zw]==1 || frag_node_types[zw]==2
		|| frag_node_types[zw]==0
	        || (show_labels==1 && text_label[thisnode][0]!='\0')){ //include spot with number inside
	       	      
               if (frag_node_types[zw]==0) //include spot with number inside
		      fragment_pointsize=label_pointsize;//font size from initial options
	       else fragment_pointsize=text_node_size[zw];//for expand/contract font
	             
	       if (fragment_pointsize==0) fragment_pointsize=start_pointsize;
	       //this is necessary for PostScript to work if 
		
	       //fprintf(stderr,"\n(2):zw=%d fragment_pointsize=%d temp_text_size=%d",
	                        //zw,fragment_pointsize,temp_text_size);
	      
	       if (moving_with_mouse==0 && (fragment_pointsize!=temp_text_size ||
					    (zw==node_no &&  frag_node_types[zw]!=0) ||
					    (show_labels==1 && text_label[zw][0]!='\0'))){     
		    
                    # if __UNIX__	
	               free_fonts();
                       setup_fonts(fragment_pointsize);//resize fonts
                    # endif
		       
		       //fprintf(stderr,"\n(3):text_node_size[%d]=%d fragment_pointsize=%d",
		            //zw,text_node_size[zw],fragment_pointsize);
		       
		    if (graph_postscript==1){
		        //resetfont_ps("Times-Roman",fragment_pointsize);//in case fontsize was changed
		        resetfont_ps("Times-Bold",fragment_pointsize);//in case fontsize was changed
			//fprintf(stderr,"\n(3):fragment_pointsize=%d",fragment_pointsize);
		        psize_ps=fragment_pointsize;
	     	    }	
	        }	       
	        jump_graph_vertex(zw,this_node_size,basin_color[zw],X1,Y1,X2,Y2);
		
	    }
	    //frags not text
	    else jump_graph_vertex(zw,this_node_size,basin_color[zw],X1,Y1,X2,Y2);
	}
	//initial setup --- not if (in_manipulate==1 && (graph_type=='s' || graph_type=='t' || graph_type=='n'))
	else jump_graph_vertex(zw,this_node_size,basin_color[zw],X1,Y1,X2,Y2);
	
	setcolor(white);
     } 
     
     setcolor(tempcolor);
     setviewport(0,0,Maxx,Maxy,0);
}

/****** draw a jump-graph vertex or node as a disk or point, Aug 2000 ********/
void jump_graph_vertex(signed int zw,float node_size,unsigned char thiscolor,
                 signed int X1,signed int Y1,signed int X2,signed int Y2){
  
  //float this_node_size;
  unsigned char tempcolor;
  signed int tempx,tempy;

  signed int blockwidth;
  unsigned char blockcolor;
  char this_type,*thisseed;
  signed int thisnode;

  if (graph_type=='s' || graph_type=='t' || graph_type=='n') thisnode=zw-1; //consecutive node numbers
  //else if (graph_type=='t') thisnode=dec_equiv(pat_state0[zw-1],L);       
  else thisnode=zw; //for labels at nodes

  //fprintf(stderr,"\n >%d",zw);
  
  //allow all graph types     
  if ((thisseed=(char *)calloc(bytesL,sizeof(char)))==NULL) outof_memory("thisseed");
  if (value_range==2) dec_to_bit_line(thisseed, thisnode,lineL);
  else dec_to_value_line(thisseed, thisnode,lineL);

  if (graph_type=='t') memcpy(thisseed,pat_state0[zw-1],bytesL);
    
  if (in_manipulate==1){
       this_type=frag_node_types[zw];
       //fprintf(stderr,"\n******zw=%d type=%d node_size=%f", zw,frag_node_types[zw],node_size);
  }     
  else this_type=show_numbers;
  
  setviewport(X1,Y1,X2,Y2,1); /*clip in rectangle*/
  if (this_type==0){ //draw a disc  
           tempcolor=getcolor();
           tempx=getx;
           tempy=gety;
	   
           setfillstyle(SOLID_FILL,thiscolor);
         	   
           //if (node_size<2.5) node_size=2.5; //?? july2024
	   
           pieslice(1,getx,gety,0,360,(signed int)node_size);
           if (graph_postscript){
              color_ps(graph_postscript-1,thiscolor);
              circle_fill_ps(tempx,tempy,(double)node_size);/*filled circle*/
              color_ps(graph_postscript-1,white);
              circle_ps(tempx,tempy,(double)node_size);/*outline*/
           }
	   //fprintf(stderr,"\npsize_ps=%d node_size=%f CHeight=%d",psize_ps,node_size,CHeight);
	   if (node_numbers==1){
              if (node_size>=CHeight*.7){
                 setcolor(black);                       
                 moveto(getx-CWidth/2,gety-CHeight/2);
                 if ((graph_type=='s' || graph_type=='t' || graph_type=='n')
		                && jump_layout_only==0) sprintf(textb[1],"%d",zw-1);
                 else sprintf(textb[1],"%d",zw);
                 outtext(textb[1]);
                 if (graph_postscript){
                    color_ps(graph_postscript-1,black);
                    nodetext_ps(2,0,textb[1],tempx,tempy);
                 }
	      }
           }
	   else if (node_numbers==2){
	         moveto(getx-CWidth/2,gety+CHeight-CHeight/2);
		 tempx=getx;	     
                 tempy=gety;
                 if ((graph_type=='s' || graph_type=='t' || graph_type=='n')
		                && jump_layout_only==0) sprintf(textb[1],"%d",zw-1);
                 else sprintf(textb[1],"%d",zw);
		 
		 setfillstyle(SOLID_FILL,black);//empty bar, black or white as background
		 bar(tempx-vgax(2),tempy-CHeight,tempx+CWidth*strlen(textb[1])+vgax(1),tempy);
		 if (graph_postscript){
		      color_ps(graph_postscript-1,black);
		      rect_fill_ps(tempx-vgax(2),tempy-CHeight,CWidth*strlen(textb[1])+vgax(2),CHeight);
		 }
		 setcolor(thiscolor); //make outline same as disc color
	
		 rectangle(tempx-vgax(2),tempy-CHeight,tempx+CWidth*strlen(textb[1])+vgax(1),tempy);
		 if (graph_postscript){
		     color_ps(graph_postscript-1,thiscolor);
                     rect_outline_ps(tempx-vgax(2),tempy-CHeight,CWidth*strlen(textb[1])+vgax(2),CHeight);
		 }    
		 moveto(tempx,tempy-CHeight);//position number, same as in disc
		 //setcolor(white);
		 setcolor(thiscolor);//color number according to disc color
                 outtext(textb[1]);                 
		 
                 if (graph_postscript){
		   //color_ps(graph_postscript-1,white);
		   color_ps(graph_postscript-1,thiscolor);
		   nodetext_ps(3,0,textb[1],tempx,tempy-CHeight/4); //try this
                 }
	   }
           setcolor(tempcolor);
           if (graph_postscript) color_ps(graph_postscript-1,tempcolor);
  }

  /*--------------- graph_type=='s' only --- code from draw60.c --------------------------------*/   
  #   if __WATCOM__
  /*decimal or hex equivalent*/  
  else if (this_type==1 || this_type==2){
     
     if (this_type==1){//start with 0 for ibaf and net graphs
        if ((graph_type=='s' ||  || graph_type=='t' graph_type=='n') && jump_layout_only==0)
	          sprintf(textb[1],"%d",zw-1);
        else if (still_jump_graph==1) sprintf(textb[1],"%d",zw);
        else sprintf(textb[1],"%d",zw-1);//start with 1 for jump-graph
    }

     setcolor(white);
     blockcolor=black;
     setfillstyle(SOLID_FILL,blockcolor);    
     tempx=getx;
     tempy=gety;
     if (blockcolor!=black) setcolor(black);
  
      if (this_type==1){          
	  blockwidth=textwidth(textb[1]);	  
	  if (labelsizefactor>0){ /*scaled line seg font*/
             bar(getx+1,gety,getx+blockwidth,gety+CHeight);
             _grtext(tempx,tempy,textb[1]);
          }
          else{ /*default font*/
             bar(getx+1,gety+2,getx+blockwidth+1,gety+CHeight-2);
             moveto(tempx,tempy);
             outtext(textb[1]);
          }
       }
       /*hex equivalent*/
       else if (this_type==2){
         unsigned char forecolor;
          forecolor=white;          
	  //if (blockcolor!=black) forecolor=black;
	  bar(getx+1,gety+2,getx+(bytesL*2*textwidth("z"))+1,
					gety+textheight("z")+1);
	  moveto(tempx,tempy);
	  print_current_bitstring_hexbytes(0,0,thisseed,-2,10000,forecolor,0);
       }
  }

# elif __UNIX__
  /*decimal or hex equivalent*/
  //else if ((this_type==1 || this_type==2) && lineL<=32){
  else if (this_type==1 || this_type==2){
      //signed int psize,temp_psize;

    //fprintf(stderr,"\nvertex: text_node_size[%d]=%d",zw,text_node_size[zw]);
     
    if (this_type==1){//start with 0 for ibaf and net graphs
        if ((graph_type=='s' || graph_type=='n') && jump_layout_only==0) sprintf(textb[1],"%d",zw-1);
	else if (graph_type=='t')	        
		 sprintf(textb[1],"%lu",dec_equiv(pat_state0[zw-1],L));
	          //sprintf(textb[1],"%lu",dec_state0[zw-1]);
        else if (still_jump_graph==1) sprintf(textb[1],"%d",zw);//??
        else sprintf(textb[1],"%d",zw-1);//start with 1 for jump-graph
    }
   
    setcolor(white);
    blockcolor=black;
             
    setfillstyle(SOLID_FILL,blockcolor);
    tempx=getx;	     
    tempy=gety;
    if (blockcolor!=black) setcolor(black);
    XSetBackground(D,Gc,(unsigned long)Color_Table[blockcolor]);
            
    if (this_type==2){
        unsigned char bytez;
	signed int z;
         sprintf(textb[1],"");
         for (z=bytesL-1;z>=0;z--){
	    bytez=thisseed[z];
            if (bytez<16) sprintf(textb[2],"0%x",bytez);
            else sprintf(textb[2],"%x",bytez);
            sprintf(textb[1],"%s%s",textb[1],textb[2]);            	 
         }
                
         /*this draws a rectange in current background first, then the string*/
         XDrawImageString(D,W,Gc,tempx,tempy,textb[1],strlen(textb[1]));	 
         /*moverel(XTextWidth(tempfont,textb[1],strlen(textb[1])),0);*/
         if (graph_postscript){
              nodetext_ps(1,blockcolor,textb[1],tempx,tempy);
         }                                    
    }
    
    else{            
         /*this draws a rectange in current background first, then the string*/
         XDrawImageString(D,W,Gc,tempx,tempy,textb[1],strlen(textb[1]));
         if (graph_postscript){                     
              nodetext_ps(1,blockcolor,textb[1],tempx,tempy);
         }      
    }
    //if (bground=='w') XSetBackground(D, Gc, WhitePixel(D, S));
    //else if (bground=='b') XSetBackground(D, Gc, BlackPixel(D, S));

  }
# endif

  /*graphic bit-string*/
  else if (this_type==3 || this_type==4){
      char tempscale;
      
      //fprintf(stderr,"\nc_scale=%f %d this_type%d ",c_scale,(char)c_scale,this_type);
      
      tempscale=scale;
      //scale=(char)c_scale;
      scale=(char)s_node_size[zw];//for 1d or 2d bits-strings, apply standard (expandable) node size
      	
      /*if (linec==black) blockcolor=lightcyan;
	  else if (linec==lightcyan) blockcolor=magenta;
	  else if (linec==green) blockcolor=cyan;
	  else if (linec==yellow) blockcolor=lightred;
	  else if (linec==lightred) blockcolor=yellow;
	  else blockcolor=white;*/

          //in case scale has changed redefine size if block1 and block_all
          //if (graph_postscript && zw<node_no && s_node_size[zw]!=s_node_size[zw+1]){ ...was a bug
          if (graph_postscript && zw<=node_no && s_node_size[zw]!=s_node_size[zw+1]){
	     scale=(char)s_node_size[zw];
	     /*fprintf(stderr,"\nbp=%d zw=%d scale=%d %f:%f",
	       basin_postScript,zw,scale,m_node_size[zw],m_node_size[zw-1]);*/	     
	     prepare_basinPS(0,0);
	     //scale=(char)c_scale;
	  } 
          blockcolor=yellow;//looks blue on white background

	  //if (twod !! showbits_1d_as_2d){
	  if (this_type==4){ //2d bits
	    showbits_1d_as_2d=1;
	    twod=1;
            print_current_state_twod(thisseed,blockcolor,0);//to screen
            if (graph_postscript) sp_node_ps(1,thisseed,getx,gety,blockcolor);//to ps
	  }   
	  else if (this_type==3){ //1d bits
	    showbits_1d_as_2d=0;
	    print_current_state_h(thisseed,blockcolor);//to screen	      
	    if (graph_postscript) sp_node_ps(0,thisseed,getx,gety,blockcolor);//to ps	
          }
          scale=tempscale;
  }

 //# if __WATCOM__||__UNIX__ works for both
  /*show a (multi line) label if set and toggled on*/  
  if (show_labels==1 && text_label[thisnode][0]!='\0'){
     signed int i,line_no=0,line_break[90];//static maxLabel=90
     signed int startWx,startWy,tempy_post; 
     char *temp_label;

     //if a valid char string label exists, review line breaks and draw it
     if (text_label[thisnode][0]!='\0'){
          
       //superseded by basin_pos[zw][0], basin_pos[zw][0] see below
       //startWx=getx; 
       //startWy=gety-CHeight;
       
       //inital Label overwrites alphanumeric nodes
       //but can be lowered with backspace \ at start       
       //recentre on nodes positions (in case getx/y displaced by node number)
       startWx=basin_pos[zw][0]; 
       startWy=basin_pos[zw][1]-CHeight;

       sprintf(textb[0],"temp_label");
       if ((temp_label=(char *)calloc(maxLabel,sizeof(char)))//static maxLabel=90
                            ==NULL) outof_memory(textb[0]);
       
       setcolor(white);
       blockcolor=black;      
       setfillstyle(SOLID_FILL,blockcolor);
       
       //identify line breaks and number of lines
       for (i=0;i<=strlen(text_label[thisnode]);i++){
	   if (text_label[thisnode][i]=='\\'){
	       line_no++;
               line_break[line_no]=i;
	   }
	}

        line_break[line_no+1]=strlen(text_label[thisnode]);
	line_break[0]=0;      
	  
        for (i=0;i<=line_no;i++){     
	     tempx=startWx;	      
	     tempy=startWy+CHeight*i;//inital Label overwrites alphnumeric nodes
	                //but can be lowered with backspace \ at start to show alphnumeric nodes 
	     tempy_post=startWy+(CHeight*i*.85)+CHeight; //for postscript to behave as screen output

	     memmove(temp_label,text_label[thisnode]+line_break[i],line_break[i+1]-line_break[i]);
	     temp_label[line_break[i+1]-line_break[i]]='\0';
	     
	     if (temp_label[0]=='\\'){
	        memmove(temp_label,temp_label+1,strlen(temp_label)); //get rid of leading '\\'		
	     }
	     //print each line in graph
             moveto(tempx,tempy);
             /*this draws a rectange in current background first, then the string*/
             bar(tempx,tempy+vgay(1),tempx+text_pix_width(temp_label),tempy+CHeight+vgay(1));
             moveto(tempx,tempy);
             outtext(temp_label);
             //print each line in PostScript
             if (graph_postscript==1 || graph_postscript==2){
	       //label width in pixels calculated in vecpost
	       nodetext_ps('L',blockcolor,temp_label,tempx,tempy_post);//move up one line to match
	       
             }	     
        }
	free(temp_label);	  
     }
  }
//# endif  
  
  free(thisseed);	   	   
  setviewport(0,0,Maxx,Maxy,0);
}

/******************* line with varying thickness ***************/
void thickline(char selflink,signed int x1, signed int y1,
	       signed int x2, signed int y2, 
                     unsigned char thiscolor, 
                     double thisthick, double maxthick){ 

  float xgap,ygap,xend,yend;
  char signx,signy,tempcolor;
  signed int gapfactor;
  signed int arrow[6];

         tempcolor=getcolor() ;   
         compute_link_angle(x1,y1,x2,y2);
      
         xend=(float) ( fabs(sin(abs_angle))*thisthick );
         yend=(float) ( fabs(cos(abs_angle))*thisthick );

         /*if (thisthick<=1 || (xend<1 && yend<1) ) thinline=1;*/
         if (selflink==-1){ /*for orbital ant*/
	    selflink=0;
            scale_links=1;
	 }
         /* gap between input and output links*/
         if (scale_links==1) gapfactor=maxthick/7; /*thick links*/
	 else gapfactor=maxthick*2; /*thin links*/
         
	 if (maxthick>=thisthick){
	     xgap=(float) ( fabs(sin(abs_angle))*gapfactor );
	     ygap=(float) ( fabs(cos(abs_angle))*gapfactor );
	 }
         /*make line central ?*/
         else{ 
	    xgap=-(float) ( fabs(sin(abs_angle))*(thisthick/2) );
	    ygap=-(float) ( fabs(cos(abs_angle))*(thisthick/2) );  
         }

	 if ( x1<=x2 && y1>y2){ 
	   signx=-1; signy=-1;            
	 }
         else if (x1>x2 && y1>=y2){
            signx=-1; signy=1; 
	 }
         else if (x1>=x2 && y1<y2){
            signx=1;signy=1;             
	 }
         else if (x1<x2 && y1<=y2){
            signx=1; signy=-1; 
            
	 }
         poly[0]=   x1  +   (xgap*signx);
         poly[1]=   y1  +   (ygap*signy);

         poly[2]=   x2  +   (xgap*signx);
         poly[3]=   y2  +   (ygap*signy);

         setcolor(thiscolor);
         if (graph_postscript) color_ps(graph_postscript-1,thiscolor);
         if (scale_links==1){ /*draw thick link (but not for state transition graph)*/
            poly[4]=   poly[2] +  (xend*signx);            
            poly[5]=   poly[3] +  (yend*signy);

            poly[6]=   poly[0] +  (xend*signx);            
            poly[7]=   poly[1] +  (yend*signy);

            /*draw line anyway in case poly too thin, wont show*/            
            line(poly[0],poly[1],poly[2],poly[3]);       
            if (graph_postscript){
              line_block_ps(poly);
              thick_line_ps(.7,poly[0],poly[1],poly[2],poly[3]);   
            }
            /*draw the filled poly*/
	    setfillstyle(SOLID_FILL,thiscolor);           
            fillpoly(4, poly);
	 }
         /*draw thin link*/
         else{ 
            line(poly[0],poly[1],poly[2],poly[3]);
            if (graph_postscript) 
                thick_line_ps(.7,poly[0],poly[1],poly[2],poly[3]);
                /*.7 to show in book*/
         }
         if (show_arrows==1){
           float thisangle;
            if (selflink==0) thisangle=linkangle-(float)PI;
            else thisangle=linkangle;
            /*center the arrow*/
            if (scale_links==1){ 
               poly[0]+=(xend*signx)/2;
               poly[1]+=(yend*signy)/2;
               poly[2]+=(xend*signx)/2;
               poly[3]+=(yend*signy)/2;
            }
	    /*reverse the angle to make arrows point the right way*/
            /*not for self link*/
	        arrow[0]=poly[0]+(poly[2]-poly[0])*.6;
                arrow[1]=poly[1]+(poly[3]-poly[1])*.6;
                arrow[2]=(cos(-(thisangle+PI/10))*w_cyclerad*arrow_size)+arrow[0];
                arrow[3]=(sin(-(thisangle+PI/10))*w_cyclerad*arrow_size)+arrow[1];
                arrow[4]=(cos(-(thisangle-PI/10))*w_cyclerad*arrow_size)+arrow[0];
                arrow[5]=(sin(-(thisangle-PI/10))*w_cyclerad*arrow_size)+arrow[1];
                /*draw the filled arrow*/
	        if (scale_links==0){ 
                   setfillstyle(SOLID_FILL,thiscolor);
                   if (graph_postscript) color_ps(graph_postscript-1,thiscolor);
                } 
                else{ 
                   setfillstyle(SOLID_FILL,white);
                   if (graph_postscript) color_ps(graph_postscript-1,white);
                }         
                fillpoly(3,arrow);
                if (graph_postscript) arrow_block_ps(arrow);         
	 }             
         setcolor(tempcolor);
         if (graph_postscript) color_ps(graph_postscript-1,tempcolor);
}


/****** drag functions: drag/manipulate graph with mouse , Aug 2000 ********** *******/
void manipulate_jump_graph(signed int wox, signed int woy,
                           signed int X1,signed int Y1,
	                   signed int X2,signed int Y2,
                           float rot_angle){

 unsigned long *node_outputs,*node_inputs;
 unsigned int most_recent_node,prev_node,basin_locked_onto=0,
            zw,zz,thiszz;
 signed int promptx,prompty,
             oldx,oldy;
 char test=0,event,components=0,link_step=0,blockset=0,range_type;
 signed int tempx,tempy,bytesT;
 unsigned int wcount,refresh;
 char show_numbers_nolinks=0; //for nolinks either discks or numbers

 float lock_radius;
    lock_radius=vgax(2.5);//to select node with left/right button, position cemtre +/- 2.5 pixels

    if (no_links==0){
       if ((node_outputs=(unsigned long*)calloc(node_no+1,
                  sizeof(unsigned long)))==NULL) outof_memory("node_outputs");    
    
       if ((node_inputs=(unsigned long*)calloc(node_no+1,
                   sizeof(unsigned long)))==NULL) outof_memory("node_inputs");
    }

   
    bytesT=(signed int)ceil((double)node_no/8);
    if ((linknet=(char*)calloc(bytesT,sizeof(char)))==NULL) outof_memory("linknet");
    if ((component_linknet=(char*)calloc(bytesT,sizeof(char)))==NULL) outof_memory("component_linknet");
    
    tempx=getx;
    tempy=gety;
 
    refresh=10000;  
    
#  if __WATCOM__
      refresh=5000;
      if (mouse_found) mouse_call(1,0,0,0); /*display mouse*/
#  elif __UNIX__
       mouse_found=1;          
#  endif

   get_prompt_box(10,3);
   
   /*for ibaf graph (interactive basin of attraction field), March 2021
     start with with 'e'-"either" so a whole basin can be moved*/ 
   if (graph_type=='s' || graph_type=='t') components='e'; 
   else components='s'; //otherwise start with a single node
   
   most_recent_node=prev_node=1;
   prompt_and_component(components,link_step,blockset,
                                   most_recent_node,prev_node);

   promptx=getx;
   prompty=gety;

   button_not_rel=button=0;
  
   wcount=0;
   moving_with_mouse=0;
   fragment=1;
   draw_jump_graph(most_recent_node,wox,woy,X1,Y1,X2,Y2);//redraw fragment=1 graph
   
   while (1){
      moveto(promptx,prompty); /*position of flashing cursor in prompt box*/
#     if __UNIX__
         /*while(event_ready()==0);*/ /*255 to suppress flashing cursor*/
         flashing_cursor(0,0,0,0,0,-1,CWidth,1+CHeight/2,255);
#     elif __WATCOM__
         flashing_cursor(0,CHeight-vgay(3),CWidth,CHeight,green);
#     endif
     
      if (mouse_found){
	 fragment=1;
         moving_with_mouse=1;
	 if (button=='l'|| button=='r'){
	  startmouse:
             wcount+=1;
             if (wcount==Maxu) wcount=1;
	     button_not_rel=0;
              
	    if (button=='l'){
	        if (basin_locked_onto){
		   if (wcount%refresh==0){
                      
                      basin_pos[basin_locked_onto][0]=mouse_x;
                      basin_pos[basin_locked_onto][1]=mouse_y;
                      
                      if (components!='s' || blockset==1){
                         xoffset=mouse_x-oldx;
                         yoffset=mouse_y-oldy;                         
                         for (zz=node_no;zz>=1;zz--){
                            thiszz=zz;
			    if (zz==basin_locked_onto || ((components!='a') && get_bit(linknet,thiszz)==0)) continue;
			    basin_pos[zz][0]+=xoffset;
                            basin_pos[zz][1]+=yoffset;
                         }
		      } 
                      oldx=basin_pos[basin_locked_onto][0];
                      oldy=basin_pos[basin_locked_onto][1];
                      
                      if (quick_move==0){ //quick_move avoids animation, bare node dragged then snap
			    //if (abs(oldx-wox)>4 || abs(oldy-wox)>4){ //reduce shaking, but doesnt work                  
			    //draw_box(-1,X1,Y1,X2,Y2,1,0);/*clear box --- if not done interesting graphic effects*/
			    draw_jump_graph(most_recent_node,wox,woy,X1,Y1,X2,Y2);
			//}
                      }
                      else{ 
			 moveto(oldx,oldy);
			 if (scale_m_nodes==1) jump_graph_vertex(basin_locked_onto,
				 m_node_size[basin_locked_onto],
				      basin_color[basin_locked_onto],X1,Y1,X2,Y2);
			 else jump_graph_vertex(basin_locked_onto,
				 s_node_size[basin_locked_onto],
				      basin_color[basin_locked_onto],X1,Y1,X2,Y2);
                      }
		   }
		}              
	       /*check left mouse button released*/
#              if __WATCOM__   
	          mouse_call(6,0,0,0);
                  if (globbx==0) button_not_rel='l';
       
#              elif __UNIX__
		  //fprintf(stderr,"L1");
                  event=XCheckWindowEvent(D,W,ButtonReleaseMask,&Event);
		  //fprintf(stderr,"L2");
                  /*left button not released*/
                  if (event==0 || Event.xbutton.button!=1) button_not_rel='l';
                  /*else fprintf(stderr," event=%d Event==%d notrel=%d\n",
                      event,Event.xbutton.button,button_not_rel);*/   
#              endif
                  /*left button released*/
		  else if (basin_locked_onto){
		     
                     /*lock-on, and left button was released*/
		     basin_pos[basin_locked_onto][0]=mouse_x;
                     basin_pos[basin_locked_onto][1]=mouse_y;
                     if (components!='s' || blockset==1){
                         xoffset=mouse_x-oldx;
                         yoffset=mouse_y-oldy;
                         for (zz=node_no;zz>=1;zz--){
                            if (zz==basin_locked_onto || (components!='a' && get_bit(linknet,thiszz)==0)) continue;
			    basin_pos[zz][0]+=xoffset;
                            basin_pos[zz][1]+=yoffset;
                         }
		      }
		     		      		      
		      most_recent_node=basin_locked_onto;
		      
                      //in any context, restore size of numbers/text (which reverted to default while dragging) 
		      moving_with_mouse=0;
		      //fprintf(stderr,"\nbutton released -- redraw draw_jump_graph");
                      draw_jump_graph(most_recent_node,wox,woy,X1,Y1,X2,Y2);
		      moving_with_mouse=1;
		      		      
		      most_recent_node=basin_locked_onto;
                      basin_locked_onto=0; /*unlock*/
		  }
	    }
            
	    if (button=='r'){ /*check right mouse button released*/                               	       	       
#              if __WATCOM__   
	          mouse_call(6,1,0,0);
                  if (globbx==0) button_not_rel='r';
#              elif __UNIX__
                   event=XCheckWindowEvent(D,W,ButtonReleaseMask,&Event);
		   //fprintf (stderr,"R1-");
                   if (event==0 || Event.xbutton.button!=3) button_not_rel='r';
		   //fprintf(stderr,"R2");
                   /*else fprintf(stderr," event=%d,Event=%d notrel=%d\n",
                           event,Event.xbutton.button,button_not_rel);*/
#              endif	      
	    }
	    
	    if (button_not_rel){
#              if __WATCOM__   		  
                  mouse_call(3,0,0,0); /*mouse position*/
                  mouse_x=globcx;
		  mouse_y=globdx;
                  /* show co-ordinates*/
		  /*sprintf(textb[0],"x=%d y=%d",mouse_x,mouse_y);
		    draw_hint_box(0,0,textb[0],vgax(500));*/		  
#              elif __UNIX__
                 if (XCheckWindowEvent(D,W,KeyPressMask|PointerMotionMask,&Event)){
                      if (Event.type == MotionNotify ||
                                    Event.type == ButtonPress){
			 if (Event.type == MotionNotify){
                            mouse_x=Event.xmotion.x;
                            mouse_y=Event.xmotion.y;
                         }
                         if (Event.type == ButtonPress){
                            mouse_x=Event.xbutton.x;
                            mouse_y=Event.xbutton.x;
                         }
                         if (mouse_x>=X1 && mouse_y>=Y1
                               && mouse_x<=X2 && mouse_y<=Y2){
                             if (inside_rect==0){
                                XDefineCursor(D,W,leftCursor);
	                        inside_rect=1;
	                     }
                         }
                         else if (inside_rect==1){
                            XDefineCursor(D,W,rightCursor);
                            inside_rect=0;
                         }
                        /* show co-ordinates*/
			/*sprintf(textb[0],"x=%d y=%d",mouse_x,mouse_y);
			  draw_hint_box(0,0,textb[0],vgax(500));*/     
                     }  
                 }
#              endif
		 if (basin_locked_onto==0){ //grab a new node, show in new top-right drag-prompts
                    for (zw=node_no;zw>=1;zw--){
		       if (mouse_x>basin_pos[zw][0]-lock_radius && 
                           mouse_x<basin_pos[zw][0]+lock_radius &&
                           mouse_y>basin_pos[zw][1]-lock_radius && 
			   mouse_y<basin_pos[zw][1]+lock_radius){
			 
                            prev_node=most_recent_node;
			    basin_locked_onto=most_recent_node=zw;
                            moveto(basin_pos[zw][0],basin_pos[zw][1]);

                            oldx=basin_pos[zw][0];
                            oldy=basin_pos[zw][1];

                            wcount=refresh-1;
			    //fprintf(stderr,"\nG1-");
                            prompt_and_component(components,blockset,link_step,
			                     most_recent_node,prev_node);
			    //fprintf(stderr,"G2");
                            break;
	                }
		    }
	         }	 
	         goto startmouse;
	    }
	    continue;
	 }	 
      }
     
      moving_with_mouse=0;
      test=0;
      test=keycheck(0);
      //fprintf(stderr,"\n %c %d",test,test);
      if (test=='q') goto endFunc;
      //if (no_links==0){ //done for each if relevant

	 if (test=='P'){
	         //note: jump-graph with no-links treated as graph_type=='n'
	         
		 this_text_size=current_text_size;
	         //fprintf(stderr,"current_text_size=%d",current_text_size);
                 # if __UNIX__
                       free_fonts();
                       setup_fonts(start_pointsize);//to preserve normal prompt font
                 # endif
		    
                 erase_prompt_box(4);
		 draw_prompt_box(1);
		 outtext("manipulate: PostScript: greyscale-P color-p:");
		 input_string(1,0);
		 	   
		 current_text_size=this_text_size;
                 # if __UNIX__
                       free_fonts();
                       setup_fonts(current_text_size);
                 # endif
		
		 if (is[0]=='p'|| is[0]=='P'){
                    save_graph_PScript(most_recent_node,X1,Y1,X2,Y2,wox,woy);		   
		 }
	 }
	 
         else if (test=='L' && components=='s' && blockset==0){
	   signed int xbox,z,len,thisnode;
	  	          
	         //get_prompt_box(15,4);
	         //jump-graph first node =1, otherwise first node =0
	         if (graph_type=='s' || graph_type=='t' || graph_type=='n') thisnode=most_recent_node-1;
                 else thisnode=most_recent_node;
					
	         this_text_size=current_text_size;
	         //fprintf(stderr,"current_text_size=%d",current_text_size);
                 # if __UNIX__
                       free_fonts();
                       setup_fonts(start_pointsize);//to preserve normal prompt font
                 # endif
	   
	         xbox=draw_prompt_box(4);
		 if (text_label[thisnode][0]=='\0'){
		   if (graph_type=='s' || graph_type=='t' || graph_type=='n')
		                sprintf(textb[0],"node=%d (0-%d) Label: empty",
							      thisnode,node_no-1);
		    else sprintf(textb[0],"node=%d (1-%d) Label: empty",thisnode,node_no);
		 }
		 else{
		   if (graph_type=='s' || graph_type=='t' || graph_type=='n')
		                sprintf(textb[0],"node=%d (0-%d) Label: \"%s\"",
					      thisnode,node_no-1,text_label[thisnode]);
		   else sprintf(textb[0],"node=%d (1-%d) Label: \"%s\"",
				        thisnode,node_no,text_label[thisnode]);
		 }
		 outtext(textb[0]);
		 moveto(xbox,gety+CHeight);
		 if (text_label[thisnode][0]=='\0') sprintf(textb[0],"accept-ret new-n:");
		 else sprintf(textb[0],"accept-ret delete-d new-n:");
		 outtext(textb[0]);
		 input_string(1,0);
                 if (is[0]==13) goto skip_new;  //accept existing label
		 else if (is[0]=='d'){
		    text_label[thisnode][0]='\0';
		    goto skip_new;
		 }   
		 //else if (is[0]=='n') moveto(xbox,gety+CHeight);
                 else if (is[0]=='n') 
                         sprintf(textb[0],"  enter new Label max %d char",maxLabel);//static maxLabel=90
		 outtext(textb[0]);
                 moveto(xbox,gety+CHeight);
                 //sprintf(textb[0],"back-backspace, linebreaks-'\\', complete/exit-ret");
		 sprintf(textb[0],"back-backspace, linebreaks-\"\\\", complete/exit-ret");
		 outtext(textb[0]);
		 moveto(xbox,gety+CHeight);
		                 
		  //for a max90 string with any isalpha,isdigit,ispunct, etc keyboard symbols
		 len=input_string(maxLabel,'L');//static maxLabel=90
		 if (is[0]==13){ //this deletes existing label
		      text_label[thisnode][0]='\0';
		      //fprintf(stderr,"\n:none:node %d: %s\n",thisnode,text_label[thisnode]);
		 }    
		 else{
		    show_labels=1;
                    memmove(text_label[thisnode],is,len);
		    text_label[thisnode][len]='\0';
                    //fprintf(stderr,"\n ok:node %d: %s\n",thisnode,text_label[thisnode]);		    
		 }
		 
	         skip_new:
		 /*
		 for (z=0;z<=node_no;z++){ //print list of Labels to xterm 
		   if (text_label[z][0]=='\0') fprintf(stderr,"\n%d: empty",z);

		   else fprintf(stderr,"\n%d: %s",z,text_label[z]);
		 }*/
		 
		 current_text_size=this_text_size;
                 # if __UNIX__
                       free_fonts();
                       setup_fonts(current_text_size);
                 # endif
		 //uncover_free_prompt_box(15);		 
         }
	 else if (test=='+') show_labels=abs(show_labels-1); //tog showing labels
             	 
         else if (test=='g' && no_links==0) disconnect_node('g',node_outputs,node_inputs, 
	     components,most_recent_node,prev_node);/*cut links to all gap nodes -- /not clear what this does*/
	   
         else if (test=='c' && no_links==0) disconnect_node('c',node_outputs,node_inputs, 
	     components,most_recent_node,prev_node);/*cut all links to current node*/
         else if (test=='r' && no_links==0) disconnect_node('r',node_outputs,node_inputs,
	     components,most_recent_node,prev_node);/*restore*/
         else if (test=='#' && no_links==0) disconnect_node('#',node_outputs,node_inputs,
	     components,most_recent_node,prev_node);/*restore network all, in case multiple cuts/additions*/ 
         else if (test=='C' && no_links==0) node_pair_link('C',
	     components,most_recent_node,prev_node);/*cut a to b*/
         else if (test=='A' && no_links==0) node_pair_link('A',
	     components,most_recent_node,prev_node);/*add a to b*/  
         else if (test=='R' && no_links==0) node_pair_link('R',
	     components,most_recent_node,prev_node);/*restore a to b*/ 
         else if (test=='i' && no_links==0) components='i';
         else if (test=='o' && no_links==0) components='o';
         else if (test=='e' && no_links==0) components='e';
	 
         else if (isdigit(test) && no_links==0){
	    sprintf(textb[0],"%c",test);
            link_step=atoi(textb[0]);/*restrict link_step 1-9*/
	    //fprintf(stderr,"\nlink_step=%d",link_step);
         }
         else if (test=='0') link_step=0;/*reset link_step to all*/
	 //fprintf(stderr,"\ntest==%c",link_step);
      //} if (no_links==0){ //done for each if relevant
	 
      if (test=='a'){
	  components='a';	  
	  blockset=0;
      }
      else if (test=='s') components='s';
      /*tog updating network when dragging a node*/
      else if (test=='d') quick_move=abs(quick_move-1);

      else if (test=='x' || test=='X'){
	rotate_component_graph(test,rot_angle,mouse_x,mouse_y);
      }
      else if (test=='h' || test=='v'){
	flip_component_graph(test,mouse_x,mouse_y);
      }
      else if (test=='{' || test=='}'){
	if (components!='s' || blockset==1)
	      EC_links_component_graph(test,mouse_x,mouse_y); /*Contract/Expand links*/
      }
      else if (test=='(' || test==')'){
	if (components=='a') EC_nodes_component_graph(test,-1,blockset);
	else EC_nodes_component_graph(test,most_recent_node,blockset); /*Contract/Expand nodes*/
      }
      else if (test=='['){ //contract both
	EC_links_component_graph('{',mouse_x,mouse_y); /*Contract links*/
	if (components=='a') EC_nodes_component_graph('(',-1,blockset);
	else if (components!='s' || blockset==1)
	     EC_nodes_component_graph('(',most_recent_node,blockset); /*Contract nodes*/
      }
      else if (test==']'){ //expand both
	EC_links_component_graph('}',mouse_x,mouse_y); /*Expand links*/
	if (components=='a') EC_nodes_component_graph(')',-1,blockset);
	else if (components!='s' || blockset==1)
	    EC_nodes_component_graph(')',most_recent_node,blockset); /*Expand nodes*/
      }
      else if (test=='E'){ //equalise node text_node_size[], m_node_size[], frag_node_types[],
	                   //in component according to component root
        EC_equalise_component_graph(most_recent_node,components,blockset);
      }
      
      else if (test=='j'){
	   just_component=abs(just_component-1);//to show just the component and manipuale it
	   just_fragment=0;//turm off just_fragment
	   if (just_component==1 /*&& components=='s' && blockset==0*/){
	      components='e'; //set to e=eather, step no-limit
	      link_step=0;
	      blockset=0;//in case block was active, reset original network
	      prompt_and_component(components,blockset,link_step,most_recent_node,prev_node);
	   }  
	   //fprintf(stderr,"\nj:c=%d f=%d",just_component,just_fragment);
      }
      else if (test=='J'){
           just_fragment=abs(just_fragment-1);//to show just the fragment as defined, and manipuale it
	   just_component=0;//turn off just_component
	   if (just_fragment==1 && components=='s' && blockset==0){
	      components='e'; //set to e=eather, step no-limit
	      //link_step=0;
	   }  
	   //fprintf(stderr,"\nJ:c=%d f=%d",just_component,just_fragment);
      }
      
      else if (test=='=' /*&& (graph_type=='s' || graph_type=='t' || graph_type=='n')*/){
	               //toggle node presentation, show_numbers:
	                        //-1 none (miss out) , 0 spot, 1 dec(lineL<32), 2 hex, 3 1d bits,  3  2d bits
             char this_type;
	     
               if (no_links==1 || jump_layout_only){//if no_links skip blank)
		     show_numbers_nolinks=abs(show_numbers_nolinks-1);
		     this_type=show_numbers_nolinks;
		     if (components=='a') most_recent_node=-1; //for all nodes no links
		     //fprintf(stderr,"\nnolink=:this_type=%d",this_type);
		     nodes_type_component_graph(this_type,most_recent_node,blockset);
		}
                
	        else{
		   if (this_type==-1) this_type=0; 
		   else if (this_type==0) this_type=1; //1 dec
		   else if ((graph_type=='s' || graph_type=='t') && this_type==1) this_type=2; //2 hex
		   else if ((graph_type=='s' || graph_type=='t') && this_type==2){//note : no 1d or 2d patterns for graph_type=='n'
		          this_type=3; //1d bitsfragnent
	           }
		   else if ((graph_type=='s' || graph_type=='t') && this_type==3){//3 2d bits
		          this_type=4; //1d bitsfragnent
	           } 
	           else this_type=-1;
                   //fprintf(stderr,"\n manipulate nodes:this_type=%d",this_type);
		   /*change node type for component only*/
		   nodes_type_component_graph(this_type,most_recent_node,blockset); 
	       }	   
      }

      if (test=='i' || test=='o' || test=='e' || test=='a'
	                     || (blockset==1 && test=='s'))  blockset=0;//to cancel block

      if (test=='B' && components=='s'){ //"single" node selected set/cancel cancel block      
	   if (blockset==0){
	      //fprintf(stderr,"\nmanipulate: %d--%d",most_recent_node,prev_node);
	      range_type=block_or_slice(components,blockset,most_recent_node,prev_node);
	      if (range_type==0) blockset=0; //block aborted qith 'q'
	      else blockset=1; //block was set
	   }
	   else blockset=0;
      }
      
      if (test=='g'){
	 draw_jump_graph(most_recent_node,wox,woy,X1,Y1,X2,Y2);
      }
      	  	
      else if (test){
         //fprintf(stderr,"\ntest=%c",test);	
	 if (test!='c') prompt_and_component(components,blockset,link_step,most_recent_node,prev_node);
	 
	 if (test=='i' || test=='o' || test=='e' ||
	     test=='(' || test==')' || test=='[' || test==']' || test=='{' || test=='}' || test=='E' || test=='='
             || test=='x' || test=='X' ||test=='h' || test=='v' || test=='j' || test=='J'
	     || test=='0' || isdigit(test) /* || test=='c'*/){
	       draw_jump_graph(most_recent_node,wox,woy,X1,Y1,X2,Y2);
         }
         else if (test=='d' || test=='a' || test=='s' /*test=='i' || test=='o' || test=='e' ||
	     || test=='B'  || isdigit(test) || test=='0' */);
	     /*fprintf(stderr,"\ndo not redraw");*/ /*do nothing, no need to redraw for these, July 2018*/
	 
	 else if (test!='P'){ //because already drawn in save_graph_PScript(...)
	     moving_with_mouse=1;
	     draw_jump_graph(most_recent_node,wox,woy,X1,Y1,X2,Y2);
	     /*if (show_numbers==1 || show_numbers==2){
	        free_fonts();
                setup_fonts(start_pointsize);
	     }*/
	  }
       }
   }//from while (1){
 endFunc:
   
   fragment=0;
   just_component=0;
   if (mouse_found){
#     if __WATCOM__     /*release mouse for rectangle*/
         mouse_call(7,0,0,getmaxx());
         mouse_call(8,0,0,getmaxy());
#     elif __UNIX__
         XDefineCursor(D,W,rightCursor); /*restore cursor shape*/
#     endif
   }   
   //uncover_free_prompt_box(12);
   //fprintf(stderr,"\nfpb12-l4971");
   
   free(linknet);
   free(component_linknet);
   if (no_links==0){
      free(node_outputs);
      free(node_inputs);
   }
   moveto(tempx,tempy);
}

/************** draw drag prompt and check component * *****************/
void prompt_and_component(char components, char blockset, char link_step,
        unsigned int most_recent_node, unsigned int prev_node){
  signed int xbox,bytesT;
  unsigned int m_r_node,p_node;
  unsigned int zu;
  
         this_text_size=current_text_size;
	 //fprintf(stderr,"current_text_size=%d",current_text_size);
         # if __UNIX__
               free_fonts();
               setup_fonts(start_pointsize);
         # endif
	 
         xbox=draw_prompt_box(4);
         setcolor(lightred);

	 //set start number 0 or 1
	 if (graph_type=='a' || graph_type=='f'
	       || (graph_type=='n' && jump_layout_only==1) ){ //jump-graph with or without links start=1
            m_r_node=most_recent_node;
            p_node=prev_node;
         }         
	 else{   /*network and ibaf indices start=0*/
	    m_r_node=most_recent_node-1;
            p_node=prev_node-1;
         }
	 
	 bytesT=(signed int)ceil((double)(node_no+1)/8);
        
         //fprintf(stderr,"\nxxx-prompt_and_component-1 bytesT=%d",bytesT);
         if (blockset==0){    
            free(linknet); /*empty the list of linked nodes*/
            if ((linknet=(char*)calloc(bytesT,sizeof(char)))==NULL) outof_memory("linknet");
         }

         //fprintf(stderr,"\nxxx-prompt_and_component-2 bytesT=%d",bytesT);

         if (link_step==0) sprintf(textb[1],"step=nolimit");
         else if (link_step>0) sprintf(textb[1],"step=%d",link_step);
	 
         if (components=='i') sprintf(textb[0],"node %d, inputs, %s: ",m_r_node,textb[1]);
         else if (components=='o') sprintf(textb[0],"node %d, outputs, %s: ",m_r_node,textb[1]);
         else if (components=='e') sprintf(textb[0],"node %d, either, %s: ",m_r_node,textb[1]);
         else if (components=='a'){
	     if (jump_layout_only==1 || no_links==1) sprintf(textb[0],"node %d, allnodes(nolinks): ",m_r_node);
	     else sprintf(textb[0],"node %d, allnodes: ",m_r_node);
	     //sprintf(textb[0],"node %d, allnodes: ",m_r_node); //no need for nolinks as this is evident in he graph
	 }
         else if (components=='s'){
	   if (jump_layout_only==1 || no_links==1) sprintf(textb[0],"node %d, single(nolinks): ",m_r_node);
	   else sprintf(textb[0],"node %d, single: ",m_r_node);
	   //sprintf(textb[0],"node %d, single: ",m_r_node);
	 }      
	 if (blockset==1){
	    unsigned int this_startBlock,this_endBlock;
	    //correct block prompt,  start number 0 or 1
	    if (graph_type=='f' || (graph_type=='n' && jump_layout_only==1) ){ //jump-graph with or without links start=1 
	       this_startBlock=startBlock;
	       this_endBlock=endBlock;
            }         
	    else{   /*network and ibaf indices start=0*/
	       this_startBlock=startBlock-1;
	       this_endBlock=endBlock-1;
            }
            sprintf(textb[0],"node %d, Block %d-%d: ",m_r_node,this_startBlock,this_endBlock);
         }
	 outtext(textb[0]);
	 
	 if ((just_component==1 && components=='e')
	         || (just_fragment==1 && (components=='e' || components=='o' || components=='i'))){
	   char temp_link_step;
	    //fprintf(stderr,"\n1:link_step=%d",link_step);
	    temp_link_step=link_step;
	    
	    if (just_fragment==0) link_step=0;//keep link_step for just_fragments
	    
	    //fprintf(stderr,"\n2:link_step=%d",link_step);
	    //first capture full component for just-j to work, where other components suppressed
	    graph_in_out_components(components,link_step,most_recent_node);
	    //fprintf(stderr,"\nlnet");
	    //for (zu=node_no;zu>=1;zu--) fprintf(stderr,"%d",get_bit(linknet,zu));	    			     
            memmove(component_linknet,linknet,bytesT);
	    
	    /*fprintf(stderr,"\ncnet=");
	      for (zu=node_no;zu>=1;zu--) fprintf(stderr,"%d",get_bit(component_linknet,zu));*/
	    
	    link_step=temp_link_step;
	    
            if (blockset==0){ 
	       free(linknet); //empty the list of linked nodes for link_step>0 to work
               if ((linknet=(char*)calloc(bytesT,sizeof(char)))==NULL) outof_memory("linknet");
	       graph_in_out_components(components,link_step,most_recent_node);
	    }
	    
	    /*fprintf(stderr,"\n>net");
	      for (zu=node_no;zu>=1;zu--) fprintf(stderr,"%d",get_bit(linknet,zu));*/
	 }
	 
	 //else if (components=='i' || components=='i' || components=='o' || components=='a'){
	 //   graph_in_out_components(components,link_step,most_recent_node);
	 //}

	 else{
            graph_in_out_components(components,link_step,most_recent_node);
	    /*fprintf(stderr,"\n<<graph_in_out_components, comp=%c step=%d node=%d",
	      components,link_step,most_recent_node);*/
	 }   
         setcolor(white);
	 
         //drag prompts:
	 
         //outtext("drag - left button, tog drag-d"); changed July 2018
         if (quick_move==0) outtext("leftb-drag, PScript-P elstc/snap-d");
         else outtext("leftb-drag, PScript-P snap/elstc-d");
	 if (no_links==0) outtext(" gap-g");
	 
         moveto(xbox,gety+CHeight);
	 if (components=='s' && blockset==0) sprintf(textb[2]," ");
	 else sprintf(textb[2],"%s ","rot-x/X flip-h/v");
	 
	 //fprintf(stderr,"\ngraph_type=%c",graph_type);
	 if (graph_type=='n' || graph_type=='f' || graph_type=='a'){	   
	   if (components!='s' || blockset==1)
	        sprintf(textb[0],"inactive?-rightb first, %snodes-(/)/=/E links-{/} both-[/] just-j/J",textb[2]);//E is extra option
	   else sprintf(textb[0],"inactive?-rightb first, %snodes-(/)/= links-{/} both-[/] just-j/J",textb[2]);
	 }
	 else if (graph_type=='s'|| graph_type=='t'){
	    if (components=='s')
	         sprintf(textb[0],"inactive?-rightb first, %snodes-(/)/= just-j/J",textb[2]);
	    else sprintf(textb[0],"inactive?-rightb first, %snodes-(/)/=/E links-{/} both-[/] just-j/J",textb[2]);
	 }
         else if (jump_layout_only==1 || no_links==1) //jump-graph with nolinks, treated as net-graph
            sprintf(textb[0], 
			      "inactive?-rightb first, %snodes-(/)/= links-{/} both-[/]",textb[2]);
	 
         else printf(textb[0],"inactive?-rightb first, %snodes-(/)/=/E links-{/} both-[/] just-j/J",textb[2]);
         //else sprintf(textb[0],"inactive?-rightb first, %s",textb[2]);
	 
         outtext(textb[0]);

         moveto(xbox,gety+CHeight);
	 
	 if (jump_layout_only==1 || no_links==1){
	    if (components=='a') sprintf(textb[0],"");
            else if (blockset==0) sprintf(textb[0],"block-B Label-L/+");
	    else if (blockset==1) sprintf(textb[0],"exit-block-B");
	    outtext(textb[0]);
	 }
         //if (no_links==0){
	 else{
	    if (components=='i' || components=='o' || components=='e'){   
	       sprintf(textb[0],
                  "Lnk%d:cut/restore-c/r Lnks%d-%d:cut/add/restore-C/A/R net-#",
                            m_r_node,m_r_node,p_node);
	    }
	    else if (components=='a') sprintf(textb[0],"net-#");
            else if (components=='s'){
              if (blockset==0) sprintf(textb[0],"block-B Label-L/+ net-#");
	      else if (blockset==1) sprintf(textb[0],"exit-block-B net-#");
	    }  
            //else sprintf(textb[0],"net-#");
	    outtext(textb[0]);
         }
         /*else{
            if (blockset==0) sprintf(textb[0],"block-B Label-L/+ net-#");
	    else if (blockset==1) sprintf(textb[0],"exit-block-B");
	    
	    outtext(textb[0]);
	 }*/
	 
         moveto(xbox,gety+CHeight);
         if (no_links==0){
            outtext(
            "step-(1-9) nolimit-0 single-s in/out/either-i/o/e all-a exit-q:");
         }
         else outtext("single-s all-a exit-q:");
	 
         //show just-j/J status inset box
	 setcolor(lightred);
	 if (just_component==1){
	       inset_prompt_box(1,3," j",'d');
	 }
	 else if (just_fragment==1){
	       inset_prompt_box(1,3," J",'d');
	 }
         setcolor(white);
	 
	 current_text_size=this_text_size;
         # if __UNIX__
            free_fonts();
            setup_fonts(current_text_size);
         # endif
}

/************** define a block, or slice in 2d or 3d *****************/
char block_or_slice(char components,char blockset,unsigned int first,unsigned int last){

             unsigned int *ijh,*ijh_in,*ijh_def_low,*ijh_def_high,
	          temp_last,start,end,zi,
                  first_ii,first_jj,first_hh,
                  last_ii,last_jj,last_hh,
	          low_ii,high_ii,low_jj,high_jj,low_hh,high_hh,
	          this_ii,this_jj,this_hh;
             signed int z,zz,xbox,bytesT;
             char range_type;

	               this_text_size=current_text_size;
                       # if __UNIX__ 
                          free_fonts();
                          setup_fonts(start_pointsize);//to preserve normal prompt font
                       # endif

			  //if (graph_type=='n') bytesT=bytesL;
			  //else if (graph_type=='s'|| graph_type=='t') bytesT=(signed int)ceil((double)(node_no+1)/8);
			  //else bytesT=(signed int)ceil((double)node_no/8);

		       bytesT=(signed int)ceil((double)(node_no+1)/8);
		       //fprintf(stderr,"\n bytesT=%d",bytesT);
			  
                       free(linknet); /*empty the list of linked nodes*/
                       if ((linknet=(char*)calloc(bytesT,sizeof(char)))
				    ==NULL) outof_memory("linknet");
             
                       if ((ijh=(unsigned int *)calloc(3,sizeof(unsigned int)))
				   ==NULL) outof_memory("ijh");
                       if ((ijh_in=(unsigned int *)calloc(3,sizeof(unsigned int)))
				   ==NULL) outof_memory("input_ijh");
                       if ((ijh_def_low=(unsigned int *)calloc(3,sizeof(unsigned int)))
				   ==NULL) outof_memory("input_def_low");
                       if ((ijh_def_high=(unsigned int *)calloc(3,sizeof(unsigned int)))
				   ==NULL) outof_memory("input_def_high");

                       /*make sure first is smaller than last, else swap*/
                       if (first>last){
			  temp_last=last;
                          last=first;
                          first=temp_last;
                       }
                       
			 
                       //if (graph_type=='n' || graph_type=='s'|| graph_type=='t'){                       
		       if  ((graph_type=='s' || graph_type=='t' || (graph_type=='n') && jump_layout_only==0)){
                          start=0;
                          end=node_no-1;                          
                          first--;
			  last--;
			  if (oned) range_type=1;
			  else if (twod) range_type=2;
                          else if (threed) range_type=3;
		       }
                       else{ //for jump-graph
			  start=1;
                          end=node_no;
                          range_type=1;
		       }
		       
                       xbox=draw_prompt_box(4);
		       
		       if (no_links || jump_layout_only)  sprintf(textb[0],"define 1d block:");
                       else if ((graph_type=='n' && jump_layout_only==0) && (threed || twod)){
                          if (threed) sprintf(textb[0],
                             "3d network: define block: 1d-1 3d-(def):");
                          else if (twod) sprintf(textb[0],
                             "2d network: define block: 1d-1, 2d-(def):");
                       }
                       /*else sprintf(textb[0],"graph_type(%c) jump_layout_only=%d, define 1d block:",
			 graph_type,jump_layout_only);*/  //for jump-graph

		       else sprintf(textb[0],"define 1d block:");				    
		       
                       outtext(textb[0]);
                       input_string(1,0);
                       if (is[0]=='q') goto quit_b;
		       
                       if (atoi(is)==1) range_type=1;

                       moveto(xbox,gety+CHeight);

                       if (range_type==1){ 
                          first_ii=first;
                          last_ii=last;
                       }
                       else if (range_type==2){
                          first_ii=first%i2d;
	                  first_jj=first/i2d; 
                          last_ii=last%i2d;
	                  last_jj=last/i2d;                            
                       }                                	
                       else if (range_type==3){
                          first_ii=first%i3d;
	                  first_jj=first%(i3d*j3d)/i3d;
                          first_hh=first/(i3d*j3d);
                          last_ii=last%i3d;
	                  last_jj=last%(i3d*j3d)/i3d;
                          last_hh=last/(i3d*j3d);
		       }                                   

                       if (range_type==1){
                             unsigned int low_v,high_v;
                             low_v=high_v=lineL-1;                       
                             if (graph_type=='n' && jump_layout_only==0) sprintf(textb[0], 
                                "%dd block (%d-%d, def %d-%d), ",
                                      range_type,start,end,first_ii,last_ii);
                             else sprintf(textb[0], 
                                "%dd block (%d-%d, def %d-%d), ",
                                      range_type,start,end,first_ii,last_ii);
                             outtext(textb[0]);
                             moveto(xbox,gety+CHeight);
                             outtext("low:");
                             input_string(5,0);
                             if (is[0]=='q') goto quit_b;
                             else if (is[0]!=13 && atoi(is)>=start && atoi(is)<=end) low_v=atoi(is);
                             else low_v=first_ii;
                             moveto(xbox,gety+CHeight);
                             outtext("high:");
                             input_string(5,0);
                             if (is[0]=='q') goto quit_b;
                             else if (is[0]!=13 && atoi(is)>=start && atoi(is)<=end) high_v=atoi(is);
                             else high_v=last_ii;
                             /*make sure first co-ord is smaller than last, else swap*/
                             if (low_v>high_v){
			           temp_last=high_v;
                                   high_v=low_v;
                                   low_v=temp_last;
                             }
			     
			     for (zi=low_v;zi<=high_v;zi++){
			       //if (graph_type=='f' || jump_layout_only==0) set_bit1(linknet,zi+1);
			       //else set_bit1(linknet,zi);                              

			       if (graph_type=='s'|| graph_type=='t' ||
				     (graph_type=='n' && jump_layout_only==0)) set_bit1(linknet,zi+1);
			       else set_bit1(linknet,zi);
			       
                             }           
                       } 
                       
                       else if (range_type==2){                        
                             ijh[0]=i2d;
                             ijh[1]=j2d;
                             ijh_def_low[0]=first_ii;
                             ijh_def_low[1]=first_jj;
                             ijh_def_high[0]=last_ii;
                             ijh_def_high[1]=last_jj;
                             
                             sprintf(textb[0],
	                      "%dd block (this=%d,%d max=%d,%d)",
                                range_type,first_ii,first_jj,i2d-1,j2d-1);
                             outtext(textb[0]);
                             for (zz=1;zz<=2;zz++){ 
                                moveto(xbox,gety+CHeight);    
                                if (zz==1) sprintf(textb[0],
                                      "low corner (def %d,%d)",first_ii,first_jj);
                                else if (zz==2) sprintf(textb[0],
                                      "high corner (def %d,%d)",last_ii,last_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)>=start && 
                                      atoi(is)<=ijh[z]-1) ijh_in[z]=atoi(is);
                                   else{ 
                                      if (zz==1) ijh_in[z]=ijh_def_low[z];
                                      else if (zz==2) ijh_in[z]=ijh_def_high[z];
                                   }
                                }
			        if (zz==1){
                                   low_ii=ijh_in[0];
                                   low_jj=ijh_in[1];         
                                } 
                                else if (zz==2){
                                   high_ii=ijh_in[0];
                                   high_jj=ijh_in[1];
                                }
			     }
                             /*make sure first co-ord is smaller than last, else swap*/
                             if (low_ii>high_ii){
			           temp_last=high_ii;
                                   high_ii=low_ii;
                                   low_ii=temp_last;
                             }
                             if (low_jj>high_jj){
			           temp_last=high_jj;
                                   high_jj=low_jj;
                                   low_jj=temp_last;
                             }  
                             first=i2d*low_jj + low_ii;
                             last=i2d*high_jj + high_ii;
                             /*fprintf(stderr,"\nfirst=%d last=%d",first,last);*/
                             for (zi=first;zi<=last;zi++){
                                 this_ii=zi%i2d;
                                 this_jj=zi/i2d;
                                 if (this_ii<low_ii || this_ii>high_ii ||
                                    this_jj<low_jj || this_jj>high_jj) continue;
                                 else set_bit1(linknet
					       ,zi+1);
                             }
                       } 
                       else if (range_type==3){                          
                             ijh[0]=i3d;
                             ijh[1]=j3d;
                             ijh[2]=h3d;

                             ijh_def_low[0]=first_ii;
                             ijh_def_low[1]=first_jj;
                             ijh_def_low[2]=first_hh;
                             ijh_def_high[0]=last_ii;
                             ijh_def_high[1]=last_jj;
                             ijh_def_high[2]=last_hh;
                                                 
                             sprintf(textb[0],
	                      "%dd block (this=%d,%d,%d max=%d,%d,%d)",
                                range_type,first_ii,first_jj,first_hh,
                                                   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],
                                     "low corner (def %d,%d,%d)",
                                              first_ii,first_jj,first_hh);
                                else if (zz==2) sprintf(textb[0],
                                   "high corner (def %d,%d,%d)",
                                       last_ii,last_jj,last_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);
                                   else{
                                      if (zz==1) ijh_in[z]=ijh_def_low[z];
                                      else if (zz==2) ijh_in[z]=ijh_def_high[z];
                                   }
                                }
			        if (zz==1){
                                   low_ii=ijh_in[0];
                                   low_jj=ijh_in[1];
                                   low_hh=ijh_in[2];
                                } 
                                else if (zz==2){
                                   high_ii=ijh_in[0];
                                   high_jj=ijh_in[1];
                                   high_hh=ijh_in[2];
                                }  
			     }
                             
                             /*fprintf(stderr,
                                 "\n1:low_ii=%d low_jj=%d low_hh=%d high_ii=%d high_jj=%d high_hh=%d",
				 low_ii,low_jj,low_hh,high_ii,high_jj,high_hh);*/
			     
                             //make sure first co-ord is smaller than last, else swap
                             if (low_ii>high_ii){
			           temp_last=high_ii;
                                   high_ii=low_ii;
                                   low_ii=temp_last;
                             }
                             if (low_jj>high_jj){
			           temp_last=high_jj;
                                   high_jj=low_jj;
                                   low_jj=temp_last;
                             }
                             if (low_hh>high_hh){
			           temp_last=high_hh;
                                   high_hh=low_hh;
                                   low_hh=temp_last;
                             }
                             first=(i3d*j3d*low_hh) + (i3d*low_jj) + low_ii;
                             last=(i3d*j3d*high_hh) + (i3d*high_jj) + high_ii;
                             for (zi=first;zi<=last;zi++){
                                 this_ii=zi%i3d;
                                 this_jj=zi%(i3d*j3d)/i3d;
                                 this_hh=zi/(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) continue;
                                 else set_bit1(linknet,zi+1);
                             }
                                    
                       }
		       
                       //fprintf(stderr,"\n linknet="); //show the block
                       //for (zi=start;zi<=end;zi++)fprintf(stderr,"%d",get_bit(linknet,zi));
		       memmove(component_linknet,linknet,bytesT);//for isolating a block with just_fragments

                       startBlock=endBlock=0;
                       for (zi=start;zi<=end;zi++){
			  if (get_bit(linknet,zi)==1){ 
                              startBlock=zi;
                              break;
                          }
                       }
                       for (zi=end;zi>=startBlock;zi--){
			  if (get_bit(linknet,zi)==1){ 
                              endBlock=zi;
                              break;
                          }
                       }
                       
		       //fprintf(stderr,"\n%d .. %d",startBlock,endBlock);
                      quit_b:
                       if (is[0]=='q'){ //to quit and return to "single"
			   blockset=0;
			   components='s';
			   range_type=0;
			   //fprintf(stderr,"\nrange_type=%d blockset=%d components=%c",range_type,blockset,components);
		       } 
		       
                        current_text_size=this_text_size;
                        # if __UNIX__
                          free_fonts();
                          setup_fonts(current_text_size);
                        # endif
		       
                        free(ijh);
                        free(ijh_in);
                        free(ijh_def_low); 
                        free(ijh_def_high); 
                        return(range_type);                    
}

/************** disconnect a node  ******************/
void disconnect_node(char what,
	    unsigned long *node_outputs, unsigned long *node_inputs,
            char components, unsigned int poss, unsigned int prev_node){
  unsigned int zu,z;

      if (what=='#'){//in case links were cut or added --- restore original
	 suppress_u_links=0;  //incase linke were suppressed
         for (zu=node_no;zu>=1;zu--) memmove(basinjumps[zu],b_j[zu],
                                      (node_no+1)*sizeof(unsigned int));	 
      } 
      
      else if (what=='g'){ /*gap node: can't transmit info*/
	              /*if no outside outputs, or no outside inputs*/
            /*recalculate node_outputs, node_inputs*/
	    for (zu=1;zu<=node_no;zu++){
	       node_outputs[zu]=0;
               node_inputs[zu]=0;
            }            

            for (zu=1;zu<=node_no;zu++){
               for (z=1;z<=node_no;z++){
		  if (z!=zu ){ /*don't count self outputs*/		     
                     node_outputs[zu]+=basinjumps[zu][z];
                     node_inputs[zu]+=basinjumps[z][zu];
                  }
	       }
            }
            /*fprintf(stderr,"\n before");
            for (z=1;z<=node_no;z++){
               if (graph_type=='n')
                 fprintf(stderr,"\n %d: out=%d in=%d",z-1,node_outputs[z],node_inputs[z]);
               else  fprintf(stderr,"\n %d: out=%d in=%d",z,node_outputs[z],node_inputs[z]);
	    }*/
            for (zu=node_no;zu>=1;zu--){ /*output links * input links*/
               if (node_outputs[zu]==0 || node_inputs[zu]==0){
                  for (z=node_no;z>=1;z--){
                      basinjumps[zu][z]=0; /*cut outputs*/
                      basinjumps[z][zu]=0; /*cut inputs*/
                  }
	       }
            }            
      } 
      else {
         if (components=='i' || components=='e'){
	    for (zu=node_no;zu>=1;zu--){
	       if (what=='c'){
	          basinjumps[zu][poss]=0; /*cut inputs*/
	       }    
               else if (what=='r') /*restore inputs*/ 
	          basinjumps[zu][poss]=b_j[zu][poss];            
            }         
         }
         if (components=='o' || components=='e'){
	    for (zu=node_no;zu>=1;zu--){
	       if (what=='c'){
	         basinjumps[poss][zu]=0; /*cut outputs*/
	       }  
               else if (what=='r') /*restore outputs*/
                  basinjumps[poss][zu]=b_j[poss][zu];
            }
         }
      }	       
}

/*************** cut links between pairs of nodes  *******************/
void node_pair_link(char what,
            char components, unsigned int poss, unsigned int prev_node){
  
      if (components=='i' || components=='e'){ 
	     if (what=='C') basinjumps[prev_node][poss]=0; /*cut input*/ 
             else if (what=='A'){ /*add input*/ 
	       if (basinjumps[prev_node][poss]==0)
		     basinjumps[prev_node][poss]=1;
             }
             else if (what=='R') /*restore input*/ 
	       basinjumps[prev_node][poss]=
                        b_j[prev_node][poss];
      
      }
      if (components=='o' || components=='e'){  
	     if (what=='C') basinjumps[poss][prev_node]=0; /*cut output*/
             else if (what=='A'){ /*add input*/ 
	       if (basinjumps[poss][prev_node]==0)
		     basinjumps[poss][prev_node]=1;
             }
             else if (what=='R') /*restore outputs*/
                basinjumps[poss][prev_node]=
                            b_j[poss][prev_node];
         
      }
}

/************** show all input or output links to cell ******************/
void graph_in_out_components(char components, char link_step,
                                          unsigned int poss){

  char *this_sweep,*genedone,linkfound;
  signed int t_step=1,bytesT;
  unsigned int startposs,
                 zu,zu1,tot_so_far=0,tot_before=0;           

     //bytesT=1+(signed int)ceil((double)node_no/8);
     bytesT=(signed int)ceil((double)(node_no+1)/8);
     
     //fprintf(stderr,"\nnode_no=%d bytesT=%d",node_no,bytesT);
     if ((genedone=(char*)calloc(bytesT,sizeof(char)))
				==NULL) outof_memory("genedone");
     if ((this_sweep=(char*)calloc(bytesT,sizeof(char)))
				==NULL) outof_memory("this_sweep");
             
      /*mark all input genes to startpos*/
      startposs=poss;

      if (components=='a'){ /*set whole graph as component*/
	 for (zu=node_no;zu>=1;zu--) set_bit1(linknet,zu);
         goto endFunc;
      }
      
      /*fprintf(stderr,"\njump: pos=%d",startposs);*/    
      if (components=='i' || components=='e'){ /*show inputs*/ 
         for (zu=node_no;zu>=1;zu--){
            if (basinjumps[zu][startposs]>0)
               set_bit1(linknet,zu);
	       tot_so_far+=1;
         }
      }
      if (components=='o' || components=='e'){ /*show outputs*/
	 for (zu=node_no;zu>=1;zu--){
            if (basinjumps[startposs][zu]>0)
               set_bit1(linknet,zu);
	       tot_so_far+=1;
         }
      }
      /*fprintf(stderr,"\ntotal=%d,startposs=%d ",tot_so_far,startposs);
      for (zu=node_no;zu>=1;zu--){
        //if (basinjumps[zu][startposs]>0 || basinjumps[startposs][zu]>0) fprintf(stderr,"%d=%d ",zu,get_bit(linknet,zu));
	fprintf(stderr,"%d",get_bit(linknet,zu));
      }*/
	
      t_step=2;
      if (link_step==1) goto endFunc; //range of links to be included

      while(1){          
         linkfound=0;        
         for (zu=node_no;zu>=1;zu--){                           
            if (get_bit(genedone,zu)==0 && get_bit(linknet,zu)==1){
	       linkfound=1;
	       set_bit1(genedone,zu);
               if (components=='i' || components=='e'){  /*inputs*/
                  for (zu1=node_no;zu1>=1;zu1--){
                     if (basinjumps[zu1][zu]>0)
                           set_bit1(this_sweep,zu1);	    
                  }   
               } 
               if (components=='o' || components=='e'){  /*outputs*/ 
                    for (zu1=node_no;zu1>=1;zu1--){
                        if (basinjumps[zu][zu1]>0)
                              set_bit1(this_sweep,zu1);	    
                    }   
               }
	    }
            else continue;
         }

         for (zu=node_no;zu>=1;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=node_no;zu>=1;zu--){                   
            if (get_bit(linknet,zu)==1) tot_so_far+=1;
         }
	 
         if (link_step>0 && t_step==link_step){ //to limit step distance
	     //fprintf(stderr,"\nlink_step=%d t_step=%d",link_step,t_step);
	     goto endFunc;
	 }
	 
	 //if (linkfound==0 || (graph_type!='s' && tot_before*2==tot_so_far)){  //this caused
         if (linkfound==0){
	    //for stg attractor drag sometimes truncated ??? but seems to work now
	    goto endFunc;
	 }
         /*if (linkfound==1 && tot_before<tot_so_far) t_step+=1;*/
         t_step+=1;
      }
    endFunc:
      
      //show data
      /*tot_so_far=0;      
      fprintf(stderr,"\n");
      for (zu=node_no;zu>=1;zu--){ //show the bits
	 fprintf(stderr,"%d",get_bit(linknet,zu));
      }
      fprintf(stderr,"\n");
      for (zu=node_no;zu>=1;zu--){ //show node numbers in fragment
	 if (get_bit(linknet,zu)==1){
	     if (graph_type=='s' || graph_type=='t' || (graph_type=='n' && jump_layout_only==0))
	         fprintf(stderr,"%d ",zu-1);
	     else fprintf(stderr,"%d ",zu);
	     tot_so_far++; //count node in fragment
	 }
      }
      //print the states in the active fragment
      fprintf(stderr,"\n-----link_step=%d t_step=%d tot_so_far=%d-----\n",link_step,t_step,tot_so_far);
      */
      poss=startposs;
      free(genedone);
      free(this_sweep);               
}


/****** compute link angle and absolute angle (<90) from 2 points *******/ 
void compute_link_angle(signed int x1, signed int y1,
                        signed int x2, signed int y2){ 
  float ratio;
       
      /* rads to degs *57.2958, deg to rads *0.0174533 */  
      if (x1==x2){
         if (y1>y2) linkangle=(float)(PI/2);
         else if (y1<y2){
            linkangle=(float)(3*PI/2);
         }
         abs_angle=(float)(PI/2);
      }
      else if (y1==y2){
         if (x1>x2) linkangle=(float)PI;
         else if (x1<x2) linkangle=(float)(2*PI);
         abs_angle=0; 
      }
      
      else {
	 ratio=(float)fabs((float)(y1-y2)/(float)(x1-x2));       
	 abs_angle = (float) atan (ratio);
         /*

  PI/2-PI    y2<y1  |   y2<y1    0-PI/2
  PI-h       x2<x1  |   x2>x1 ...ok
           ---------|--------
  PI-3*PI/2  y2>y1  |   y2>y1
  PI+h       x2<x1  |   x2>x1  3*PI/2 - 2*PI-h  */

         if      (x1<=x2 && y1>y2) linkangle=abs_angle; 	 
         else if (x1>x2 && y1>=y2) linkangle=(float)PI-abs_angle;
         else if (x1>=x2 && y1<y2) linkangle=(float)PI+abs_angle;        
         else if (x1<x2 && y1<=y2) linkangle=(float)(2*PI)-abs_angle; 
      }     
}  

/********************** reset nodes size Aug 2035*********************************/
void reset_nodesize(void){
  unsigned int zw;
  double this_f,av_f;
  
           for (zw=node_no;zw>=1;zw--){
		  s_node_size[zw]=c_scale;
		  //fprintf(stderr,"\n%d: c_scele=%f netnodesize[%d]=%d",zw,c_scale,zw,netnodesize[zw]);
		  if (graph_type=='t' &&  netnodesize[zw]==255){ //255 netnodesize is unsigned char
		         m_node_size[zw]=c_scale/2; //for isolated equiv trees
		  }	 
		  else if (no_links==1 && jump_layout_only==0) m_node_size[zw]=c_scale;
		  else{
		        if (graph_type=='t'){
		           //otherwise default nodes for can be too big for single or special cases
			   if (m_space<=255) av_f= 255 / node_no;
			   else av_f= m_space / node_no;
			   //fprintf(stderr,"\n%f=%f/%d",av_f,m_space,node_no);
                        }
		        else av_f= m_space / node_no;
			
		        if (graph_type=='f' || jump_layout_only) this_f=(double)m_basin_volume[zw];
		        else if (graph_type=='a') this_f=(double)histnodesize[zw];
		        else if (graph_type=='s' || graph_type=='t'){
			   if (netnodesize[zw]==0) this_f=.5; //give leaf states small scale size
			   else this_f=(double)netnodesize[zw];
			}      
		        else if (graph_type=='n'){			   
			    if (network_outputs==1) this_f=(double)m_att_period[zw]; //outputs
			    else this_f=(double)netnodesize[zw];
			}  
		        m_node_size[zw]=c_scale*(float)pow(this_f/av_f,.5); //inputs k
			//if (m_node_size[zw]<vgax(2.5)) m_node_size[zw]=vgax(2.5);
			
			if (m_node_size[zw]<vgax(1)) m_node_size[zw]=vgax(1);
			/*fprintf(stderr,"\n%d:%f this_f=%f netnodesize=%d",
			  zw,m_node_size[zw],this_f,netnodesize[zw]);*/
		  }
            }

}  
/*************************************************************************/
