/* EI_EXCH looks for the all elementary modes in all combinations of external/internal metabolites */
/* using algorithms of METATOOL // 20.06.2002 */

/* ************************************************************************************ */
/* METATOOL: TO ANALYZE METABOLIC NETWORKS ******************************************** */
/* WRITTEN BY THOMAS PFEIFFER, extensive worked by F. Moldenhauer ********************* */
/* COMPILE WITH GCC, Microsoft C 6.0 or Borland C 5.0********************************** */
/* ************************************************************************************ */

/* ######################## */
/* fix by HMS to generate unreduced elemenary modes. */
/* Changed lines marked by HMS######### */
/* 26.06.2000, change in the elementary modes matrix section, */
/* gives out the unreduced matrix instead of reduced subset matrix  */ 

/* INCLUDED FILES ********************************************************************* */
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <float.h>
#include <time.h>

#define AA 524288L
#define BB 16384

#if (defined DOS || defined _DOS || defined WIN32 || defined _WIN32)
  #include <conio.h>
  #include <malloc.h>
  #include<sys\types.h>  // for time measurement
  #include<sys\timeb.h>
#else 
  #define getch() getchar()
#endif

#ifndef _MAX_PATH
 #define _MAX_PATH 256
#endif
#ifdef sun
 #define powl pow
 #define floorl floor
 #define ceill ceil
 #define fabsl fabs
#endif

#ifdef sun
  #define long_double double
#else 
  #define long_double long double
#endif
#define NN	  501    // maximal number of metabolites

int   mean_path_length(struct mat *vmode);
float m_pathway_length;
void addressed(void *p, char *s, int a )
{
 if(p==NULL)
 {
  printf("\nNot enough memory: %s\nProgramm prematurely finished.\n", s );
  getch(); exit(1);
 }
 if(!a)
 {
  printf("\namount for allocation is zero : %s\nProgramm prematurely finished.\n", s );
  getch(); exit(1);
 }
}

long_double rund ( long_double value, int dezimale )
{
 long_double unten, oben, rest;

 value *= powl(10, dezimale);
 unten = floorl( value );
 oben  = ceill( value );
 rest = value - unten;

 if( rest == 0.5 )
    if( ((int)unten%2) ) return(oben/powl(10, dezimale));
    else return( unten/powl(10, dezimale) );
 if( rest > 0.5 ) return ( oben/powl(10, dezimale) );
 if( rest < 0.5 ) return ( unten/powl(10, dezimale) );
 return -1.0;
} // rund

/* MAKROS ***************************************************************************** */
#define TXT 200

/* STRUCT DECLARATIONS **************************************************************** */
struct enc    {int rev; int key; int consumed; int built; int reactions; char txt[TXT]; struct enc *next;};
struct vector {int row; long_double *head;};
struct mat    {int row; int col; long_double **head;};

/* DECLARATION of FUNCTIONS *********************************************************** */
int  compstr (int m, char t1[100], char t2[100]);
long_double ggt (long_double u, long_double v);
void ggt_matrix (struct mat *v);
void read_comment( FILE *fp_in );
int detect_double_declared_metabolites( struct enc *metlist );
int control_modi (struct mat *m, FILE *savefile, struct enc *enzlist);
int control_condition7 (struct mat *m, int ii, long_double *rev1, int *r01);
double VarVect_Init( int *nx, int* VarVect, const int Anz_Var, struct vector um );
int foutput(FILE *fout, FILE *fcomb, struct mat* unreduced1, int* VarVect, struct enc *metlist,
            int nx, const unsigned long ii, int *no_em, struct mat* unreduced, int count_enz, const ei_um);
int foutput_mets( int* VarVect1, struct enc *metlist, int nx1, unsigned long int ulii );
int count_enzymes( struct mat* vmode );
int VarVect_Init_1( FILE* fcomb, int *nx, int *nx1, int* InitVect, const int Anz_Var,
                    struct vector um, int *VarVect, int *VarVect1, unsigned long *ulii,
                    char* res0, struct vector ei);


// global variables that it is possible to scan metabolites and enzymes containing whitespaces
struct vector *branch; /* contains the number of intern metabolites at branch points */
char **metabolites; int* mets_cumul; int met_counter;
char **enzyme_names; int enzyme_counter;
/* FUNCTIONS ************************************************************************** */
/* ************************************************************************************ */
/* 1. for struct enc ****************************************************************** */
/* ************************************************************************************ */
/* 1.1 insert element ************************* */
struct enc *ins (struct enc *t1, int r, int k, char t[TXT])
{
 struct enc *x;
 int i;
  x= (struct enc*) calloc (1, sizeof (struct enc)); addressed( x, "x not allocated", 1);
  x->key=k; x->rev=r;
  for (i=0;i<TXT;i++) x->txt[i]=t[i];
  x->next=t1->next;
  t1->next=x;
 return x;
} // ins
/* 1.2 function get enzlist ******************* */
int my_fscanf_enz_names(FILE *s, char* tx);
struct enc *getenzlist (FILE *s)
{
 struct enc *enzlist, *eac, *ez;
 char tx[TXT];

 enzlist=(struct enc*)calloc(1, sizeof(struct enc )); addressed( enzlist, "enzlist not allocated", 1);
 ez=(struct enc*)calloc(1, sizeof(struct enc));            addressed( ez, "ez not allocated", 1);
 enzlist->next=ez; enzlist->key=0;
 ez->next=ez; ez->key=0; eac=enzlist;

 read_comment(s);
 fscanf(s,"%s",tx);

  	   if ((tx[0]!='-')&&(tx[1]!='E')) 
        printf ("ERROR IN FILE!");
  	   while (!feof(s))
    	  {
    	  my_fscanf_enz_names(s, tx); // fscanf(s,"%s",tx); 
          if (tx[0]=='-') break;
    	  eac=ins(eac,0,(eac->key)+1,tx);
    	  }	
  	   while (!feof(s))
    	  {
    	  my_fscanf_enz_names(s, tx); // fscanf(s,"%s",tx); 
         if (tx[0]=='-') break;
    	  eac=ins(eac,1,(eac->key)+1,tx);
    	  }
  	   return enzlist;
} // getenzlist

// my own strrev which does not exsist under UNIX
char* strrev (char* tx)
{
  int len, i;
  char help[TXT];
  len=strlen(tx)-1;
  for(i=0; i<=len; i++)
    help[i]=tx[len-i];
  help[i]='\x0';
  for(i=0; i<=len; i++)
    tx[i]=help[i];
  return tx;
} // strrev

void mets_which_differ( struct enc *metlist, int mrow )
{
  int i, j, yn;
  struct enc *help;
  for( i=0; i<met_counter; i++ )
  {
   help = metlist->next; yn=1;
   for( j=0; j<mrow; j++ )
   { 
    if( strcmp(*(metabolites+i), help->txt)) yn=1;
    else {yn=0; break;}
    help=help->next;
   }
   if( yn ) 
     printf("\n->%s<- not found in -METINT -METEXT declarations", *(metabolites+i));
  }

} // mets_which_differ

void fout_reactions (FILE *fout, struct enc *enzlist)
{
  struct enc *help;
  help = enzlist->next;
  fprintf(fout, "\n");
  do
  {
    fprintf( fout, "%s ", help->txt);
    help=help->next;
  }while( help->next != help);

  fprintf(fout, "\n"); // fflush(fout);
} // fout_reactions

void fout_branches (FILE *fout, struct enc *metlist)
{
  int i;
  struct enc *help;
  help = metlist->next;
  fprintf(fout, "\n");
  fprintf(fout, "-> Branch metabolites are : ");
  for( i=0; i<branch->row; i++ )
  {
    if( *(branch->head+i) )
      fprintf( fout, "%s ", help->txt);
    help=help->next;
  }
  fprintf(fout, "\n");
  help = metlist->next;
  fprintf(fout, "\n-> No branch metabolites are : ");
  for( i=0; i<branch->row; i++ )
  {
    if( !*(branch->head+i) )
      fprintf( fout, "%s ", help->txt);
    help=help->next;
  }
  fprintf(fout, "\n");
} // fout_branches 

// format formatstring for double numbers
int formatting( char *format, long_double **ptab, int rn, int cn )
{
#ifdef sun
  char *s1;
  char ns[25];
  long double hd;
  char *pchar;
#endif
  char *number_string;
  char string[25];
  int i, j, max=0;
  long double num;
  int dec, sign, ndig = 24;

  /* a negative number */
  for( i=0; i<rn; i++ )
  {
    for( j=0; j<cn; j++ )
    {
     if(*((*(ptab+i))+j) == (int)-0.0 ) *((*(ptab+i))+j)=(int)0.0; // for deleting minus sign
     num = (long double) *(*(ptab+i)+j);
#ifdef sun
    s1 = qfconvert(&num, ndig, &dec, &sign, &ns[0]);
    number_string = ns; //s1;
#else
     number_string = fcvt((double/*FM 18.09.2000*/)num, ndig, &dec, &sign);
#endif
     max = ( ((dec+sign) > max) ? (dec+sign) : max );
    }
  }
  strcpy( format, "%" );
  // itoa(max, string, 10 ); // itoa is not available at UNIX machines
#ifdef sun
  hd = (int)max;
  pchar = qgconvert(&hd, 24, 1, string );
  strcpy( string, pchar );
#else
  gcvt(max, 24, string);
#endif

  strcat( format, string );
  // strcat( format, "0lf " ); // No full stop for Microsoft C !!!! Only god knows why !!!
  // printf("Formatstring = %s", format ); // i=getchar();
  format[strlen(format)-1]='\x0';
  return 0;
} // formatting

int longer_name_found(FILE *s, char* static_tx0);
// compare tx-strings with those of *(metabolites+i),
// concatenate the strings while there is an agreement, otherwise exit(1)
int my_fscanf(FILE *s, char* tx)
{
 long int fposition; int i, trial=1; char tx1[TXT], tx0[TXT]; static char static_tx0[TXT];

 fposition=ftell(s);
 *tx='\x0'; fscanf(s,"%s",tx1);
 strcpy(tx0, tx1);
 do{
   if( strlen(tx)+strlen(tx1)>=TXT && trial==1 ) 
   {fseek(s, fposition, SEEK_SET); strcpy(tx, static_tx0); trial=2; fscanf(s,"%s",tx0);strcat(tx," ");strcat(tx, tx0);}
   else if( strlen(tx)+strlen(tx1)>=TXT && trial==2 ) 
   {printf("\nMetabolite -> %s <- not found in the stoichiometric equations!\n\nProgram prematurely terminated.\nPlease press ENTER", tx0); getch(); exit(1);}
   else if(!strlen(tx))
    strcat(tx, tx1);
   else 
    {strcat(tx," "); strcat(tx, tx1);}
   for(i=0; i<met_counter; i++)
   { if(!strcmp(*(metabolites+i), tx)) /* if found */ 
     {strcpy(static_tx0, tx); 
        if(!strcmp(static_tx0, tx0))
          { if(longer_name_found(s, static_tx0)) strcpy(tx, static_tx0); return 0;}
        else 
          { if(longer_name_found(s, static_tx0)) strcpy(tx, static_tx0); return 1;}
     }
   }
   if (tx[0]=='-') return 0;
   fscanf(s,"%s",tx1);
 }while(1);
} // my_fscanf

int longer_name_found(FILE *s, char* static_tx0)
{
 long int fposition; int i, trial=1; char tx1[TXT], tx0[TXT];
 char tx[TXT]={""}; 

 fposition=ftell(s);
 fscanf(s,"%s",tx1);
 strcpy(tx, static_tx0);
 strcpy(tx0, tx1);
 do{
   if( strlen(tx)+strlen(tx1)>=TXT && trial==1 ) 
   {fseek(s, fposition, SEEK_SET); strcpy(tx, static_tx0); trial=2; fscanf(s,"%s",tx0);strcat(tx," ");strcat(tx, tx0);}
   else if( strlen(tx)+strlen(tx1)>=TXT && trial==2 )
   {fseek(s, fposition, SEEK_SET); return 0; /* printf("\nMetabolite -> %s <- not found in the stoichiometric equations!\n\nProgram prematurely finished.\nPlease press ENTER", tx0);getch();  fclose(s); exit(1);*/}
   else if(!strlen(tx))
    strcat(tx, tx1);
   else 
    {strcat(tx," "); strcat(tx, tx1);}
   for(i=0; i<met_counter; i++)
   { if(!strcmp(*(metabolites+i), tx)) /* if found */ 
     {strcpy(static_tx0, tx);
        if(!strcmp(static_tx0, tx0))
          { return 0; }
        else 
          return 1;
     } else;
   }
   if (tx[0]=='-')
        return 0;
   fscanf(s,"%s",tx1);
 }while(1);
} // longer_name_found

int my_fscanf_enz_names(FILE *s, char* tx)
{
 long int fposition; int i, trial=1; char tx1[TXT], tx0[TXT]; static char static_tx0[TXT];

 fposition=ftell(s);
 *tx='\x0'; fscanf(s,"%s",tx1);
 strcpy(tx0, tx1);
 do{
   if( strlen(tx)+strlen(tx1)>=TXT && trial==1 ) 
   {fseek(s, fposition, SEEK_SET); strcpy(tx, static_tx0); trial=2; fscanf(s,"%s",tx0);strcat(tx," ");strcat(tx, tx0);}
   else if( strlen(tx)+strlen(tx1)>=TXT && trial==2 )
   {printf("\nEnzyme name ->%s<- not found in the stoichiometric equations!\n\nProgram prematurely finished.\nPlease press ENTER", tx0); getch(); exit(1);}
   else if(!strlen(tx))
    strcat(tx, tx1);
   else 
    {strcat(tx," "); strcat(tx, tx1);}
   for(i=0; i<enzyme_counter; i++)
   { if(!strcmp(*(enzyme_names+i), tx)) /* if found */ 
     {strcpy(static_tx0, tx); return 0;} else;}
   if (tx[0]=='-') return 0;
   fscanf(s,"%s",tx1);
 }while(1);
} // my_fscanf_enz_names

int met_in_eac( struct enc* metlist, char* tx, const int int_ext )
{
  struct enc *mz;
  mz=metlist->next;
  do{
    if(mz->txt[0]=='\x0') break;
    if(!strcmp(mz->txt, tx))
    {
     printf("\nMetabolite ->%s<- is declared twice ", mz->txt);
     if     ( !int_ext && !mz->rev ) printf("as internal.");
     else if(  int_ext &&  mz->rev ) printf("as external.");
     else                            printf("as internal and external.");
     printf("\nPlease change your input file.");
     printf("\nplease press ENTER"); getch(); printf("\r                  \r"); 
     return 1;
    }
    mz=mz->next;
  }while(1);
  return 0;
} //met_in_eac
/* 1.3 function get metlist ******************* */
struct enc *getmetlist (FILE *s)
{
 struct enc *metlist, *eac, *mz;
 char tx[TXT];

 metlist=(struct enc*)calloc(1, sizeof( struct enc )); addressed( metlist, "metlist not allocated", 1);
 mz=     (struct enc*)calloc(1, sizeof( struct enc )); addressed( mz,      "mz not allocated", 1     );
      
 metlist->next=mz; metlist->key=0;
 mz->next=mz; mz->key=0; eac=metlist;
 while (!feof(s))
 {
  my_fscanf(s, tx);  //fscanf(s,"%s",tx);
  if (tx[0]=='-') break;
  // if( met_in_eac( metlist, tx, 0 ) ) continue;
  eac=ins(eac,0,(eac->key)+1,tx);
  // FM eac->rev=0; // notice metabolite as intern
 }
 while (!feof(s))
 {
  my_fscanf(s, tx);// fscanf(s,"%s",tx);
  if (tx[0]=='-') break;
  // if( met_in_eac( metlist, tx, 1 ) ) continue;
  eac=ins(eac,1,(eac->key)+1,tx);
  // FM eac->rev=1;
 }
 detect_double_declared_metabolites( metlist );
 return metlist;
} // getmetlist
/* ************************************************************************************ */
/* 2. functions for struct vector and struct mat *********************************** */
/* ************************************************************************************ */
/* 2.1 output ********************************* */
  int flistoutput (struct enc *list, FILE *savefile)
      {
      fprintf(savefile,"\nlist output\n");
      while (list!=list->next) 
         {
         fprintf(savefile,"%d: %s, %d\n",list->key,list->txt,list->rev);
         list=list->next;
         }
      return 0;
      }

int vectoroutput (struct vector *v)
{
 int i;
 printf ("\n");
 for (i=0; i<v->row; i++) printf ("%g ",(double)*(v->head+i));
 printf ("\n"); 
 return 0;
}

void print_mat(struct mat *m)
{
 int i, j;
 printf("\n");
 for( i=0; i<m->row; i++)
 {  for( j=0; j<m->col; j++)
    #ifdef sun
     printf("%g ", *(*((m->head)+i)+j));
    #else
     printf("%2g ", (double)*(*((m->head)+i)+j));
    #endif
   printf("\n");
 }
}//print_mat

int null_mat(struct mat *m)
{
 int i, j, k=0;
 for( i=0; i<m->row; i++)
  for( j=0; j<m->col; j++)
   if( *(*((m->head)+i)+j))k++;
 return k;
}//null_mat

int fvectoroutput (struct vector *v, FILE *savefile)
{
 int i;
 for (i=0; i<(v->row); i++)
 {
   if(fabsl(*(v->head+i))>1.0E-9)
    fprintf(savefile,"%2g ", (double)*((v->head)+i));
   else fprintf(savefile, " 0 ");
 }
 fprintf (savefile,"\n"); return 0;
}

int fmatoutput (struct mat *m, FILE *savefile)
{
 int i,ii, zero_count, zero_lines=0;
 char format[101] = {" "};

 // first count zero_lines for a correct matrix dimension FM
 for (i=0; i<(m->row); i++) 
 {
  for (zero_count=ii=0; ii<(m->col); ii++) 
    if( *(*((m->head)+i)+ii)==0.0) zero_count++;
  if( zero_count==m->col) 
    zero_lines++;
 }

 // to format
 formatting( format, m->head, m->row, m->col );
#ifdef sun
   strcat(format, "g ");
#else   
   strcat(format, "Lg ");
#endif
 fprintf (savefile," \n matrix dimension %d x %d\n",m->row-zero_lines, m->col);
 for (i=0; i<(m->row); i++) 
 {
  // do not fprintf if a line contains only zeros
  for (zero_count=ii=0; ii<(m->col); ii++) 
    if( *(*((m->head)+i)+ii)==0.0) zero_count++;
  if( zero_count==m->col) continue;
 
  for (ii=0; ii<(m->col); ii++) 
    // fprintf(savefile,"%2.0Lf ",*(*((m->head)+i)+ii));
    fprintf(savefile, format, (long_double) *(*((m->head)+i)+ii));
  fprintf(savefile,"\n");
 }
 return 0;
} // fmatoutput

int fenzymeoutput (struct mat *m, struct enc *list, FILE *savefile)
{
 int i,r, zero_lines=0, yn=0;
 long_double **mat, **h;
 unsigned long fpos;
 struct enc *acel;
 char format[101];
 
 h=(long_double**)calloc( 1, sizeof(long_double));
 mat=m->head;
 fprintf (savefile,"\n enzymes\n");
 for (i=0;i<m->row;i++)
 {
   fpos=ftell(savefile);
   fprintf (savefile,"\n %d:\t",i+1-zero_lines);
   acel=list->next; r=0;
   
   while (acel!=acel->next)
   {
    if (*(*(mat+i)+(acel->key-1))!=0) 
	{
	 fprintf(savefile, " " );
     if(fabsl(*(*(mat+i)+(acel->key-1)))==1 && strstr(acel->txt, " "))        fprintf(savefile, "(");  // metabolites with spaces to fasten together
     
     if (*(*(mat+i)+(acel->key-1))==1) 
       fprintf(savefile,"%s",acel->txt);
     else if (*(*(mat+i)+(acel->key-1))==-1) 
       fprintf(savefile,"-%s",acel->txt);
	 else 
     {  
        // to format
        fprintf(savefile,"("); *h=(*(mat+i)+(acel->key-1));
        formatting( format, h, 1, 1 );
        #ifdef sun
         strcat(format, "g ");  // strcpy( format, "%3g ");
        #else   
         strcat(format, "Lg "); // strcpy( format, "%Lg");
        #endif
        fprintf(savefile, format, *(*(mat+i)+(acel->key-1)));
        fprintf(savefile,"%s)", acel->txt);
     }
     if( fabsl(*(*(mat+i)+(acel->key-1)))==1 && strstr( acel->txt, " ") )        fprintf(savefile,")");
     if ((acel->rev)==1) r=1;
     yn=1;
	}
    acel=acel->next;
   };
   if(yn==1)
   {if (r==1) fprintf (savefile," irreversible");
    else fprintf (savefile," reversible");
   }else
    { ++zero_lines; fseek( savefile, fpos, SEEK_SET); }
   yn=0;
 }
 if( m->row == zero_lines ) fprintf(savefile, " - none found -\n");
 fprintf (savefile,"\n");
 free(h);
 return i;
} // fenzymeoutput

int foveralloutput (struct mat *m, struct enc *list, FILE *savefile)
{
 int i,t, j, zero_count, zero_lines=0;
 long_double **mat, **h;
 struct enc *acel;
 char format[101];
 h=(long_double**)calloc(1, sizeof(long_double*));
 mat=m->head;
 //*->*/    printf("m r%d x c%d", m->row, m->col);   print_mat( m  ); getch();
 fprintf(savefile,"\n overall reaction\n");
 for (i=0;i<m->row;i++)
 {
  for(zero_count=j=0; j<m->col; j++)
  {
    if(!(*(*(m->head+i)+j))) zero_count++;
  }
  if(zero_count==m->col)
   {/* skip zerolines */ zero_lines++; continue; }
  fprintf (savefile,"\n %d:\t",i+1/*-zero_lines*/); // fflush(savefile);
  acel=list->next;
  t=0;	
  while (acel!=acel->next)
  {
   if (*(*(mat+i)+(acel->key-1))<0) 
   {			
    if (t==1) fprintf (savefile," + ");
    if (*(*(mat+i)+(acel->key-1))==-1)
       fprintf (savefile,"%s",acel->txt);
    else
    { // fprintf(savefile,"%Lf %s",-*(*(mat+i)+(acel->key-1)),acel->txt);
      // to format
      *h=(*(mat+i)+(acel->key-1)); (**h)=-(**h);
      formatting( format, h, 1, 1 );
      #ifdef sun
        strcat(format, "g ");  
      #else   
        strcat(format, "Lg "); 
      #endif
      fprintf(savefile, format, *(*(mat+i)+(acel->key-1)));
      // fprintf(savefile, "%lg ", (double) *(*(mat+i)+(acel->key-1)));
      fprintf(savefile,"%s", acel->txt); (**h)=-(**h);
      // fflush(savefile);
    }
    t=1;
   }
   acel=acel->next;
  };
  fprintf (savefile," = ");
  t=0;
  acel=list->next;
  while (acel!=acel->next)
  {
   if (*(*(mat+i)+(acel->key-1))>0) 
   {
    if (t==1) fprintf (savefile," + ");
    if (*(*(mat+i)+(acel->key-1))==1) 
       {fprintf (savefile,"%s",acel->txt); /* fflush(savefile);*/ }
    else
    { 
      *h=(*(mat+i)+(acel->key-1));
        formatting( format, h, 1, 1 );
      #ifdef sun
       strcat( format, "g ");
      #else   
       strcat( format, "Lg ");
      #endif
      fprintf(savefile, format, (long_double)*(*(mat+i)+(acel->key-1)));
      fprintf(savefile,"%s",acel->txt);
      // fflush(savefile);
    }
    t=1;
   }
   acel=acel->next;
  };
 }
 if( m->row == zero_lines ) fprintf(savefile, " - none found -\n");
 if(zero_lines) 
    fprintf(savefile, "\n\nThe remaining overall reactions perform no net transformation of external metabolites.");
 fprintf (savefile,"\n");// fflush(savefile);
 free(h);
 return 0;
} // foveralloutput 

struct vector *getrev (struct enc *list)
{
 int i=0;
 struct enc *acel; struct vector *v;
 acel=list->next;
 while (acel!=acel->next) {acel=acel->next;i++;}
 v=(struct vector*)calloc(1, sizeof(struct vector)); v->row=i;   addressed( v, "v not allocated", 1);
 v->head=(long_double*)calloc(v->row, sizeof(long_double));      addressed( v->head, "v->head not allocated", v->row);
 acel=list->next; i=0;
 while (acel!=acel->next) {*(v->head+(i++))=acel->rev; acel=acel->next;} 
 return v;
} //struct vector *getrev 

int scan_metabolites( char*tx, char *end )
{
  static int first=1;
  char help[TXT];
  int len, i, y_n=0;
  if(!met_counter)first=1;
  
  len=strlen(tx)-3;
  i=0; while(isspace(tx[i++])); 
  strcpy(help, &tx[i-1]); help[len-i+1]='\x0';
  strcpy(tx, help);
  if( !strcmp( end, " : ") ) return 0;
  if( first )
  { metabolites = (char**)calloc(1, sizeof(char*)); addressed(metabolites, "metabolites", 1 ); 
    mets_cumul  = (int*)  calloc(1, sizeof(int*));  addressed(mets_cumul, "mets_cumul", 1 ); }
  for(i=0; i<met_counter; i++ )
   if( !first && !strcmp(*(metabolites+i), help )) 
   { y_n=1; (*(mets_cumul+i))++; break;}
  if(!y_n)
  {
   metabolites = (char**)realloc(metabolites, (met_counter+1)*sizeof(char*)); addressed(metabolites, "realloc metabolites", (met_counter+1)); 
   mets_cumul  = (int*)  realloc(mets_cumul,  (met_counter+1)*sizeof(char*)); addressed(mets_cumul, "realloc mets_cumul", (met_counter+1)); *(mets_cumul+met_counter) = 1;
   *(metabolites+met_counter) = (char*)calloc(len+1, sizeof(char)); addressed(*(metabolites+met_counter), "*(metabolites+met_counter)", len+1);
   // copy the name of the metabolite if it is not included into the global array
   strcpy(*(metabolites+met_counter), help);
   met_counter++;
  }
  first=0;
  return 0;
} //scan_metabolites

int read_unit(FILE *s, char *tx) // read syntactical units of the stoichiometrical equations
{
 int c, c1, i=0, len;
 char end[4];
 long int f_pos;

 do{
   do{
     c = fgetc(s);
     if(c==EOF && tx[i-1]!='.') return -1;
     c1 = fgetc(s); if(c1!=EOF)fseek(s, -1, SEEK_CUR); 
     if(isspace(c1)&&isspace(c)){continue;}
     if(c1==':'&&isspace(c)||c1=='.'&&isspace(c)||c1=='='&&isspace(c)||c1=='+'&&isspace(c)) 
       f_pos=ftell(s)-1;
    
     if(c=='\t' ||  c=='\n' || c==EOF)c=' ';
     if(strlen(tx)>1)
       if(tx[strlen(tx)-1]=='.' && isspace(c) ) c=' ';
     if((i>1&&isspace(tx[i-1]))&&isspace(c));
     else{tx[i] = (char)c; tx[++i]='\x0';}
     if(i>2) 
       if(isspace(tx[i-3]) && (tx[i-2]==':'||tx[i-2]=='+'||tx[i-2]=='='||tx[i-2]=='.' ) && isspace(tx[i-1]))
          break; 
   }while(1);

   len=strlen(tx); 
   tx=strrev(tx);
   while(isspace(tx[len-1]))tx[--len]='\x0';
   tx=strrev(tx);
   if(isspace(tx[0])) tx[0]=' ';
   if(i==2)
    {
     if( !strcmp(tx, ": ") || !strcmp(tx, "+ ") ||
         !strcmp(tx, "= ") || !strcmp(tx, ". ") ) 
         { return 0; }
    }
   if(i>2)
   {
    {
     if( !strcmp(tx, ": ") || !strcmp(tx, "+ ") ||
         !strcmp(tx, "= ") || !strcmp(tx, ". ") ) 
         { return 0; }
    }
    if(strlen(tx)==3)strcpy(end, tx);else strcpy(end, &tx[strlen(tx)-3]);
    if( !strcmp(end, " : ") || !strcmp(end, " + ") ||
        !strcmp(end, " = ") || !strcmp(end, " . "))  
        { scan_metabolites(tx, end);
          if(!strcmp(end, " : ")||!strcmp(end, " + ")||!strcmp(end, " = ")||!strcmp(end, " . "))
            fseek(s,f_pos, SEEK_SET);
          break;
        }
   } 
 } while(1);
 return 0;
}// read_unit */

int read_stoech_koeff(FILE *s, char* tx, int *rs)
{
 int c, i=0, len, y_n;
 long int f_position;
 char *end;

 f_position = ftell(s);
 do{
   c = fgetc(s);
   tx[i++] = (char)c; tx[i]='\x0';
   if(i>2)
   {
    end = &tx[i-2];
    if( !strcmp(end, "+ ") ) break;
    if( !strcmp(end, "= ") ) break; 
    if( !strcmp(end, ". "/*\n*/) )break;
   }
 } while( !isspace(tx[i-1]) );
 
 y_n=0; len = strlen(tx)-1;
 for( i=0; i<len; i++ )
   if( !isdigit(tx[i]) ) {y_n=1; break;}
  
 if(!y_n) // oo 
   { fseek(s, -1, SEEK_CUR); *rs=atoi(tx);  }
 else 
   { fseek(s, f_position, SEEK_SET); *rs=1;}
 return 0;
} //read_stoech_koeff

struct mat *my_getnex (FILE *s, struct enc *metlist, struct enc *enzlist) 
{
 char tx[TXT]={""};
 struct enc *el, *ml, *acel;
 struct mat *m;
 int metfl, rs=0, con, rev;
 int nmet, nreact, acrow, acol;
 long_double **sub;
    
 // unfortunately the metabolites have to be read once more  out of the stochiometrical equations
 if( met_counter )
 {for(rs=0; rs<met_counter; rs++)
   free(*(metabolites+rs)); 
  free(metabolites); met_counter=0;
  free(mets_cumul);
 }
 nmet=0;nreact=0;
 acel=metlist->next;
 while (acel!=acel->next) {acel=acel->next;nmet++;}
 acel=enzlist->next;
 while (acel!=acel->next) {acel=acel->next;nreact++;}
 sub=(long_double**)calloc(nmet, sizeof(long_double*));  addressed( sub, "sub not allocated", nmet);
 for (acrow=0;acrow<nmet;acrow++)
 {*(sub+acrow)=(long_double*)calloc(nreact, sizeof(long_double)); addressed( *(sub+acrow), "*(sub+acrow) not allocated", nreact);}
 metfl=0; 
 while (!feof(s))	
 {
   el=enzlist; ml=metlist;
   if( read_unit(s, tx) == -1 ) break; 
   if      (tx[0]=='.') {metfl= 0;  if( read_unit(s, tx)==-1 /*fscanf(s,"%s",tx)==EOF*/ ) break;            }
   else if (tx[0]==':') {metfl= 1; read_stoech_koeff(s,tx,&rs); read_unit(s, tx); }  
   else if (tx[0]=='=') {metfl=-1; read_stoech_koeff(s,tx,&rs); read_unit(s, tx); }
   else if (tx[0]=='+') {          read_stoech_koeff(s,tx,&rs); read_unit(s, tx); }
   if(!metfl)
   {
    con=1; acrow=0;
    while (el!=el->next) 
    {
     el=el->next;   
     if(compstr(100,tx,el->txt)) 
     {con=0;rev=el->rev; break;}
    }
    if (con) 
    {printf ("ERROR: UNKNOWN ENZYME: %s\n",tx); printf("press ENTER key -> "); getch(); printf("\r                   \r");} 
    else acol=(el->key)-1;      
   }
   else
   {
    con=1;
    while (ml!=ml->next) 
    {
     ml=ml->next;
     if (compstr(100,tx,ml->txt)) {con=0; break;}
    }
    if (con) 
      {printf ("ERROR: UNKNOWN METABOLITE: %s\n",tx); printf("press ENTER key -> "); getch(); printf("\r                   \r");}
    else acrow=(ml->key)-1; 
    *(*(sub+acrow)+acol)=-rs*metfl;
    // for irreversible reactions: only consumed or only built
    if(metfl>0 ) // if rev==1 the reaction is irreversible
       ml->consumed=1;
    else       
       ml->built=1;
    if(rev==0) {ml->consumed=1; ml->built=1;}
    ml->reactions++;
   }   
   tx[0]='\x0';
 }; // end while()
 m=(struct mat*)calloc(1, sizeof(struct mat));   addressed( m, "m not allocated", 1);
 m->row=nmet; 
 m->col=nreact; 
 m->head=sub;
 return m;
} //struct mat *my_getnex 

int get_enzyme_names(char *enz_name)
{
 int len, i;
 len=strlen(enz_name);
 if(!enzyme_counter)
   enzyme_names = (char**)calloc(1, sizeof(char*)); addressed(enzyme_names, "enzyme_names", 1 );

 enzyme_names = (char**)realloc(enzyme_names , (enzyme_counter+1)*sizeof(char*)); addressed(enzyme_names , "realloc enzym_names", (enzyme_counter+1));
 *(enzyme_names+enzyme_counter) = (char*)calloc(len+1, sizeof(char)); addressed(*(enzyme_names+enzyme_counter), "*(enzyme_names+enzyme_counter)", len+1);
 strcpy(*(enzyme_names+enzyme_counter), enz_name);
 enzyme_counter++;
  // test if there is a double defined reaction
 for( i=0; i<enzyme_counter-1; i++ )
   if(!strcmp(*(enzyme_names+i), enz_name))
   { printf("The enzyme reaction ->%s<- is more than once defined.", enz_name ); 
     printf("\nPlease delete the extra defined reaction in the input file.\n\nProgram prematurly finished. Please press ENTER key ");
     getch(); exit(1); 
   }
 return 0;
} // get_enzyme_names

int get_metabolites_from_equations (FILE *s) 
{
 char tx[TXT];
 int rs=0;static int a;

 do{ fgets(tx, TXT-1, s);
 }while(strcmp(tx, "-CAT\n"));
 fgetc(s); // read only NEWLINE
 
 fseek(s, -1, SEEK_CUR);
 while (!feof(s))	
 {                     a++; 
   if      (read_unit(s,tx)==-1) { break; } if(a==1)
                                            get_enzyme_names(tx); 
   if      (tx[0]=='.') { if(read_unit(s, tx)==-1) break; 
                          get_enzyme_names(tx); /*if( fscanf(s,"%s",tx)==EOF ) break; */}
   else if (tx[0]==':') { read_stoech_koeff(s,tx,&rs); 
                          read_unit(s, tx); }  
   else if (tx[0]=='=') { read_stoech_koeff(s,tx,&rs); 
                          read_unit(s, tx); }
   else if (tx[0]=='+') { read_stoech_koeff(s,tx,&rs); 
                          read_unit(s, tx); }
   tx[0]='\x0';
 }; // end while()
 rewind(s);
 return 0;
} //get_metabolites_from_equations

struct mat *cutnex (struct mat *nex, struct vector *met)
                             // *mex, struct vector *ex)
{
 struct mat *m;
 int i,k=0, j;
 m=(struct mat*)calloc(1, sizeof(struct mat)); addressed( m, "m not allocated", 1);
 m->row=0; m->col=nex->col;
 for (i=0; i<met->row; i++) if (!*(met->head+i)) m->row++; else;
 if(m->row)
 { m->head=(long_double**)calloc( m->row, sizeof(long_double*)); addressed( m->head, "m->head not allocated", m->row); }
 else
 { printf("\nThe system comprises only external metabolites.\n"); m=NULL; return m; /* getch(); exit(1); */}
 for (i=0;i<met->row;i++)
 if (!*(met->head+i))  // leave out external if *(met->head+i)==1
 {
   /* allocated by FM */
   *(m->head+k)=(long_double*)calloc(m->col, sizeof(long_double));  
   addressed( *(m->head+k), "*(m->head+i) not allocated", m->col);
   for( j=0; j<m->col; j++ ) *(*(m->head+k)+j)=*(*(nex->head+i)+j); k++;
 }else;
 return m;
} // cutnex

/* free ************************************** */
int freevector (struct vector *v)
{free (v->head); free (v); return 0;}
int freemat (struct mat *m)
{
 int i;
 for (i=0; i<m->row; i++) 
 free (*(m->head+i));
 free (m->head); free (m); return 0;
}
int free_met_list(struct enc *metlist)
{
 int i=0, j;
 struct enc *a;
 a=metlist;
  while( a->next != a->next->next )
  {
   a= a->next;
   i++;
  }
 for( ++i; i>0; i-- )
 {
  a=metlist;
   for( j=0; j<i-1; j++ )
    a = a->next;
  free( a->next );
 }
 free(a);
 return 0;
} // free_met_list

int print_met_list(struct enc *metlist)
{
 int i=0;
 struct enc *a;
 a=metlist;
  while( a->next != a->next->next )
  {
   a= a->next;
   printf("%3d %s\n", i+1, a->txt );
   i++;
  }
 return 0;
} // print_met_list

int additional_em(FILE *fout, struct mat *cb, struct mat *em)
{
  int ok, c, r, re, cc, ee;

  // control if cb not found in em (convex basis cb; elementary mode em
  for(r=0; r<cb->row; r++)
  {
   for( re=0; re<em->row; re++ )
   {
    for(cc=ee=ok=c=0; c<cb->col; c++)
    {  
     if( *(*(cb->head+r)+c) && *(*(em->head+re)+c) ) ok++;
     if( *(*(cb->head+r)+c) ) cc++;
     if( *(*(em->head+re)+c) ) ee++;
    }
    if( ok==cc && ok==ee ) break;
   }
   if(!(ok==cc && ok==ee)) 
     { fprintf(fout, " %d", r+1 ); }
  }
  fprintf(fout, "\n");  // fflush(fout);
  return 0;
} // additional_em

void read_comment( FILE *fp_in )
{
 char*help;
 long int f_pos;
 help=(char*)calloc(1000, sizeof(char));addressed(help,"not enough memory | in read comment", 1000);
 do{
  f_pos = ftell(fp_in);
  fgets( help, 999, fp_in);
  if( !strstr(help, "#") ) {fseek(fp_in, f_pos, SEEK_SET); break;}
 }while(1);
 free(help);
}

/* 2.3 mat operations ********************+* */
  struct mat *transp (struct mat *m)
      {
      struct mat *tm; int i,ii;
      tm=(struct mat*)calloc(1, sizeof(struct mat));   addressed( tm, "tm not allocated", 1);
      tm->row=m->col; tm->col=(m->row);
      tm->head=(long_double**)calloc(tm->row, sizeof(long_double*)); addressed( tm->head, "tm->head not allocated", tm->row);
      for (i=0; i<m->col; i++) 
          {
          *(tm->head+i)=(long_double*)calloc(tm->col, sizeof(long_double));  addressed( *(tm->head+i), "*(tm->head+i) not allocated", tm->col);
          for (ii=0; ii<m->row; ii++) *(*(tm->head+i)+ii)=*(*(m->head+ii)+i);
          }
      return tm;
      }
  struct mat *addi (struct mat *m)
      {
      struct mat *mi; int i,ii;
      mi=(struct mat*)calloc(1, sizeof(struct mat)); addressed( mi, "mi not allocated", 1);
      mi->row=m->row; mi->col=m->col+m->row;
      mi->head=(long_double**)calloc(mi->row, sizeof(long_double*)); addressed( mi->head, "mi->head not allocated", mi->row);
      for (i=0; i<m->row; i++)
          {
          *(mi->head+i)=(long_double*)calloc(mi->col, sizeof(long_double)); addressed( *(mi->head+i), "*(mi->head+i) not allocated", mi->col);
          for (ii=0; ii<mi->col; ii++)
             {
             if (ii<m->col) *(*(mi->head+i)+ii)=*(*(m->head+i)+ii);
             else if (ii==m->col+i) *(*(mi->head+i)+ii)=1;
             else *(*(mi->head+i)+ii)=0;
             }
          }
      return mi;
      }

struct mat *cutcol (struct mat *m, int cc)
{
 struct mat *mc; int i,ii;
 mc=(struct mat*)calloc(1, sizeof(struct mat)); addressed( mc, "mc not allocated", 1);
 mc->row=m->row; mc->col=m->col-cc;
 mc->head=(long_double**)calloc(mc->row, sizeof(long_double*)); addressed( mc->head, "mc->head not allocated", mc->row);
 if(cc>m->col) {printf("ERROR IN FUNCTION CUTCOL: CC>M->ROW!\n"); getch(); exit(1); /* return NULL; */}
 for (i=0; i<mc->row; i++)
 {
  *(mc->head+i)=(long_double*)calloc(mc->col, sizeof(long_double)); addressed( *(mc->head+i), "*(mc->head+i) not allocated", mc->col);
  for (ii=0; ii<mc->col; ii++)
    *(*(mc->head+i)+ii)=*(*(m->head+i)+ii+cc);
 }
 return mc;
}

struct mat *simplify (struct mat *m)
{
 struct mat *mc;
 struct vector *vf;
 int i,ii,k;

 vf=(struct vector*)calloc(1, sizeof(struct vector)); addressed( vf, "vf not allocated", 1);
 vf->row=m->row; vf->head=(long_double*)calloc(vf->row, sizeof(long_double)); addressed( vf->head, "vf->head not allocated", vf->row);
 
 mc=(struct mat*)calloc(1, sizeof(struct mat)); addressed( mc, "mc not allocated", 1);
 mc->row=m->row; mc->col=m->col;

 {
  if( branch )
  {  
    branch=(struct vector*)calloc(1, sizeof(struct vector)); addressed( branch, "branch not allocated", 1);
    branch->row=m->row; branch->head=(long_double*)calloc(branch->row, sizeof(long_double)); addressed( branch->head, "branch->head not allocated", branch->row);
    for(i=0; i<branch->row; i++) *(branch->head+i)=1;
  }
 }

 for (i=0; i<m->row; i++)
 {
   *(vf->head+i)=0;
   for (ii=0;ii<m->col;ii++) 
       *(vf->head+i)=ggt(*(vf->head+i),*(*(m->head+i)+ii));
   if (*(vf->head+i)==0) // at this line are shown the non branch metabolites
   {
    if(branch) *(branch->head+i)=0.0;  // write into the global variable 
    mc->row--;
   }
 }
 if( !mc->row ) // Microsoft C++ 6.0 allocates any pointer if(mc->row==0 but no correct one)
 {
   // printf("there is no simplification ...\n");
   mc->head=(long_double**)calloc(m->row, sizeof(long_double*)); addressed( mc->head, "mc->head not allocated 1", m->row);
   // return a copy of *m
   for (i=0; i<m->row; i++)
   {
    *(mc->head+i)=(long_double*)calloc(m->col, sizeof(long_double)); addressed( *(mc->head+i), "*(mc->head+i) not allocated", m->col);
    for (ii=0;ii<m->col;ii++) 
      *(*(mc->head+i)+ii)=*(*(m->head+i)+ii);
   }
   mc->row=m->row; mc->col=mc->col;
 }
 else 
 {
   mc->head=(long_double**)calloc(mc->row, sizeof(long_double*)); addressed( mc->head, "mc->head not allocated", mc->row); k=0;
   for (i=0; i<vf->row; i++)
   { 
    if (*(vf->head+i)!=0) 
    {
     *(mc->head+k)=(long_double*)calloc(mc->col, sizeof(long_double)); addressed( *(mc->head+k), "*(mc->head+k) not allocated", mc->col);
     for (ii=0;ii<mc->col;ii++) 
       *(*(mc->head+k)+ii)=*(*(m->head+i)+ii)/(*(vf->head+i));
     k++;
    }
   }
 }
 freevector(vf);
 return mc;
} // simplify
      
struct mat *mult (struct mat *m1, struct mat *m2)
{
 struct mat *mm; int i,j,k; long_double sum;
 if (m1->col!=m2->row) printf("error in mult: mat dimensions are inkompatible");
 mm=(struct mat*)calloc(1, sizeof(struct mat));  addressed( mm, "mm not allocated", 1);
 mm->row=m1->row; mm->col=m2->col;
 mm->head=(long_double**)calloc(mm->row, sizeof(long_double*));  addressed( mm->head, "mm->head not allocated", mm->row);
 for (i=0; i<mm->row; i++)
 {
  *(mm->head+i)=(long_double*)calloc(mm->col, sizeof(long_double));  addressed( *(mm->head+i), "*(mm->head+i) not allocated", mm->col);
  for (k=0; k<mm->col; k++)
  {
   sum=0;
   for (j=0; j<m1->col; j++) 
     sum+=(*(*(m1->head+i)+j)*(*(*(m2->head+j)+k)));
   *(*(mm->head+i)+k)=sum;
  }
 }
 return mm;
}
/* 2.4 complex mat operations ************** */
int switch_if_all_row_is_minus_into_plus(struct mat *help)
{
  int i, j, count_negatives, count_positives;
  for(i=0; i<help->row; i++ )
  {
    count_negatives=0; count_positives=0;
    for(j=0; j<help->col; j++)
      if     ( *(*(help->head+i)+j) < 0 ) 
        count_negatives++;
      else if( *(*(help->head+i)+j) > 0 )
        { count_positives++; break;}
    if( !count_positives && count_negatives )
    for(j=0; j<help->col; j++ )
      if(*(*(help->head+i)+j)) *(*(help->head+i)+j)*=-1.0;
  }
 return 0;
} // switch_if_all_row_is_minus_into_plus
/* Kernel */
struct mat *kernel (struct mat *m)
{
 struct mat *help, *k; int i,u,ii,uu; long_double f1,f2;
       
 k=transp(m);
 help=addi(k);
 freemat(k);
 for (ii=0; ii<m->row; ii++)
 {
  for (i=0; i<help->row; i++) if (*(*(help->head+i)+ii)!=0) break;
  for (u=i+1; u<help->row; u++) if (*(*(help->head+u)+ii)!=0)
  {
   f1=(*(*(help->head+u)+ii))/ggt(*(*(help->head+u)+ii),*(*(help->head+i)+ii));
   f2=(*(*(help->head+i)+ii))/ggt(*(*(help->head+u)+ii),*(*(help->head+i)+ii));
   for (uu=0;uu<help->col;uu++) 
     *(*(help->head+u)+uu)=f2*(*(*(help->head+u)+uu))-f1*(*(*(help->head+i)+uu));
  }
  if (i<help->row) for (uu=0;uu<help->col;uu++) *(*(help->head+i)+uu)=0;
 }
 k=cutcol(help,m->row); 
 freemat(help); 
 help=simplify(k);
 freemat(k); 
 switch_if_all_row_is_minus_into_plus(help);
 return help;
} // Kernel

int delete_corresponding_row_in_rev(struct vector *a, int wrong_subset)
{
 int j;
 
 if(wrong_subset<a->row-1)
   for( j=0; j<a->row; j++ )
     *(a->head+j) = *(a->head+j+1);
 a->row--;
 return 0;
} //delete_corresponding_row_in_rev
      
/* Subsets */
struct mat *subset (struct mat *m, struct vector *v, int **wrong_subset)
{
 struct mat *help, *k; int i,ii,u; 
 long_double f1,sign1;
 k=transp(m); help=addi(k); freemat(k);
     
 for (i=0;i<help->row;i++) 
	{
		f1=0; sign1=0;  
		for (ii=0;ii<m->row;ii++) if (*(*(help->head+i)+ii)!=0)
		{
		 f1=ggt(f1,*(*(help->head+i)+ii));
		 if (sign1==0) sign1=*(*(help->head+i)+ii)/fabsl(*(*(help->head+i)+ii));
		}
		if (f1==0) for (ii=0;ii<help->col;ii++) *(*(help->head+i)+ii)=0;
		else 
		{
		 for (ii=0;ii<m->row;ii++) *(*(help->head+i)+ii)=*(*(help->head+i)+ii)*sign1/f1;
			*(*(help->head+i)+i+m->row)=f1*sign1; 
		}
 }	
 //*->*/    printf("help r%d x c%d", help->row, help->col);   print_mat( help ); getch();

 for (i=0;i<help->row;i++) for (u=i+1;u<help->row;u++)
	{
	 f1=0;
		for (ii=0;ii<m->row;ii++) if ((*(*(help->head+i)+ii))!=(*(*(help->head+u)+ii))) f1=1;
		if (f1==0)
		{
			for (ii=m->row;ii<help->col;ii++) *(*(help->head+i)+ii)+=*(*(help->head+u)+ii);
			for (ii=0;ii<help->col;ii++) *(*(help->head+u)+ii)=0;
		}
 }

 k=cutcol(help,m->row); freemat(help);
 help=simplify(k); freemat(k);
 *wrong_subset = (int*) calloc(help->row, sizeof(int)); addressed(wrong_subset, "wrong_subset not enough memory", help->row);
 //*->*/ print_mat(help);
 for (i=0;i<help->row;i++)						/* revstatetest */
	{
		f1=0;
		for (ii=0;ii<help->col;ii++) 
           if ((*(v->head+ii))&&(*(*(help->head+i)+ii)<0))
           {f1=1;break;}
		if (f1==1)
         for (ii=0;ii<help->col;ii++) 
           *(*(help->head+i)+ii)*=-1;
		f1=0;
		for (ii=0;ii<help->col;ii++) 
           if ((*(v->head+ii))&&(*(*(help->head+i)+ii)<0))
           {f1=1;break;}
		if (f1==1) 
        { *(*wrong_subset+i)=1;  /* for (ii=0;ii<help->col;ii++) *(*(help->head+i)+ii)=0;*/ }
 }	
 switch_if_all_row_is_minus_into_plus(help);
 return (help);
} // subset

struct vector *subrev (struct mat *m, struct vector *v)
{
 int i,ii;
 struct vector *r;
 r=(struct vector*)calloc(1, sizeof(struct vector));  addressed( r, "r not allocated", 1);

 r->row=m->row; r->head=(long_double*)calloc(r->row, sizeof(long_double));  addressed( r->head, "r->head not allocated", r->row);
 for (i=0;i<m->row;i++) 
 {
  *(r->head+i)=0;
  for(ii=0;ii<m->col;ii++) 
    if((*(*(m->head+i)+ii))&&(*(v->head+ii))) 
      {*(r->head+i)=1; break;}
 }
 return r;
}

inline int numerical_array( long_double k2, long_double hi, long_double k1, long_double hu, 
                     const int abs1, const int sign1, const int sign2, const char*loop )
{
 // control the numerical overflow of calculation of tablaux
 long double result;
  if( abs1 )
  { result = sign1*fabsl(k2)*(long double)hi + sign2*fabsl(k1)*(long double)hu;}
  else
    result = sign1*k2*(long double)hi + sign2*k1*(long double)hu;
  
  if((long double) result > (long double)  DBL_MAX ||
     (long double) result < (long double) -DBL_MAX )
    {printf("\n\nerror: the intermediate result %g exceeds\nthe allowed integer range  (+- %g), %s\
               \nProgram prematurely finished.", (double)result, DBL_MAX, loop);
     getch(); exit(1);}
  return 0;  
} // numerical_array
      
/* basis */
struct mat *basis (struct mat *m, struct vector *v)
{
  struct mat *help, *k; 
  long_double **h1, **h2, abs_hi, abs_hu, ggt_Erg;
  long_double *rev1, *rev2, k1,k2;
  int i,u,tu,ii,uu,test1;
  int f1, r1, r2, c, counter;
  // struct vector *help_v;
  // help_v =(struct vector*)calloc(1, sizeof(struct vector)); addressed(help_v, "help_v", 1); 

  k=transp(m);help=addi(k);freemat(k);
  r1=(help->row); c=help->col; counter=m->row;
  rev1=(long_double*)calloc(v->row, sizeof(long_double));  addressed( rev1, "rev1 not allocated", v->row);
  for (i=0;i<v->row;i++) {*(rev1+i)=*(v->head+i); if(fabsl(*(rev1+i))<1E-6) *(rev1+i)=0.0;}
  
  h1=help->head;
  for (ii=0; ii<counter; ii++)
  {
    h2  =(long_double**)calloc(1,sizeof(long_double*));  addressed( h2,   "h2 not allocated (1)", 1 );
    rev2=(long_double*) calloc(1,sizeof(long_double) );  addressed( rev2, "rev2 not allocated (2)", 1);
    r2=0;
    f1=0;
    for (i=0; i<r1; i++) 
      if ((*(*(h1+i)+ii))&&(!(*(rev1+i))))   // if rev1==1 than irrev
        {f1=1;break;}
    if (f1) /* reversible row */
    {
     // r2=0;
     h2 = (long_double**) realloc(h2, (r2+1)*sizeof(long_double*)); addressed(h2, "h2 realloc (1)", r2+1);
     {*(h2+r2)  =(long_double*)calloc(c, sizeof(long_double));    addressed( *(h2+r2), "*(h2+r2) not allocated (6)", c); }
     rev2 = (long_double*) realloc(rev2, (r2+1)*sizeof(long_double)); addressed( rev2, "rev2 realloc (2)", (r2+1));
     for (u=0; u<r1; u++) 
     {
      if (*(*(h1+u)+ii)==0)          // transfer "zero lines"
      {
       *(rev2+r2)=*(rev1+u);
       for (uu=0; uu<c; uu++) *(*(h2+r2)+uu)=*(*(h1+u)+uu);
       r2++;
       h2 = (long_double**) realloc(h2, (r2+1)*sizeof(long_double*)); addressed(h2, "h2 realloc (1)", r2+1);
       {*(h2+r2)  =(long_double*)calloc(c, sizeof(long_double));    addressed( *(h2+r2), "*(h2+r2) not allocated (6)", c); }
       rev2 = (long_double*) realloc(rev2, (r2+1)*sizeof(long_double)); addressed( rev2, "rev2 realloc (2)", (r2+1));
       // if(r2>r02) {printf("error1"); getch(); exit(1);}
      }
     }
     for (u=i+1; u<r1; u++)
     {
      if ((*(*(h1+u)+ii))&&(!(*(rev1+u)))) /* rev rev combinations */
      {
       *(rev2+r2)=0.0; k1=*(*(h1+i)+ii); k2=*(*(h1+u)+ii);
       abs_hi=(*(*(h1+i)+ii)>=0 ? *(*(h1+i)+ii) : -*(*(h1+i)+ii)); // FM
       abs_hu=(*(*(h1+u)+ii)>=0 ? *(*(h1+u)+ii) : -*(*(h1+u)+ii)); // FM
       ggt_Erg=ggt(abs_hi,abs_hu);  // FM
       k1/=ggt_Erg; k2/=ggt_Erg;    // FM
       for (uu=0;uu<c;uu++) 
       {
        numerical_array(k2,*(*(h1+i)+uu),k1,*(*(h1+u)+uu), 0, 1, -1, "loop 1");
        *(*(h2+r2)+uu)=k2**(*(h1+i)+uu)-k1**(*(h1+u)+uu);
        //if(fabsl(*(*(h2+r2)+uu))<1E-9) *(*(h2+r2)+uu)=0.0;
        //else 
        *(*(h2+r2)+uu)=rund(*(*(h2+r2)+uu), 0);
       }
       r2++;
       h2 = (long_double**) realloc(h2, (r2+1)*sizeof(long_double*)); addressed(h2, "h2 realloc (1)", r2+1);
       {*(h2+r2)  =(long_double*)calloc(c, sizeof(long_double));    addressed( *(h2+r2), "*(h2+r2) not allocated (6)", c); }
       rev2 = (long_double*) realloc(rev2, (r2+1)*sizeof(long_double)); addressed( rev2, "rev2 realloc (2)", (r2+1));
       // if(r2>r02) {printf("error2"); getch(); exit(1);}
      }
     }
     for (u=0; u<r1; u++) 
     {
      if (*(*(h1+u)+ii)&&(*(rev1+u))) /* rev irrev combinations */
      {
       *(rev2+r2)=1.0; k1=*(*(h1+i)+ii); k2=*(*(h1+u)+ii);
       abs_hi=(*(*(h1+i)+ii)>=0 ? *(*(h1+i)+ii) : -*(*(h1+i)+ii)); // FM
       abs_hu=(*(*(h1+u)+ii)>=0 ? *(*(h1+u)+ii) : -*(*(h1+u)+ii)); // FM
       ggt_Erg=ggt(abs_hi,abs_hu);  // FM
       k1/=ggt_Erg; k2/=ggt_Erg;    // FM
       if (k1*k2<0)
       for (uu=0;uu<c;uu++)
       {
        numerical_array( k2, *(*(h1+i)+uu), k1, *(*(h1+u)+uu), 1, 1, 1, "loop 2"); 
        *(*(h2+r2)+uu)=fabsl(k2)* *(*(h1+i)+uu)+ fabsl(k1)* *(*(h1+u)+uu); 
        // if(fabsl(*(*(h2+r2)+uu))<1E-9) *(*(h2+r2)+uu)=0.0;
        // else 
        *(*(h2+r2)+uu)=rund(*(*(h2+r2)+uu), 0);
       }
       if (k1*k2>=0) 
       for (uu=0;uu<c;uu++)
       {
        numerical_array( k2, *(*(h1+i)+uu), k1, *(*(h1+u)+uu), 1, -1, 1, "loop 3");
        *(*(h2+r2)+uu)=-fabsl(k2)**(*(h1+i)+uu)+fabsl(k1)**(*(h1+u)+uu);
        // if(fabsl(*(*(h2+r2)+uu))<1E-9) *(*(h2+r2)+uu)=0.0;
        // else 
        *(*(h2+r2)+uu)=rund(*(*(h2+r2)+uu), 0);
       }
       r2++;
       h2 = (long_double**) realloc(h2, (r2+1)*sizeof(long_double*)); addressed(h2, "h2 realloc (1)", r2+1);
       {*(h2+r2)  =(long_double*)calloc(c, sizeof(long_double));    addressed( *(h2+r2), "*(h2+r2) not allocated (6)", c); }
       rev2 = (long_double*) realloc(rev2, (r2+1)*sizeof(long_double)); addressed( rev2, "rev2 realloc (2)", (r2+1));
       // if(r2>r02) {printf("error3"); getch(); exit(1); }
      }
     }
    }
    else /* no reversible row */
    {
     h2 = (long_double**) realloc(h2, (r2+1)*sizeof(long_double*)); addressed(h2, "h2 realloc (1)", r2+1);
     {*(h2+r2)  =(long_double*)calloc(c, sizeof(long_double));    addressed( *(h2+r2), "*(h2+r2) not allocated (6)", c); }
     rev2 = (long_double*) realloc(rev2, (r2+1)*sizeof(long_double)); addressed( rev2, "rev2 realloc (2)", (r2+1));

     // r2=0;
     for (u=0; u<r1; u++)
     {
      if (*(*(h1+u)+ii)==0)
      {
       *(rev2+r2)=*(rev1+u);
       for (uu=0; uu<c; uu++) *(*(h2+r2)+uu)=*(*(h1+u)+uu);
       r2++;
       h2 = (long_double**) realloc(h2, (r2+1)*sizeof(long_double*)); addressed(h2, "h2 realloc (1)", r2+1);
       {*(h2+r2)  =(long_double*)calloc(c, sizeof(long_double));    addressed( *(h2+r2), "*(h2+r2) not allocated (6)", c); }
       rev2 = (long_double*) realloc(rev2, (r2+1)*sizeof(long_double)); addressed( rev2, "rev2 realloc (2)", (r2+1));
       // if(r2>r02) {printf("error4"); getch(); exit(1);}
      }
     }
     for (i=0; i<r1; i++) 
     {
      if (*(*(h1+i)+ii)>0) 
      {
       for (u=0; u<r1; u++) 
       {
        if (*(*(h1+u)+ii)<0)
        {
         *(rev2+r2)=1.0; k1=*(*(h1+i)+ii); k2=*(*(h1+u)+ii);
         abs_hi=(*(*(h1+i)+ii)>=0 ? *(*(h1+i)+ii) : -*(*(h1+i)+ii)); // FM
         abs_hu=(*(*(h1+u)+ii)>=0 ? *(*(h1+u)+ii) : -*(*(h1+u)+ii)); // FM
         ggt_Erg=ggt(abs_hi,abs_hu);  // FM
         k1/=ggt_Erg; k2/=ggt_Erg;    // FM
         for (uu=0;uu<c;uu++)
         { 
          numerical_array(k2, *(*(h1+i)+uu), k1, *(*(h1+u)+uu), 1, 1, 1, "loop 4");
          *(*(h2+r2)+uu)=fabsl(k2)**(*(h1+i)+uu)+fabsl(k1)**(*(h1+u)+uu); 
          // if(fabsl(*(*(h2+r2)+uu))<1E-9) *(*(h2+r2)+uu)=0.0;
          // else 
          *(*(h2+r2)+uu)=rund(*(*(h2+r2)+uu), 0);
         }
         test1=1;
         for (tu=0;tu<r2;tu++) 
         {
          test1=0;
          for (uu=counter;uu<c;uu++)
          {
           if ((*(*(h2+r2)+uu)==0)&&(*(*(h2+tu)+uu)!=0)) {test1=1;break;}
          }
          if (test1==0) break;
         }
         if (test1==1)
         { r2++; 
           h2 = (long_double**) realloc(h2, (r2+1)*sizeof(long_double*)); addressed(h2, "h2 realloc (1)", r2+1);
           {*(h2+r2)  =(long_double*)calloc(c, sizeof(long_double));    addressed( *(h2+r2), "*(h2+r2) not allocated (6)", c); }
           rev2 = (long_double*) realloc(rev2, (r2+1)*sizeof(long_double)); addressed( rev2, "rev2 realloc (2)", (r2+1));
           //if(r2>r02) {printf("error5"); getch(); exit(1);}
         }
        }
       }
      }
     }
    }
    for(i=0;i<r1;i++) free (*(h1+i)); free (h1); free(rev1); 
    h1=h2; rev1=rev2; r1=r2; //* cf. modes !!!! -> */ r2=r02;
    help->head=h1; help->row=r1; help->col=c;
    // control_condition7( help, ii, rev1, &r1 ); /* FM 20.10.2000 condition (7) */
    for(i=r1;i<=r2;i++)
      free(*(help->head+i));
    r2=r1;
    ggt_matrix(help);
    // printf("result tab %d row %d\n", ii,r1); // getch();
    //free( *(h2+r2));
    if(!help->row) break;
   }
 free(rev2);   // otherwise memory leak
 help->head=h2; help->row=r2; help->col=c;
 
 // for(i=r2; i>r1; i--) free(help->head+i); 
 if(help->row)
 {
  k=cutcol(help,counter);
  freemat(help);
  help=simplify(k);freemat(k);
 }
 // free(help_v);
 switch_if_all_row_is_minus_into_plus(help);
 return help;
} // basis

/* modes */
struct mat *modes (struct mat *m, struct vector *v)
{
 struct mat *help, *k;                       /* help matrices */
 long_double **h1, **h2, abs_hi, abs_hu, ggt_Erg;  /* pointer to current and nex tab */
 long_double *rev1, *rev2,k1,k2;                           /* corresponding revesibilities */
 int i,u,ii,uu,tu;                           /* counter */
 int r1,r2,c, counter, test1, r01, ok_4=1, r02;

 k=transp(m);help=addi(k);freemat(k);
 h1=help->head;
 r1=(help->row); c=help->col; counter=m->row;
 r01=r2=r1;
 rev1=(long_double*)calloc(v->row,sizeof(long_double));   addressed( rev1, "rev1 not allocated (5.5)", v->row);
 for (i=0;i<v->row;i++) {*(rev1+i)=*(v->head+i);if(fabsl(*(rev1+i))<1E-9) *(rev1+i)=0.0;}
 // printf("first alloc %d\n", r1 );
 for (ii=0; ii<counter; ii++)
 {
  // printf("allocate ");
  rev2=(long_double*) calloc(1, sizeof(long_double) );   addressed( rev2, "rev2 not allocated (7)", 1);
  h2  =(long_double**)calloc(1, sizeof(long_double*));   addressed( h2, "h2 not allocated (6)", 1);
   r2=0;
   for (i=0; i<r1; i++)
    if (!(*(*(h1+i)+ii)))                 /* taking zero rows to the nex tab */
    {
     {h2=(long_double**)realloc(h2, (r2+1)*sizeof(long_double*)); addressed( h2, "h2 not allocated (8)", r2+1); }
     {*(h2+r2)  =(long_double*)calloc(c, sizeof(long_double));    addressed( *(h2+r2), "*(h2+r2) not allocated (6)", c); }
     rev2=(long_double*) realloc(rev2, (r2+1)*sizeof(long_double) );   addressed( rev2, "rev2+r2 not allocated (7) in realloc", r2+1);
     *(rev2+r2)=*(rev1+i);
     for(uu=0;uu<c;uu++) *(*(h2+r2)+uu)=*(*(h1+i)+uu);
     // printf("%d ", ++r2);
     ++r2;
    }else;
    r02=r2;
    ok_4=1;
    for (i=0; i<r1; i++) 
     if ((*(*(h1+i)+ii))&&(!(*(rev1+i)))) /* reversible combinations */
     {
      for (u=i+1; u<r1; u++)
       if ((*(*(h1+u)+ii))&&(!(*(rev1+u))))
       {
        if(ok_4) // FM 23.07.2001 while(r02<=r2) /* 1 */
        {h2=(long_double**)realloc(h2, (r2+1)*sizeof(long_double*)); addressed( h2, "h2 not allocated (8)", r2+1);
         *(h2+r2)  =(long_double*)calloc(c, sizeof(long_double));    addressed( *(h2+r2), "*(h2+r2) not allocated (6)", c);
         rev2=(long_double*) realloc(rev2, (r2+1)*sizeof(long_double) );   addressed( rev2, "rev2+r2 not allocated (7) in realloc", r2+1);
         r02++;
        }
        *(rev2+r2)=0.0; k1=*(*(h1+i)+ii); k2=*(*(h1+u)+ii);
        abs_hi=(*(*(h1+i)+ii)>=0 ? *(*(h1+i)+ii) : -*(*(h1+i)+ii)); // FM
        abs_hu=(*(*(h1+u)+ii)>=0 ? *(*(h1+u)+ii) : -*(*(h1+u)+ii)); // FM
        ggt_Erg=ggt(abs_hi,abs_hu);  // FM
        k1/=ggt_Erg; k2/=ggt_Erg;    // FM
        for (uu=0;uu<c;uu++)
        {  
           numerical_array( k2, *(*(h1+i)+uu), k1, *(*(h1+u)+uu), 0, 1, -1, "loop 007");
           *(*(h2+r2)+uu)=k2**(*(h1+i)+uu)-k1**(*(h1+u)+uu);
           *(*(h2+r2)+uu)=rund(*(*(h2+r2)+uu), 0);
        }

        test1=1;
        for (tu=0;tu<r2;tu++)
        {
         test1=0;
         for (uu=counter;uu<c;uu++)
         {
           if ( *(*(h2+r2)+uu)==0.0 && *(*(h2+tu)+uu) ) {test1=1;break;} // 26.09.2001 hier waren die r2 und tu vertauscht (Sascha)
         }
         if (test1==0) break; // 06.03.01
        }
        if (test1==1){
         // printf("%d ", ++r2); /* 1 */
         ++r2;
         ok_4=1; // FM 23.07.2001
        }else ok_4=0;
       } // for u
     }  // for i

    for (i=0; i<r1; i++) 
     if ((*(*(h1+i)+ii))&&!(*(rev1+i))) /* rev-irrev combinations */
     {
      for (u=0; u<r1; u++) 
       if ((*(*(h1+u)+ii))&&(*(rev1+u)))
       {
         if(ok_4) // FM 23.07.2001 while(r02<=r2) /* 22 */
         {h2=(long_double**)realloc(h2, (r2+1)*sizeof(long_double*));     addressed( h2, "h2 not allocated (8)", r2+1); 
          *(h2+r2)  =(long_double*)calloc(c, sizeof(long_double));        addressed( *(h2+r2), "*(h2+r2) not allocated (6)", c);
          rev2=(long_double*) realloc(rev2, (r2+1)*sizeof(long_double) ); addressed( rev2, "rev2+r2 not allocated (7) in realloc", r2+1);
         r02++;
         } 
         *(rev2+r2)=1.0; k1=(*(*(h1+i)+ii)); k2=(*(*(h1+u)+ii));
         abs_hi=(*(*(h1+i)+ii)>=0 ? *(*(h1+i)+ii) : -*(*(h1+i)+ii)); // FM
         abs_hu=(*(*(h1+u)+ii)>=0 ? *(*(h1+u)+ii) : -*(*(h1+u)+ii)); // FM
         ggt_Erg=ggt(abs_hi,abs_hu);  // FM
         k1/=ggt_Erg; k2/=ggt_Erg;    // FM
         if (k1*k2<0)
           for (uu=0;uu<c;uu++)
           {
             numerical_array( k2, *(*(h1+i)+uu), k1, *(*(h1+u)+uu), 1, 1, 1, "loop5");
             *(*(h2+r2)+uu)=fabsl(k2)**(*(h1+i)+uu)+fabsl(k1)**(*(h1+u)+uu);
             *(*(h2+r2)+uu)=rund(*(*(h2+r2)+uu), 0);
           }
         if (k1*k2>0) // ooo
           for (uu=0;uu<c;uu++)
           {
             numerical_array( k2, *(*(h1+i)+uu), k1, *(*(h1+u)+uu), 1, -1, 1, "loop 6");
             *(*(h2+r2)+uu)=-fabsl(k2)**(*(h1+i)+uu)+fabsl(k1)**(*(h1+u)+uu);
             *(*(h2+r2)+uu)=rund(*(*(h2+r2)+uu), 0);
           }
         test1=1;
         for (tu=0;tu<r2;tu++)
         {
          test1=0;
          for (uu=counter;uu<c;uu++)
          {
           if ((*(*(h2+r2)+uu)==0)&&(*(*(h2+tu)+uu)!=0)) {test1=1;break;}
          }
          if (test1==0) break;
         }
         if (test1==1){
           // printf("%d ", ++r2); /* 2 */
           ++r2;
           ok_4=1; // FM 23.07.2001
         }else ok_4=0; // FM 23.07.2001
       } // for u
     } // for i
    for (i=0; i<r1; i++) 
     if ((*(*(h1+i)+ii)>0)&&(*(rev1+i))) /* irrev combinations */
     {
      for (u=0; u<r1; u++) 
       if ((*(*(h1+u)+ii)<0)&&(*(rev1+u)))
       {
        if(ok_4) // FM 23.07.2001 while(r02<=r2) /* 333 */
        {h2=(long_double**)realloc(h2, (r2+1)*sizeof(long_double*));     addressed( h2, "h2 not allocated (8)", r2+1);
         *(h2+r2)  =(long_double*)calloc(c, sizeof(long_double));        addressed( *(h2+r2), "*(h2+r2) not allocated (6)", c);
         rev2=(long_double*) realloc(rev2, (r2+1)*sizeof(long_double) ); addressed( rev2, "rev2+r2 not allocated (7) in realloc", r2+1);
         r02++;
        }
        *(rev2+r2)=1.0; k1=fabsl(*(*(h1+i)+ii)); k2=fabsl(*(*(h1+u)+ii));
        abs_hi=(*(*(h1+i)+ii)>=0 ? *(*(h1+i)+ii) : -*(*(h1+i)+ii)); // FM
        abs_hu=(*(*(h1+u)+ii)>=0 ? *(*(h1+u)+ii) : -*(*(h1+u)+ii)); // FM
        ggt_Erg=ggt(abs_hi,abs_hu);  // FM
        k1/=ggt_Erg; k2/=ggt_Erg;    // FM
        for (uu=0;uu<c;uu++)
        {
          numerical_array( k2, *(*(h1+i)+uu), k1, *(*(h1+u)+uu), 0, 1, 1, "loop 7");
          *(*(h2+r2)+uu)=k2**(*(h1+i)+uu)+k1**(*(h1+u)+uu);
          *(*(h2+r2)+uu)=rund(*(*(h2+r2)+uu), 0);
        }
        test1=1;
        for (tu=0;tu<r2;tu++)
        {
         test1=0;
         for (uu=counter;uu<c;uu++)
         {
          if ((*(*(h2+r2)+uu)==0)&&(*(*(h2+tu)+uu)!=0)) {test1=1;break;}
         }
         if (test1==0) // than all zeros containing in r2 too in tu; condition (4) in www2.bioinf.mdc-berlin.de/metabolic/metatool/algorithm.pdf
            break;
        }
        if (test1==1){
          // printf("%d ", ++r2); /* 3 */
          ++r2;
          ok_4=1; // FM 23.07.2001
        }else ok_4=0; // FM 23.07.2001
       } // for u
     } // for i
    // printf("release %d\t", r01);
    for(i=0;i<r01;i++) free (*(h1+i)); free (h1); free(rev1); 
    h1=h2; rev1=rev2; r1=(r2<=r02?r2:r02); r01=r02; // r02
    // printf("\nresult modes tab %d row %d\n",ii,r1);
    help->head   = h1;   help->row  =r1; help->col=c;
    control_condition7( help, ii, rev1, &r1 ); // r1=help->row; /* FM 20.09.2000 condition (7) in www2.bioinf.mdc-berlin.de/metabolic/metatool/algorithm.pdf */
    r2=r1; // FM 23.07.2001
    ggt_matrix( help );
    if(!help->row) break; // 06.03.01
 } // for ii
 free(rev2); // otherwise memory leak FM
 while(r02>r1)
   {free(*(h1+(r02-1))); r02--;}
 help->head=h1; help->row=r1; help->col=c;
     ggt_matrix(help); // FM 15.06.2001
 if(help->row)
 {
   k=cutcol(help,counter); 
   freemat(help);
   help=simplify(k);
   freemat(k);
   // print_mat(help);
 }
 switch_if_all_row_is_minus_into_plus(help);
 return help;
} // modes


/* ************************************************************************************ */        
/* 3. other functions ***************************************************************** */
/* ************************************************************************************ */
/* function compstr */
  int compstr (int m, char t1[100], char t2[100])
    	  {
    	  int i;
    	  int k=1;
    	  for (i=0; i<m; i++)
      		  {
      		  if ((t1[i]=='\0')&&(t2[i]=='\0')) break;
      		  if (t1[i]!=t2[i]) {k=0; break;}
      		  }
    	  return k;
    	  }

inline long_double ldmod( long_double u, long_double v);
/* function biggest common divisor */
long_double ggt (long_double u, long_double v)
{
 long_double t, r;
 u=fabsl(u); v=fabsl(v);
 if(!(u*v))                return(u+v);
 else if(u==v)             return u;
 else if(u==1.0 || v==1.0) return ((long_double)1.0);
 if (u<v)
 {t=u; u=v; v=t;}
 r=u;
 while (r>0)
 {
   u = rund(u, 0); v=rund(v, 0);
   r = (long_double)ldmod(u,v);
   u=v;  v=r;
 }
 return (u);
} /* ggt */

void ggt_matrix (struct mat *v)
{
 // divide each row of the new tableau through the greatest common denominator of this row
 long_double denominator, abs1;
 int c, r, y_n;
 //*->*/    printf("v r%d x c%d", v->row, v->col);   print_mat( v );
 for(r=0; r<v->row; r++) 
 {
  // for(j=0; j<v->col; j++) if( *(*(v->head+r)+j) == 1 || *(*(v->head+r)+j) == -1) goto NEXT_ROW;
  denominator=1.0;y_n=1;
  for(c=0; c<v->col; c++) 
  { 
   abs1 = fabsl(*(*(v->head+r)+c));
   /**/ if(abs1==1.0)
    {denominator=1.0; break;}
   else /**/ if(abs1) 
   { if(y_n==1)denominator=abs1; // this command is for initialisation of denominator 
     else denominator=ggt(denominator, abs1);
     y_n=0;
   } 
  }
  /**/if(denominator > 1)
   for( c=0; c<v->col; c++)
    if(*(*(v->head+r)+c)) 
    {  *(*(v->head+r)+c)/=denominator; /* rund (*(*(v->head+r)+c), 0);*/ }
  // NEXT_ROW:;
 }
 //*->*/    printf("v r%d x c%d", v->row, v->col);   print_mat( v );
} // ggt_matrix

void ggt_matrix_simple_algorithm (struct mat *v) 
{
 long_double denominator, min, i, abs1;
 int c, r, counter, non_zero;
 //*->*/    printf("v r%d x c%d", v->row, v->col);   print_mat( v );
 for(r=0; r<v->row; r++) 
 {
   min = DBL_MAX;
   denominator=0;
   for(c=0; c<v->col; c++) 
   { 
     abs1=fabsl(*(*(v->head+r)+c));
     if(abs1) min = abs1<min? abs1 : min; else;
   }
   i=2.0;
   while(i<=min)
   { 
    for( non_zero=counter=c=0; c<v->col; c++ )
     if(*(*(v->head+r)+c) ) 
     {
       if( floorl( *(*(v->head+r)+c)/i ) == ceill( *(*(v->head+r)+c)/i )) counter++;
       non_zero++;
     }
    if(counter==non_zero) denominator=i;
    i++;
   };
  if(denominator)
   for( c=0; c<v->col; c++)
    if(*(*(v->head+r)+c)) *(*(v->head+r)+c)/=denominator;
 }
 //*->*/    printf("v r%d x c%d", v->row, v->col);   print_mat( v );
} // ggt_matrix

int delete_zero_line(struct mat *a, int zero_line)
{
 int i, j;
 
 if(zero_line<a->row-1)
  for( i=zero_line; i<a->row; i++ )
   for( j=0; j<a->col; j++ )
     *(*(a->head+i)+j) = *(*(a->head+i+1)+j);
 free( *(a->head+(a->row-1))); 
 a->row--;
 return 0;
} //delete_zero_line

inline long_double ldmod( long_double u, long_double v)
{
  if(u==v) return 0;
  else if(u>v)  return (u-floorl(u/v)*v);
  else return (v-floorl(v/u)*u);
}

// genreate file names for input and output files
int get_filein_fileout(int argn, char** files_in_out, char f[4][_MAX_PATH], int*VarInit)
{
 char fname[_MAX_PATH]; 
 int i;
 if(argn==4) *VarInit=2;
 if( argn != 3 && argn!=4 ) 
 {
   printf("\nMETATOOL [path]inputfile [path]outputfile\n\n");
   printf("\nFilenames as program parameters are not found\n\n");
   printf("\nPlease type in the source file name with metabolic reaction eqations:\n");
   printf("\n-> "); scanf("%s", f[1]);
   printf("\nand type in the file name for METATOOL output:\n");
   printf("\n-> "); scanf("%s", f[2]);
 }
 else 
 {  
   strcpy( f[1], files_in_out[1] );
   strcpy( f[2], files_in_out[2] );
 }
 if( !strcmp(f[1], f[2]) )
 {printf("\nThe name of input file\n%s\nis the same as the name of the output file\n%s\nProgram prematurely finished.", f[1], f[2]); getch(); exit(1); }
 strcpy( f[0], files_in_out[0] );

 strcpy(fname, f[2]);
   i=strlen(fname); 
   do{ --i; }
   //  while(fname[i]!='\\' && fname[i]!='/' && i);
     while(fname[i]!='.' && i);
   //if(i) strcpy(&fname[i], "\\combis.txt");
   //else  strcpy(&fname[i], "combis.txt");
   if(i) strcpy(&fname[i], ".cmb");
 strcpy( f[3], fname );

 return 0;
} // get_filein_fileout

int detect_double_declared_enzymes( struct enc *list )
{
  struct enc *a, *b;

  a=list;
  do{
   a=a->next;
   b=a->next;
   while( b!=b->next)
   {
     if( !strcmp(a->txt, b->txt)) 
     { 
       printf("\nEnzyme ->%s<- is delared twice", a->txt );
       if     ( !a->rev && !b->rev) printf(" as reversible.");
       else if(  a->rev &&  b->rev) printf(" as irreversible.");
       else                          printf(" as reversible and as irreversible.");
       printf("\nplease press ENTER"); getch(); printf("\r                  \r");
     }
     b=b->next;
   }
  }while(a != a->next);

  return 0;
} // detect_double_declared_enzymes

int detect_double_declared_metabolites( struct enc *metlist )
{
 int int_ext1, int_ext2, i, j, met_counter=0;
 struct enc *ml1;
 struct enc *ml2;

 ml1=metlist; ml2=metlist;
 int_ext1=metlist->rev;
 
 while(ml1!=ml1->next)
 { met_counter++; ml1=ml1->next;}
 
 ml1=metlist;
 ml1=metlist->next; int_ext1=ml1->rev;

  for(i=0; i<met_counter-1; i++)
  {
   ml2=ml1->next; int_ext2=ml2->rev;
   for(j=i+1; j<met_counter; j++ )
   {
    if(!strcmp(ml1->txt, ml2->txt))
    {
     printf("\nMetabolite ->%s<- is declared twice ", ml1->txt);
     if     ( !int_ext1 && !int_ext2 ) printf("as internal.");
     else if(  int_ext1 &&  int_ext2 ) printf("as external.");
     else                            printf("as internal and external.");
     printf("\nPlease change your input file.");
     printf("\nplease press ENTER"); getch(); printf("\r                  \r"); 
     return 1;
    }
    ml2=ml2->next;int_ext2=ml2->rev;
   } // for j
   ml1=ml1->next; int_ext1=ml1->rev;
  } // for i
  return 0;
} // detect_double_declared_metabolites

int control_modi (struct mat *m, FILE *savefile, struct enc *enzlist)
{
 int r1, r2, n=0, k, not_zero_r1, not_zero_r2, same;
 // struct enc *enznames;

 for(r1=0; r1<m->row-1; r1++ )
 {
   for( not_zero_r1=k=0; k<m->col; k++)
     if(*(*((m->head)+r1)+k)) not_zero_r1++;
   // fprintf(savefile, "%d\t%d\n", r1+1, not_zero_r1);
 
   for(r2=r1+1; r2<m->row; r2++)
   {
     /*not_zero_r1=*/not_zero_r2=same=0;
     for( k=0; k<m->col; k++)
     {  
       // if(*(*((m->head)+r1)+k)) not_zero_r1++;  // line is moved 04.02.2002
       if(*(*((m->head)+r2)+k)) not_zero_r2++;
       if(*(*((m->head)+r1)+k) && *(*((m->head)+r2)+k) ) same++;
     }
     if( (same == not_zero_r1 || same == not_zero_r2) && same && not_zero_r1 && not_zero_r2 )
     {  
       if(not_zero_r2 > not_zero_r1)     printf("\nElementary mode %d (%d) contains elementary mode %d (%d).", r2+1, not_zero_r2, r1+1, not_zero_r1 );
       else if(not_zero_r2==not_zero_r1) printf("\nElementary mode %d (%d) and %d (%d) are identical.", r2+1, not_zero_r2, r1+1, not_zero_r1 );
       else                              printf("\nElementary mode %d (%d) contains elementary mode %d (%d).", r1+1, not_zero_r1, r2+1, not_zero_r2 );

       if(not_zero_r2 > not_zero_r1)     fprintf(savefile, "\nElementary mode %d (%d) contains elementary mode %d (%d).", r2+1, not_zero_r2, r1+1, not_zero_r1 );
       else if(not_zero_r2==not_zero_r1) fprintf(savefile, "\nElementary mode %d (%d) and %d (%d) are identical.", r1+1, not_zero_r1, r2+1, not_zero_r2 );
       else                              fprintf(savefile, "\nElementary mode %d (%d) contains elementary mode %d (%d).", r1+1, not_zero_r1, r2+1, not_zero_r2 );
       n=1;
     }
   }
 }
 
 // for( not_zero_r1=k=0; k<m->col; k++)     
 //  if(*(*((m->head)+r1)+k)) not_zero_r1++;
 // fprintf(savefile, "%d\t%d\n", r1+1, not_zero_r1);
 if(n) { printf("\n");fprintf(savefile, "\n"); }
 // control which enzymes not occur in modes
 /*
 enznames = enzlist;
 for(k=0, r1=0; r1<m->col; r1++ )
 {
  enznames = enznames->next;
  for(r2=0; r2<m->row; r2++)
  {
   if(*(*((m->head)+r2)+r1)) {k++; break;}
  }
  if(r2==m->row) 
     fprintf(savefile, "%s\t", enznames->txt);
 }
 if(k!=m->col) fprintf(savefile, "\n%d enzymes are not involved in reactions\n", m->col-k ); 
 */
 return 0;
} // control_modi

int stack_down(struct mat *m, int r1 )
{
 // matrix h2 overwrite the line r1 with the following line and so on
 int i, j, col;
 for(i=r1; i<m->row-1; i++ )
 {
   for( j=i+1, col=0; col<m->col; col++)
       *(*(m->head+i)+col) = *(*(m->head+j)+col);
 }
 // do not free( *(m->head+j) ); that memory is freed in modes with the variable r01 at line 1590
 m->row--;
 return 0;
} // stack_down

int stack_down_rev(long_double *rev1, int r1, int row )
{
 // vector rev1 stack_down
 int i, j;
 // realloc ???
 for(i=r1; i<row-1; i++ )
 {
   for( j=i+1; j<row; j++)
       *(rev1+i) = *(rev1+j);
 }
 // do not free( *(m->head+j) ); that memory is freed in modes with the variable r01 at line 1590
 return 0;
} // stack_down_rev

int control_condition7 (struct mat *m, int ii, long_double *rev1, int *r01 )
{
 int r1, r2, c, zero_r1, same12;
 int zero_r2; // FM 04.02.2002

 if(m->row>1)
 for(r1=0; r1<m->row-1; r1++ )
 {
   for( zero_r1=0, c=ii; c<m->col; c++)
       if(!*(*(m->head+r1)+c)) zero_r1++;  // FM 04.02.2002 siehe ein paar Zeilen weiter unten
   for(r2=r1+1; r2<m->row; r2++)
   {
     /*zero_r1=*/zero_r2=same12=0;
     for( c=ii; c<m->col; c++)
     {  
       // if(!*(*(m->head+r1)+c)) zero_r1++;  // FM 04.02.2002 siehe ein paar Zeilen weiter oben
       if(!*(*(m->head+r2)+c)) zero_r2++; 
       if(!*(*(m->head+r1)+c) && !*(*(m->head+r2)+c) ) same12++;
     }
     if(zero_r1 == same12) // changed in comparison to meta3.5_int FM 23.07.2001
     // if( *(rev1+r1) && *(rev1+r2) )// changed in comparison to meta3.5_int FM 23.07.2001
     // if(zero_r2>=same12 && zero_r1==same12 ) // 04.02.2002
     { 
       stack_down(m, r1); // da dann mehr Nullen in r2 stehen als in r1 fliegt die Zeile r1 raus
       stack_down_rev( rev1, r1, m->row+1 ); // r2--;
       zero_r1=zero_r2;
       r1--; break;
     }
   }
 }
 (*r01)=m->row;
 return 0;
} // control_condition7

struct vector unbalanced_mets(struct mat *n, struct enc *metlist, struct enc *enzlist)
{
 int r, c, counter, count_irrev, sum;
 struct enc *ml, *el;
 struct vector um;
 //*->*/    printf("n r%d x c%d", n->row, n->col); print_mat(n); 
 um.head = (long_double *) calloc(met_counter, sizeof(long_double)); addressed(um.head, "um.head", met_counter);
 um.row  = 0;
 // printf("The following metabolites occur only once | (are only consumed | only formed in irreversible reactions).\nTherefore they are set ever external.\n(Same order as in inputfile)\n");
 
 ml = metlist->next;
 for(r=0; r<n->row; r++)
 {
   sum=0;
   counter=0; count_irrev=0; el=enzlist->next;
   for(c=0; c<n->col; c++)
   {  
     if( *(*(n->head+r)+c) ) 
     {  counter++; sum+=(int)*(*(n->head+r)+c);
        if( el->rev ) count_irrev++;
     }
     el=el->next; 
   }
   // metabolite occurring only once or formed or consumend only in irrev reactions
   // 12.11.2001: setze alle Metabolite mit ominöser Festlegung, daß die Connectivität größer als 5 ist als external
   // if( (counter==1 || (counter==count_irrev && ml->consumed+ml->built==1)) || ml->reactions>4)
   // sonst 
   if( counter==1 || (counter==count_irrev && ml->consumed+ml->built==1) )
   {
     *(um.head+r)=r+1;  // set external
     um.row++;
     ml->rev=1;
     // printf("%s\n", ml->txt);
   }
   else if(counter==2 && sum && count_irrev==2 )
   {
     *(um.head+r)=r+1;  // set external
     um.row++;
     ml->rev=1;
     printf("\7\7\nHier solltest Du gar nicht reinkommen\n"); getch();
   }
   else
   {
     *(um.head+r)=0;  // set internal
     ml->rev=0;
   }
   ml = ml->next;
 } // for r
 return um;
} // unbalanced_mets

struct vector set_as_extern(struct enc *metlist, struct vector *um, struct vector *ei )
{
 int r=0;
 struct enc *ml;
 struct vector sae;

 // Speicher bereitstellen für den Vector sai, der die metabolitnummern enhält, die immer als intern zu setzen sind
 ei->head=(long_double*) calloc(met_counter, sizeof(long_double)); 
 addressed(ei->head, "ei->head", met_counter);
 ei->row=0;
 
 //*->*/    printf("n r%d x c%d", n->row, n->col); print_mat(n); 
 sae.head = (long_double *) calloc(met_counter, sizeof(long_double)); addressed(sae.head, "sae.head", met_counter);
 sae.row=0;
 ml = metlist->next;
 do{
   if( ml->reactions>2 && !*(um->head+r) )  
     { *(sae.head+r)=1;  sae.row++;  *(ei->head+r)=r+1; ei->row++; /* only these set as external */ }
   else
     *(sae.head+r)=0;  // not to set as external
   ml = ml->next;
   r++;
 }while(ml!=ml->next);
 for(r=0; r<met_counter; r++)
   if( *(sae.head+r) || *(um->head+r) ) 
       *(sae.head+r)=1;
 return sae;
} // set_as_extern


int allocate_VarVect(int** VarVect, int**VarVect1, int **InitVect, int n)
{
 *VarVect=(int*) calloc(n, sizeof(int));
 addressed(*VarVect, "VarVect", n );
 *VarVect1=(int*) calloc(n, sizeof(int));
 addressed(*VarVect1, "VarVect1", n );
 *InitVect=(int*) calloc(n, sizeof(int));
 addressed(*InitVect, "InitVect", n );
 return 0;
} // allocate_VarVect

int change_intern_extern_mets(int*VarVect1, int *nx1, struct vector *met, struct vector ei, char* res0, struct vector um )
{
 int i, j, index, max, pos;
 for(        i=0; i<met_counter; i++) VarVect1[i]=0;
 for(*nx1=0, i=0; i<ei.row;      i++)
  if(res0[i])   (*nx1)++;   else;
 
 for(j=0, i=ei.row-1; i>=0; i--) 
 { if(res0[i]) 
   {index=(int)*(ei.head+i); VarVect1[j++]=index; } 
 }
 for( i=0; i<met->row; i++) *(met->head+i)=0;
 for( i=-1; j<met_counter; j++ )
 { 
   do{i++;}while(i<met_counter && !um.head[i]);
   if(i==met_counter) break;
   VarVect1[j] = (int)um.head[i]; 
 }
 
 (*nx1)+=um.row;
 // sortiere VarVect1 absteigend
 for( j=0; j<*nx1; j++ )
 {
  for( pos=0, max=INT_MIN, i=j; i<*nx1; i++ ) 
  { 
   if(VarVect1[i]>max) 
     {max=VarVect1[i]; pos=i;} 
  }
  VarVect1[pos] = VarVect1[j];
  VarVect1[j]=max; 
 }
 
 for( i=0; i<*nx1; i++)
 {
  *(met->head+ ((VarVect1[i])-1) ) = 1;
 }
 return 0;   
} // change_intern_extern_mets


int res0_init(char* res0, int *nx1, struct vector ei, int*VarVect1, 
              struct vector um, char*res1, char*uebertrag, unsigned long *ulii)
{
 int i, j, index, max, pos, hv[NN]; //, nx_hv;
 // FILE *fp_out;
 // fp_out=fopen("c:\\quelltxt\\mdc\\metatool\\vollst\\test.cmb", "w");
 // if(fp_out==NULL) { perror("test.cmb : "); getch(); exit(1);}
 *ulii=0;
 // for( i=0; i<ei.row; i++) fprintf(fp_out, "\t%.0Lf", ei.head[i]); fprintf(fp_out, "\n" );
 // for( i=0; i<*nx1; i++) fprintf(fp_out, "\t%d", VarVect1[i]); fprintf(fp_out, "\n" );
 do{
  (*ulii)++;
  for(i=0; i<NN; i++) hv[i]=0;

  for(j=0, i=0; i<ei.row; i++) 
  { if(res0[i]) 
    {index=(int)*(ei.head+i); hv[j++]=index; }  // VarVect1[j++]=index; 
  } 
  // put in the always setted metabolites 
  for( i=-1; j<met_counter; j++ )
  { 
   do{i++;}while(i<met_counter && !um.head[i]);
   if(i==met_counter) break;
   hv[j] = (int)um.head[i];  // VarVect1[j] = (int)um.head[i]; 
  }
  // sortiere hv absteigend
  for( j=0; j<*nx1; j++ )
  {
   for( pos=0, max=INT_MIN, i=j; i<*nx1; i++ ) 
   { 
    if(hv[i]>max) 
     {max=hv[i]; pos=i;} 
   }
   hv[pos] = hv[j];
   hv[j]=max; 
  }
 
  // check if VarVect1 and hv are equal 
  for(max=i=0; i<met_counter; i++)
  {
     if(hv[i]==VarVect1[i] && hv[i]) max++;
     // if(hv[i]) nx_hv++;
  }
  printf("\r");
  for(i=ei.row-1; i>-1; i--)
  { 
   if     ( res0[i]&& uebertrag[i+1]) { res1[i]=0; uebertrag[i]=1; }
   else if(!res0[i]&&!uebertrag[i+1]) { res1[i]=0; uebertrag[i]=0; }
   else                               { res1[i]=1; uebertrag[i]=0; }
  }
  for(i=0; i<ei.row; i++) 
      { res0[i]=res1[i]; printf("%d", (int)res0[i]); } 
  if(max==*nx1) break;
  // if(nx_hv==53) {fprintf(fp_out, "%Ld", *ulii ); for( i=0; i<nx_hv; i++) fprintf(fp_out, "\t%d", hv[i]); fprintf(fp_out, "\n" );} fflush(fp_out);
  // printf("\n");for( i=0; i<met_counter; i++) printf("%d\t", hv[i]);
  if(uebertrag[0]) break;
 }while(1);
 return 0;   
} // res0_init

/* ******************************************************************************** */
// in the past the functions were written in the separate source file schleifen2.cpp
#undef isspace

#define TRUE	1
#define TXT   200

double AnzTeilKombinationen(int n, int k, int nx);
int           VarKreuzVal(char *datapath, char *tmp_File);

int sort_function(const int *a, const int *b)
{
  if ( *a  < *b ) return(1);
  else if ( *a == *b ) return(0);
  else return( -1 );
};

double VarVect_Init( int *nx, int* VarVect, const int Anz_Var, struct vector um )
{
 int i, col, h[NN];
 double z=0;
 
 // stack down um
 for( col=i=0; i<met_counter; i++ )
 {
     if( *(um.head+i) && !(*(um.head+i)&&i==0))
     { *(um.head+col)=*(um.head+i); *(um.head+i)=0; col++;}
     else if(*(um.head+0)&&!i) col++;
 }

 typedef int (*fcmp) (const void *, const void *);

 *nx=0;
 for(i=0;i<NN;i++)
 {
   if(*(um.head+i) && i<met_counter )
   {
    h[i]=(int)*(um.head+i);
    (*nx)++;
   }
   else 
    h[i]=0;
 }
 qsort((void *)h, (*nx)+1, sizeof(h[0]), (fcmp) sort_function);
 for( i=0; i<=*nx; i++ )
  (VarVect[i]) = h[i];
 // intercept error, if in Varinit.txt is given a too large index
 if((VarVect[0]) > Anz_Var )
 {printf("\nAt least one of the indices of variables in varinit.txt is larger then %d.\nProgramm vorzeitig beendet.", Anz_Var); getch(); exit(1);}

 return (z-1.0);
} //VarVect_Init

int VarVect_Init_1( FILE* fcomb, int *nx, int *nx1, int* InitVect, const int Anz_Var, 
                    struct vector um, int* VarVect, int* VarVect1, unsigned long *ulii, 
                    char* res0, struct vector ei)
{
 int i, j, col;
 char row[5001], *p;
 
 fgets( row, 5000, fcomb);
 p=strtok(row, "\t");
 *ulii=(unsigned long int)atof(p);
 p=strtok(NULL, " ");
 col=atoi(p);
 for(i=col-1; i>=0; i--)
 {  
   p=strtok(NULL, " "); 
   InitVect[i]=atoi(p); 
 }

 for(i=col; i<NN; i++) InitVect[i]=0;
 *nx=col;
 *nx1=col;
 // intercept error, if the index is too large in varinit.txt 
 if((InitVect[0]) > Anz_Var )
 {printf("\nAt least one of the indices of variables in varinit.txt is larger then %d.\nProgram prematurely finished.", Anz_Var); getch(); exit(1);}
 for(i=0; i<NN; i++) VarVect1[i]=InitVect[i];
 
 i=-1; j=0;
 while(i<*nx){
     while(!InitVect[++i] && i<*nx);
     VarVect[j++]=InitVect[i];
 };

 i=-1; while(VarVect[++i]);
 *nx=i;
 for(i=0; i<ei.row; i++) res0[i]=0;

 return 1;
} //VarVect_Init_1


int foutput(FILE *fout, FILE *fcomb, struct mat* unreduced1, int* VarVect1, struct enc *metlist, int nx1, 
            const unsigned long ulii, int*no_em, struct mat* unreduced, int count_enz, const int ei_um)
{
 int i, j, h[NN], modi, zero_count, zero_lines=0;
 static int a=1, basis;
 struct enc *help;
 
 if(count_enz!=-99) 
 for(i=0; i<unreduced1->row; i++)
 {
  for(zero_count=j=0; j<unreduced1->col; j++ )
    if(!*(*(unreduced1->head+i)+j))zero_count++; else break;
  if( zero_count==unreduced1->col ) 
    zero_lines++;
 }
 if(count_enz!=-99) 
  modi=unreduced1->row-zero_lines;
 if(count_enz==-99) modi=basis=0;
 else basis=unreduced->row;
 
 *no_em=0;
 j=0;
 for(i=0; i<NN; h[i++]=0);
 help=metlist;
 // if(a && ulii==1) { fprintf(fout, "loop\tmean_emlength\tbasis\tmodi\tenzymes\tcount"); for(i=0;i<ei_um;i++) fprintf(fout, "\tmet%d", i+1); fprintf(fout, "\n");}

 fprintf(fout, "#%lu.\t%f\t%d\t%d\t%d\t%d", ulii, m_pathway_length, basis, modi, count_enz, nx1);
 rewind(fcomb); 
 fprintf(fcomb, "%lu\t%d", ulii, nx1 ); // fflush(fcomb);

 i=nx1-1;
 while(i>=0)
 { // fprintf(fout, "%d ", *VarVect1[i]); 
   fprintf(fcomb, " %d", VarVect1[i]); 
   h[j++]=VarVect1[i--];
 }
 // fprintf(fout, "\t"); 
 for(j=i=0; i<met_counter; i++ )
 { 
   help=help->next;
   while((++i)<h[j] && i<met_counter)
      { help=help->next; } 
   i--;
   if( h[j]) 
   { fprintf(fout, "\t%s", help->txt); j++;}
 }
 if(count_enz==-99) fprintf(fout, "\n");
 fprintf(fcomb, "\n");
 a=0;
 return 0;
} // foutput

int foutput_mets( int** VarVect1, struct enc *metlist, int nx1, unsigned long int ulii )
{
 int i, j, h[NN];
 static int y_n=0;
 struct enc *help;
 FILE *fout;
 //if(y_n)
 //{ fout=fopen("mets.txt", "a"); if(fout==NULL) { perror("fout mets.txt "); getch();}}
 //else
 { fout=fopen("mets.txt", "w"); if(fout==NULL) { perror("fout mets.txt "); getch();}}
 y_n=1;
 j=0;
 for(i=0; i<NN; h[i++]=0);
 help=metlist;
 
 fprintf(fout, "%lu.\t%d\t", ulii, nx1);

 i=nx1-1;
 while(i>=0)
 { // fprintf(fout, "%d ", *VarVect1[i]); 
   fprintf(fout, " %d", *VarVect1[i]); 
   h[j++]=*VarVect1[i--];
 }
 // fprintf(fout, "\t"); 
 for(j=i=0; i<met_counter; i++ )
 { 
   help=help->next;
   while((++i)<h[j] && i<met_counter)
      { help=help->next; } 
   i--;
   if( h[j]) 
   { fprintf(fout, "\t%s", help->txt); j++;}
 }
 fprintf(fout, "\n");
 fclose(fout);
 return 0;
} // foutput_mets


int count_enzymes( struct mat* vmode )
{
 int r, c, count=0, *help_v;
 help_v=(int*)calloc(vmode->col, sizeof(int)); 
 addressed(help_v, "help_v in count_enzymes", vmode->col);
 for(r=0; r<vmode->row; r++)
  for(c=0; c<vmode->col; c++)
   if( *(*(vmode->head+r)+c) ) 
    *(help_v+c)=1;
 for(c=0; c<vmode->col; c++) if( *(help_v+c) ) count++;
 free(help_v);
 return count;
}

int mean_path_length(struct mat *vmode)
{
  int r, c, count=0;
  for(r=0; r<vmode->row; r++)
   for(c=0; c<vmode->col; c++)
     if(*(*(vmode->head+r)+c) ) count++;
  m_pathway_length=(float)count/(vmode->row);
  return count;
}


/* ************************************************************************************ */        
/* MAIN *****************************************************************************+* */
/* ************************************************************************************ */
int main(int argn, char *files_in_out[])
{
    FILE          *src,*fout, *fcomb;      /* input/output file */
    struct enc    *enzlist, *metlist;	   /* linked lists of metabolites and enzymes */
    struct mat    *help;			       /* matrix for internal operations */
    struct mat    *nex, *n, *nred;         /* stoich. matrix, reduced, with ext. met */
    struct mat    *vkernel, *vsub;	   	   /* kernel, subsets */
    struct mat    *vbasis, *vmode;		   /* basis, modes */
    struct mat    *unreduced, *unreduced1;  
    struct vector *rev, *redrev, *met;
    struct vector um, sae, ei;             /* unbalanced internal metabolites (frequency == 0), set sae && um as external */
    int    i, ii, **wrong_subset, *no_em, count_enz, ei_um;
    int    *VarVect, *VarVect1, nx, nx1;   /* nx is the number of new x */
    int    VarInit=0, *InitVect;
    unsigned long ulii=0;
    char   f[4][_MAX_PATH];
    char   buf_fcomb[AA], buf_fout[BB]; //262144L 
    long_double   combis;

#ifndef sun
    time_t start, finish;
    time(&start);
#if (defined DOS || defined _DOS || defined WIN32 || defined _WIN32)
    char t1[128], t2[128];
    struct timeb tstruct1, tstruct2;    
    _strtime(t1); ftime( &tstruct1 );
    // printf( "Starting time:\t\t\t\t%s : %u\n", t1, tstruct1.millitm );
#endif
#endif
    
    branch=(struct vector*)0;
    allocate_VarVect(&VarVect, &VarVect1, &InitVect, NN);
    no_em=(int*)calloc(1, sizeof(int)); addressed(no_em, "no_em", 1);
/* genreate file names for input and output files ****************** */
    get_filein_fileout(argn, files_in_out, f, &VarInit );

/* INPUT *********************************************************** */  
    src=fopen(f[1],"r"); if (src==NULL) {perror("file error!"); printf("%s ", f[1]); getch(); return 0;}  
    if(argn==3) 
     { fcomb=fopen(f[3], "w"); if (fcomb==NULL) { printf("->%s<-", f[3]); perror(" "); getch(); exit(1);}}
    else 
     { fcomb=fopen(f[3], "r+"); if (fcomb==NULL) { printf("->%s<-", f[3]); perror(" "); getch(); exit(1);}}

    // set a Filebuffer for minimal harddisc read write
    if (setvbuf(fcomb, buf_fcomb, _IOFBF, AA) != 0)
      printf("failed to set up buffer for input file\n");
 
    // fill in the global array char **metabolites and int met_counter;
    read_comment(src);
    get_metabolites_from_equations( src );

    enzlist=getenzlist(src); 
      rev=getrev(enzlist);
      detect_double_declared_enzymes(enzlist);
    
    metlist=getmetlist(src);
      met=getrev(metlist);

    if( met_counter!=met->row)
    {printf("\nThere are %d metabolites in the stoichiometric equations\nand %d are declared as -METINT or -METEXT\n\nProgram prematurely terminated.", met_counter, met->row);
     mets_which_differ( metlist, met->row );
     if(met_counter<met->row) printf("\n%d metabolite(s) is/are more than one times declared.",met->row-met_counter);printf("\nPlease press ENTER"); getch(); exit(1);}

/* GENERATE THE STOICHIOMETRIC MATRICES  NEX AND N ****************** */
    nex=my_getnex(src,metlist,enzlist); 
    //*->*/    printf("nex r%d x c%d", nex->row, nex->col); print_mat(nex);
    fclose (src);
    if( argn==4) 
      { fout=fopen(f[2],"a+"); if(!fout) {perror("fout-error "), printf("%s", f[2]); getch(); exit(1);}}
    else
      { fout=fopen(f[2],"w"); if(!fout){perror("fout-error "), printf("%s", f[2]); getch(); exit(1);} else fprintf(fout, "loop\tmean_emlength\tbasis\tmodi\tenzymes\tcount");}
    // set a Filebuffer for minimal harddisc read write
    if (setvbuf(fout, buf_fout, _IOFBF, BB) != 0)      printf("failed to set up buffer for input file\n");

/* DETECT NONE BALANCED (INTERNAL METABOLITES) IN N and set them to 1 all others to 0 ******************* */ 
  //*->*/ printf("nex mets r%d x react c%d", nex->row, nex->col); print_mat(nex);
  um = unbalanced_mets(nex, metlist, enzlist); // external mets in ubm == 1
  sae = set_as_extern(metlist, &um, &ei); // mets in "subsets" sae == 1
  for(ii=i=0; i<met_counter; i++) if(!*(sae.head+i)) ii++;else;
  printf("\nThe following %d metabolites with 0 are balanced in two reactions. Therefore, they are set ever internal.\n", ii);
  for(i=0; i<met_counter; i++) printf("%-6d",(int)*(sae.head+i));
  {struct enc ml=*metlist; printf("\n");
   for(i=0; i<met_counter; i++)
   {
    ml=*ml.next; 
    if(!*(sae.head+i)) 
     printf("%-6s", ml.txt); 
    else printf("#     ");
   }
   ml=*metlist; printf("\n");
   // for(i=0; i<met_counter; i++){ml=*ml.next;       printf("%-6s", ml.txt); } printf("\n");
  }
  if(argn==3) {if(um.row || sae.row) VarInit=1;}
  printf("\n\n%d metabolites are observed.\n%d of them are unbalanced and ever set as external.", met_counter, um.row );
  printf("\nThey are:\n");
  {struct enc ml=*metlist;
   for(i=0; i<met_counter; i++){ml=*ml.next; 
   if(*(um.head+i)) printf("%-6s", ml.txt); else printf("#     ");}
   printf("\n");
  }

  printf("\nOnly %d metabolites at branch points are changable as external/internal.", sae.row );
  printf("\nThease are:\n");
  {struct enc ml=*metlist;
   for(i=0; i<met_counter; i++)
   {ml=*ml.next; 
    if(!*(sae.head+i)||*(um.head+i) ) 
    {printf("#     "); ei.head[i]=0; } // hier ist ei zu setzen (Sascha) 26.09.2001
    else  
    {printf("%-6s", ml.txt);ei.head[i]=i+1; }
   }
   printf("\n");
  }
  printf("\nTogether with um they are %d:\n", sae.row+um.row);
  {struct enc ml=*metlist;
   for(i=0; i<met_counter; i++){ml=*ml.next; 
   if(*(sae.head+i)) printf("%-6s", ml.txt); else printf("#     ");}
   printf("\n");
  }
  if(ei.row)
    combis=(long_double) pow(2, ei.row); // take into consideration the empty set
  else 
    { printf("\nNo branch points observed.\nProgram prematurely finished."); getch(); exit(1);}
  printf("\n%Lg combinations of %d branch point metabolites have to be calculated.\n", combis, ei.row ); 
  printf("Please wait %Lf years (provided .5 sec/combination)\n", combis/((long double)2*60*24*365));
  printf("Please press ENTER "); getch(); printf("\r                   \r");

  // ei nachstapeln
  ii=i=0;
  {struct enc ml=*metlist; printf("\n");
  do{
    ml=*ml.next;
    if(ei.head[i])
    { 
      ei.head[ii]=ei.head[i]; ii++;  // printf("%-6s", ml.txt);
    }  
    else; // printf("#     "); 
    i++;
  }while(ii<met_counter && i<met_counter );
  }
  for(; ii<met_counter; ii++) 
    ei.head[ii]=0;
 ei_um = um.row + ei.row;
 // complete the headline in the output file
 for(i=0;i<ei_um;i++) fprintf(fout, "\tmet%d", i+1); fprintf(fout, "\n");

 ///////////// Beginn neue Kombinationen ////////////////////////
 char *res0, *res1, *uebertrag;
 res0=(char*)calloc(ei.row, sizeof(char)); addressed(res0, "res0", ei.row);
 res1=(char*)calloc(ei.row, sizeof(char)); addressed(res1, "res0", ei.row);
 uebertrag=(char*)calloc(ei.row+1, sizeof(char)); addressed(uebertrag, "res0", ei.row+1);
 uebertrag[ei.row]=1;
 for(i=0; i<ei.row; i++) { res0[i]=res1[i]; printf("%d", (int)res0[i]); }
 do{
     {
       // if(VarInit) VarVect_Init( &nx, VarVect, met_counter, um ); VarInit=0;
       if(VarInit==2) 
       { if (VarVect_Init_1(fcomb, &nx, &nx1, InitVect, met_counter, um, VarVect, VarVect1, &ulii, res0, ei)) 
         {
          VarInit=0; printf("\r"); 
          for(i=0; i<ei.row; i++) 
          { res0[i]=res1[i]; printf("%d", (int)res0[i]);}
         } 
         else { printf("\rThe last combination was reached.\n"); break;}
         res0_init(res0, &nx1, ei, VarVect1, um, res1, uebertrag, &ulii);
       }
       // if(ulii>=combis) goto FINISH; 

       change_intern_extern_mets(VarVect1, &nx1, met, ei, res0, um );
       // vectoroutput(met);       
       
       // printf("                  \r%d | ii=%lu\n", nx1, ++ulii);
       printf("\t%d\t\t%lu\r", nx1, ++ulii);

       //*->*/ { printf("nex mets r%d x react c%d", nex->row, nex->col); print_mat(nex); }
       n=cutnex(nex,met);
       if(n==NULL) break; // continue; 04.02.2002
       //*->*/ printf("n r%d x c%d", n->row, n->col); print_mat(n); 
         
/* GET KERNEL OF N **************************** */ 
       vkernel=kernel(n); 
    
/* GET SUBSETS ******************************** */
       wrong_subset=(int**)calloc(1, sizeof(int*)); addressed(wrong_subset, "wrong_subset ", 1);
       vsub=subset(vkernel,rev,wrong_subset);
       freemat(vkernel);
       redrev=subrev(vsub,rev);  // subset reversibility
       for( i=0; i<vsub->row; i++ )
       { 
         if( *(*wrong_subset+i) )
         { 
           // printf("!!! Subset %d with contradictory irreversibility constraints.\r", i+1 );
           // printf("    Enzymes of that subset are cancelled for the further calculations.\n");
           // printf("\nplease press ENTER"); getch(); printf("\r                  \r");
           // fprintf(fout, "\n!!! Following subset %d with contradictory irreversibility constraints.\n", i+1 );
           // fprintf(fout, "    Enzymes of that subset are cancelled for further calculations.\n");
           fprintf(fout, "iss%d", i+1); 
           for (ii=0;ii<vsub->col;ii++) *(*(vsub->head+i)+ii)=0;
         }
       }
       free(*wrong_subset); free(wrong_subset); // fflush(fout);

/* REDUCTION OF THE SYSTEM ******************** */
       nred=transp(vsub); 
       help=mult(n,nred); freemat (nred); // branch=(struct vector*)1; 
       nred=simplify(help); 
       freemat (help);
       if (nred->row==0) {printf ("System reduced to zero (simple system)\nEach subset forms an elementary mode\n");fprintf (fout, "System reduced to zero (simple system)\nEach subset forms an elementary mode\n");}//getch();return 0;

/* CONVEX BASIS ******************************* */
       // if(ulii==11) {print_mat(nred); vectoroutput(redrev); }
       vbasis=basis(nred,redrev);
       if(!vbasis->row) 
         { foutput(fout, fcomb, unreduced1, VarVect1, metlist, nx1, ulii, no_em, unreduced, -99, ei_um); freemat(vbasis); goto FREE1;}
       unreduced=mult(vbasis,vsub);
       freemat (vbasis);     

/* CONSERVATION RELATIONS ********************* */

/* ELEMENTARY MODES *************************** */
       //*->*/    printf("nred r%d x c%d", nred->row, nred->col); print_mat(nred);
       //*->*/    printf("redrev: r%d\n", redrev->row);   vectoroutput(redrev);
       vmode=modes(nred,redrev);    //*->*/    printf("vmode r%d x c%d", vmode->row, vmode->col); print_mat(vmode); 
       //*->*/ fprintf(fout,"\nELEMENTARY MODES\n"); // HMS######### Removed by HMS  
       //*->*/ fmatoutput (vmode,fout);fflush(fout);
       unreduced1=mult(vmode,vsub);
       mean_path_length(unreduced1);
       if(!vmode->row) 
          { *no_em=-99; foutput(fout, fcomb, unreduced1, VarVect1, metlist, nx1, ulii, no_em, unreduced, -99, ei_um); goto FREE; }
       //*->*/    printf("vsub: r%d x c%d", vsub->row, vsub->col); print_mat(vsub);
       //*->*/    printf("\nunreduced: r%d x c%d", unreduced->row, unreduced->col); print_mat(unreduced1);
       count_enz = count_enzymes( unreduced1 );
       //*->*/    printf("unred1 r%d x c%d", unreduced1->row, unreduced1->col); print_mat(unreduced1);
       foutput(fout, fcomb, unreduced1, VarVect1, metlist, nx1, ulii, no_em, unreduced, count_enz, ei_um);
       control_modi(unreduced1, fout, enzlist);   // FM 04.02.2002 wieder eröffnet und durch enzlist ergänzt
	   // fmatoutput (unreduced1, fout);
       // additional_em(fout, unreduced, unreduced1);
       fprintf(fout, "\n");
       freemat(unreduced1);
FREE:;       
       freemat(unreduced); freemat(vmode);
FREE1:;
/* FREE *************************************** */
       freemat(nred);       freevector(redrev);        freemat(vsub);
       freemat(n);  
       // fflush (fout); fflush(fcomb);
     } //*VarVect[0]

     // add to res0 the binary 1
     for(i=ei.row-1; i>-1; i--)
     { 
      if     ( res0[i]&& uebertrag[i+1]) { res1[i]=0; uebertrag[i]=1; }
      else if(!res0[i]&&!uebertrag[i+1]) { res1[i]=0; uebertrag[i]=0; }
      else                               { res1[i]=1; uebertrag[i]=0; }
     }
     for(i=0; i<ei.row; i++) 
      { res0[i]=res1[i]; printf("%d", (int)res0[i]); }
     printf("\t");
     // in vector res0 stand variables to be combined
     fflush(fout);
     
 }while(!uebertrag[0]); // new loop all combinations
     

/* FREE *************************************** */
    free(res0); free(res1); free(uebertrag); // 12.09.2001
    fclose(fout); fclose(fcomb);
    freemat(nex);
    // free concatenation lists
    free_met_list( metlist ); free_met_list(enzlist);// FM
    freevector(rev);freevector(met);
    if( met_counter )
    {
      for(i=0; i<met_counter; i++)free(*(metabolites+i));
      free(metabolites); met_counter=0; free(mets_cumul);
    }
    free(VarVect); free(VarVect1);  free(InitVect);
    free(no_em); free(um.head); free(ei.head); free(sae.head);
#ifndef sun
    time(&finish);
#if (defined DOS || defined _DOS || defined WIN32 || defined _WIN32)
    _strtime(t2); ftime( &tstruct2 );
    printf("\nStarting time was   :\t%s : %3u\n", t1, tstruct1.millitm );
    if( tstruct1.millitm > tstruct2.millitm )
    {
      printf( "The current time is :\t%s : %3u\ndiff of millisec    :\t           %3d", t2, tstruct2.millitm, (int)(1000-tstruct1.millitm+tstruct2.millitm) );
      printf( "\nProgram took %6.0f seconds and %3u millisec. ", difftime( finish, start )-1.0, (int)(1000-tstruct1.millitm+tstruct2.millitm) );
    }
    else
    {
      printf( "The current time is :\t%s : %3u\ndiff of millisec    :\t           %3d", t2, tstruct2.millitm, (int)(tstruct2.millitm-tstruct1.millitm) );
      printf( "\nProgram took %6.0f seconds and %3u millisec. ", difftime( finish, start ), (int)(tstruct2.millitm-tstruct1.millitm) );
    }
    printf("\nProgram correctly finished. -> please press ENTER key "); getch();
#else
    printf("\nProgram correctly finished.\n");
#endif
#endif // sun
    return 0;
} // main
