/* METATOOL 2.0 */


/* ************************************************************************************ */
/* METATOOL: TO ANALYZE METABOLIC NETWORKS ******************************************** */
/* WRITTEN BY THOMAS PFEIFFER ********************************************************* */
/* COMPILED WITH GCC ****************************************************************** */
/* 1/99 ******************************************************************************* */

/* INCLUDED FILES ********************************************************************* */
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>

// necessary under DOS:
#include <conio.h>
// dito:
#include <malloc.h>

void addressed(void *p, char *s )
{
 if(p==NULL)
 {
  printf("\nNot enough memory: %s\nProgramm prematurely terminated.\n", s );
  getchar(/*stdin*/); exit(1);
 }
}

/* MAKROS ***************************************************************************** */
#define BOOL int
// #define LIM 200000000L
#define TXT 100

/* STRUCT DECLARATIONS **************************************************************** */
struct enc {int rev; int key; char txt[TXT]; struct enc *next;};  
struct vector {int row; int *head;};
struct mat {int row; int col; int **head;};
int compstr (int m, char t1[100], char t2[100]);
int ggt (int u, int v);

/* 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 (/* *x */ struct enc)); addressed( x, "x not allocated");
      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;
      }
/* 1.2 function get enzlist ******************* */
  struct enc *getenzlist (FILE *s)
	  {
	   struct enc *enzlist, *eac, *ez;
  	   char tx[TXT];
	   enzlist=(struct enc*)calloc(1, sizeof(/* *enzlist Ferd */struct enc )); addressed( enzlist, "enzlist not allocated");
  	   ez=(struct enc*)calloc(1, sizeof(/* *ez Ferd */struct enc));            addressed( ez, "ez not allocated");
       ///* Ferd */ eac=(struct enc*)calloc(1, sizeof( struct enc));             addressed( eac, "eac in getenzlist");
       /* Ferd Sphaghetti-code der folgenden zwei Zeilen entflechten! */
       enzlist->next=ez; enzlist->key=0;
  	   ez->next=ez; ez->key=0; eac=enzlist;
  	   fscanf(s,"%s",/*&*/tx);
  	   if ((tx[0]!='-')&&(tx[1]!='E')) printf ("ERROR IN FILE!");
  	   while (!feof(s))
    	  {
    	  fscanf(s,"%s",/*&*/tx); if (tx[0]=='-') break;
    	  eac=ins(eac,0,(eac->key)+1,tx);
    	  }	
  	   while (!feof(s))
    	  {
    	  fscanf(s,"%s",/*&*/tx); if (tx[0]=='-') break;
    	  eac=ins(eac,1,(eac->key)+1,tx);
    	  }	
  	   return enzlist;
	  }
/* 1.3 function get metlist ******************* */
  struct enc *getmetlist (FILE *s)
	  {
	  struct enc *metlist, *eac, *mz;
  	  char tx[TXT];
	   metlist=(struct enc*)calloc(1, sizeof(/* *metlist Ferd */ struct enc )); addressed( metlist, "metlist not allocated");
  	   mz=(struct enc*)calloc(1, sizeof(/* *mz Ferd */ struct enc ));           addressed( mz, "mz not allocated");
       ///* Ferd */ eac=(struct enc*)calloc(1, sizeof( struct enc));             addressed( eac, "eac in getenzlist");  	  
      
       metlist->next=mz; metlist->key=0;
  	   mz->next=mz; mz->key=0; eac=metlist;
  	   while (!feof(s))
           {
    	   fscanf(s,"%s",/*&*/tx); if (tx[0]=='-') break;
           eac=ins(eac,0,(eac->key)+1,tx);
           }
	   while (!feof(s))
           {
    	   fscanf(s,"%s",/*&*/tx); if (tx[0]=='-') break;
    	   eac=ins(eac,1,(eac->key)+1,tx);
           }
	   return metlist;
	  }
/* ************************************************************************************ */
/* 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;
	  for (i=0; i<v->row; i++) printf ("%3d",*(v->head+i));
	  printf ("\n"); return 0;
	  }
  int matoutput (struct mat *m)
	  {
	  int i,ii;
	  for (i=0; i<(m->row); i++) 
		  {
		  for (ii=0; ii<(m->col); ii++) printf("%3d",*(*((m->head)+i)+ii));
		  printf("\n");
		  }
	  return 0;
	  }
  int fvectoroutput (struct vector *v, FILE *savefile)
      {
	  int i;
	  for (i=0; i<(v->row); i++) fprintf (savefile,"%3d",*((v->head)+i));
	  fprintf (savefile,"\n"); return 0;
	  }
  int fmatoutput (struct mat *m, FILE *savefile)
      {
	  int i,ii;
      fprintf (savefile," \n matrix dimension %d x %d\n",m->row, m->col);
	  for (i=0; i<(m->row); i++) 
		  {
		  for (ii=0; ii<(m->col); ii++) fprintf(savefile,"%3d",*(*((m->head)+i)+ii));
		  fprintf(savefile,"\n");
		  }
	  return 0;
	  }
  int fenzymeoutput (struct mat *m, struct enc *list, FILE *savefile)
    {
  	int i,r;
    int **mat;
	struct enc *acel;
    /* allociert von Ferd */
    //acel = (struct enc *) calloc( 1, sizeof( struct enc ));
    //     addressed( acel, "acel in fenzymoutput not allocated" );
    //mat  = (int**) calloc( 1, sizeof( int*));
    //     addressed( mat, "mat in fenzymoutput not allocated" );
    //*mat  = (int*) calloc( 1, sizeof( int));
    //     addressed( *mat, "*mat in fenzymoutput not allocated" );
    
    mat=m->head;
    fprintf (savefile,"\n enzymes\n");
	for (i=0;i<m->row;i++)
		{
		fprintf (savefile,"\n %d:\t",i+1);
        /* Ferd struct enc {int rev; int key; char txt[TXT]; struct enc *next;} */
        acel=list->next; r=0;
		while (acel!=acel->next)
    			{
			if (*(*(mat+i)+(acel->key-1))!=0) 
				{
				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 fprintf(savefile," (%d %s)",*(*(mat+i)+(acel->key-1)),acel->txt);
				if ((acel->rev)==1) r=1;
				}
    			acel=acel->next;
			}
		if (r==1) fprintf (savefile," irreversible");
		else fprintf (savefile," reversible");
		}
	fprintf (savefile,"\n");
    /* Ferd */ //free( acel ); free(*mat); free(mat);
	return i;
	}
int foveralloutput (struct mat *m, struct enc *list, FILE *savefile)
{
 int i,t;
 int **mat;
 struct enc *acel;
 //Ferd
 //mat=(int**)calloc(1, sizeof(int*)); addressed(mat, "mat in foveralloutput");
 mat=m->head;
 //Ferd
 //acel=(struct enc*)calloc(1, sizeof(struct enc)); addressed(acel, "acel in foveralloutput");
 fprintf(savefile,"\n overall reaction\n");
 for (i=0;i<m->row;i++)
	{
		fprintf (savefile,"\n %d:\t",i+1);
		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,"%d %s",-*(*(mat+i)+(acel->key-1)),acel->txt);
				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);
				else fprintf(savefile,"%d %s",*(*(mat+i)+(acel->key-1)),acel->txt);
				t=1;
			}
			acel=acel->next;
	 };
	}
	fprintf (savefile,"\n");
 return 0;
}
  struct vector *getrev (struct enc *list)
      {
      int i=0;
      struct enc *acel; struct vector *v;
        /* allociert von Ferd */
        //acel = (struct enc *) calloc( 1, sizeof( struct enc ));
        //   addressed( acel, "acel in getrev not allocated" );
        acel=list->next;
        while (acel!=acel->next) {acel=acel->next;i++;}
        v=(struct vector*)malloc(sizeof(/* *v Ferd */ struct vector)); v->row=i;   addressed( v, "v not allocated");
        v->head=(int*)malloc(v->row*sizeof(int));         addressed( v->head, "v->head not allocated");
        acel=list->next; i=0;
        while (acel!=acel->next) {*(v->head+(i++))=acel->rev; acel=acel->next;} 
        /* Ferd */ // free(acel); 
        return v;
      }

  struct mat *getnex (FILE *s, struct enc *metlist, struct enc *enzlist) 
	  {
   	  char tx[TXT];
	  struct enc *eac, *eac1, *acel;
      struct mat *m;
  	  int metfl, rs, con;
  	  int nmet, nreact, acrow, acol;
  	  int **sub;
    
	  /* Ferd */
      //acel = (struct enc *) calloc( 1, sizeof( struct enc ));
      //     addressed( acel, "acel in getnex not allocated" );
      //eac  = (struct enc *) calloc( 1, sizeof( struct enc ));
      //     addressed( eac, "eac in getnex not allocated" );
      //eac1 = (struct enc *) calloc( 1, sizeof( struct enc ));
      //     addressed( eac1, "eac1 in getnex not allocated" );
      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=(int**)calloc(nmet, sizeof(/* *sub Ferd */ int*));  addressed( sub, "sub not allocated");
      // if (sub==NULL) return 0;
      for (acrow=0;acrow<nmet;acrow++)
   	  {
   		  *(sub+acrow)=(int*)calloc(nreact, sizeof(int)); addressed( *(sub+acrow), "*(sub+acrow) not allocated");
          // Ferd if (*sub==NULL) return 0;
   		  // for (acol=0;acol<nreact;acol++) {*(*(sub+acrow)+acol)=0;}
   	  }
  	  metfl=0;
	  while (!feof(s))	
    		  {
    		  eac=enzlist; eac1=metlist;
    		  fscanf(s,"%s",/*&*/tx);
    		  if (tx[0]=='.') {metfl=0; if (fscanf(s,"%s",/*&*/tx)==-1) break;}
    		  else if (tx[0]==':') {metfl=1; if (!fscanf(s,"%d",&rs)) rs=1; fscanf (s,"%s",/*&*/tx);}
    		  else if (tx[0]=='=') {metfl=-1; if(!fscanf(s,"%d",&rs)) rs=1; fscanf(s,"%s",/*&*/tx);}   
    		  else if (tx[0]=='+') {if(!fscanf(s,"%d",&rs)) rs=1; fscanf(s,"%s",/*&*/tx);}
    		  if (!metfl)
      			  {
      			  con=1; acrow=0;
      			  while (eac!=eac->next) 
        			  {
        			  eac=eac->next;   
        			  if (compstr(100,tx,eac->txt)) {con=0;break;}
        			  }
      			  if (con) {printf ("ERROR: UNKNOWN ENZYME: %s\n",tx);} 
      			  else acol=(eac->key)-1;      
      			  }
    		  else
      			  {
      			  con=1;
      			  while (eac1!=eac1->next) 
        			  {
        			  eac1=eac1->next;
        			  if (compstr(100,tx,eac1->txt)) {con=0; break;}
       				  }
      			  if (con) {printf ("ERROR: UNKNOWN METABOLITE: %s\n",tx);}
      			  else acrow=(eac1->key)-1; 
      			  *(*(sub+acrow)+acol)=-rs*metfl;
      			  }   
    		  }
      m=(struct mat*)calloc(1, sizeof(/* *m Ferd*/struct mat));   addressed( m, "m not allocated");
      m->row=nmet; 
      m->col=nreact; 
      m->head=sub;
      /* Ferd */ // free(acel); 
                 // free(eac); // den nicht freigeben da doppelt gemoppelt
                 // free(eac1);  und diesen auch nicht
	  return m;
	  }

  
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(/* *m Ferd */ struct mat)); addressed( m, "m not allocated");
     m->row=0; m->col=nex->col;
     for (i=0; i<met->row; i++) if (!*(met->head+i)) m->row++; else;
     m->head=(int**)calloc( m->row, sizeof(/* *(m->head) */ int*)); addressed( m->head, "m->head not allocated");
     for (i=0;i<met->row;i++)
       if (!*(met->head+i))
       {
         /* allociert von Ferd */
         *(m->head+k)=(int*)calloc(m->col, sizeof(int));  addressed( *(m->head+i), "*(m->head+i) not allocated");
         for( j=0; j<m->col; j++ ) *(*(m->head+k)+j)=*(*(nex->head+i)+j); k++;
         //*(m->head+k++)=*(nex->head+i);
       }
     return m;
     }

/* 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;
      }
/* 2.3 mat operations ********************+* */
  struct mat *transp (struct mat *m)
      {
      struct mat *tm; int i,ii;
      tm=(struct mat*)calloc(1, sizeof(/* *tm */ struct mat));   addressed( tm, "tm not allocated");
      tm->row=m->col; tm->col=(m->row);
      tm->head=(int**)calloc(tm->row, sizeof(/* *(tm->head) */ int*)); addressed( tm->head, "tm->head not allocated");
      for (i=0; i<m->col; i++) 
          {
          *(tm->head+i)=(int*)calloc(tm->col, sizeof(int));  addressed( *(tm->head+i), "*(tm->head+i) not allocated");
          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(/* *mi Ferd */struct mat)); addressed( mi, "mi not allocated");
      mi->row=m->row; mi->col=m->col+m->row;
      mi->head=(int**)calloc(mi->row, sizeof(/* *(mi->head) Ferd */ int*)); addressed( mi->head, "mi->head not allocated");
      for (i=0; i<m->row; i++)
          {
          *(mi->head+i)=(int*)calloc(mi->col, sizeof(int)); addressed( *(mi->head+i), "*(mi->head+i) not allocated");
          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(/* *mc Ferd */ struct mat)); addressed( mc, "mc not allocated");
      mc->row=m->row; mc->col=m->col-cc;
      mc->head=(int**)calloc(mc->row, sizeof(/* *(mc->head) Ferd */ int*)); addressed( mc->head, "mc->head not allocated");
      if(cc>m->col) {printf("ERROR IN FUNCTION CUTCOL: CC>M->ROW!\n"); getchar(); exit(1); /* return NULL; */}
      for (i=0; i<mc->row; i++)
          {
          *(mc->head+i)=(int*)calloc(mc->col, sizeof(int)); addressed( *(mc->head+i), "*(mc->head+i) not allocated");
          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");
    // stutz
    vf->row=m->row; vf->head=(int*)calloc(vf->row, sizeof(int)); addressed( vf->head, "vf->head not allocated");
    mc=(struct mat*)calloc(1, sizeof(struct mat)); addressed( mc, "mc not allocated");
    mc->row=m->row; mc->col=m->col;
    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),abs(*(*(m->head+i)+ii)));
      if (*(vf->head+i)==0) mc->row--;
    }
    
    if( !mc->row ) // Microsoft C++ 6.0 produdes allocates any pointer if(mc->row==0 but no correct one)
    {
      printf("there is no simplification ...\n");
      mc->head=(int**)calloc(m->row, sizeof(int*)); addressed( mc->head, "mc->head not allocated 1");
      // return a copy of *m
      for (i=0; i<m->row; i++)
      {
       *(mc->head+i)=(int*)calloc(m->col, sizeof(int)); addressed( *(mc->head+i), "*(mc->head+i) not allocated");
       for (ii=0;ii<m->col;ii++) 
         *(*(mc->head+i)+ii)=*(*(m->head+i)+ii);
      }
    }
    else 
    {
      mc->head=(int**)calloc(mc->row, sizeof(/* *(mc->head) Ferd*/int*)); addressed( mc->head, "mc->head not allocated"); k=0;
      for (i=0; i<vf->row; i++) if (*(vf->head+i)!=0) 
      {
       *(mc->head+k)=(int*)calloc(mc->col, sizeof(int)); addressed( *(mc->head+k), "*(mc->head+k) not allocated");
       for (ii=0;ii<mc->col;ii++) 
         *(*(mc->head+k)+ii)=*(*(m->head+i)+ii)/(*(vf->head+i));
       k++;
      }
    }
    freevector(vf);
    return mc;
  }
      
  struct mat *mult (struct mat *m1, struct mat *m2)
      {
      struct mat *mm; int i,j,k,sum;
      if (m1->col!=m2->row) printf("error in mult: mat dimensions are inkompatible");
      mm=(struct mat*)calloc(1, sizeof(/* *mm */ struct mat));  addressed( mm, "mm not allocated");
      mm->row=m1->row; mm->col=m2->col;
      mm->head=(int**)calloc(mm->row, sizeof(/* *(mm->head) */ int*));  addressed( mm->head, "mm->head not allocated");
      for (i=0; i<mm->row; i++)
          {
          *(mm->head+i)=(int*)calloc(mm->col, sizeof(int));  addressed( *(mm->head+i), "*(mm->head+i) not allocated");
          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 ************** */
/* Kernel */
  struct mat *kernel (struct mat *m)   
      {
      struct mat *help, *k; int i,u,ii,uu,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(abs(*(*(help->head+u)+ii)),abs(*(*(help->head+i)+ii)));
              f2=(*(*(help->head+i)+ii))/ggt(abs(*(*(help->head+u)+ii)),abs(*(*(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); 
      return help;
      }
      
/* Subsets */
  struct mat *subset (struct mat *m, struct vector *v)
      {
      struct mat *help, *k; int i,ii,sign1,f1,u;
      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,abs(*(*(help->head+i)+ii)));
			if (sign1==0) sign1=*(*(help->head+i)+ii)/abs(*(*(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; 
			}
		}	
      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);
      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) for (ii=0;ii<help->col;ii++) *(*(help->head+i)+ii)=0;
        }	
      return (help);
      }
  struct vector *subrev (struct mat *m, struct vector *v)
      {
      int i,ii;
      struct vector *r;
      r=(struct vector*)calloc(1, sizeof(/* *v Ferd */ struct vector));  addressed( r, "r not allocated");
      // stutz
      r->row=m->row; r->head=(int*)calloc(r->row, sizeof(int));  addressed( r->head, "r->head not allocated");
      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;
      }
      
/* basis */
  struct mat *basis (struct mat *m, struct vector *v)   
      {
      struct mat *help, *k; 
      // struct vector *rev;
      int **h1, **h2;
      int *rev1, *rev2;
      int i,u,tu,ii,uu,test1;
      int r1, r2, c, counter;
      int f1,k1,k2,neg,pos,nrow;
       
      k=transp(m);help=addi(k);freemat(k);
      r1=(help->row); c=help->col; counter=m->row;
      rev1=(int*)calloc(v->row, sizeof(int));  addressed( rev1, "rev1 not allocated");
      for (i=0;i<v->row;i++) *(rev1+i)=*(v->head+i);
      //h1 = (int**)calloc(1, sizeof(int*)); addressed(h1,"h1 in basis not allocated");
      h1=help->head;
      for (ii=0; ii<counter; ii++)
          {
          f1=0;
          for (i=0; i<r1; i++) if ((*(*(h1+i)+ii))&&(!(*(rev1+i)))){f1=1;break;}
          if (f1) /* reversible row */
              {
              r2=r1-1;
              h2=(int**)calloc(r2,sizeof(/* *h2 Ferd */int*));   addressed( h2, "h2 not allocated");
              rev2=(int*)calloc(r2,sizeof(int));  addressed( rev2, "rev2 not allocated");
              for (u=0; u<r2; u++)
              {*(h2+u)=(int*)calloc(c,sizeof(int)); addressed( *(h2+u), "*(h2+u) not allocated"); }
              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++;
                }
              for (u=i+1; u<r1; u++) if ((*(*(h1+u)+ii))&&(!(*(rev1+u)))) /* rev rev combinations */
                {
                *(rev2+r2)=0; k1=*(*(h1+i)+ii); k2=*(*(h1+u)+ii);
                for (uu=0;uu<c;uu++) *(*(h2+r2)+uu)=k2**(*(h1+i)+uu)-k1**(*(h1+u)+uu);
                r2++;
                } 
              for (u=0; u<r1; u++) if (*(*(h1+u)+ii)&&(*(rev1+u))) /* rev irrev combinations */
                {
                *(rev2+r2)=1; k1=*(*(h1+i)+ii); k2=*(*(h1+u)+ii);
                if (k1*k2<0) for (uu=0;uu<c;uu++) *(*(h2+r2)+uu)=abs(k2)**(*(h1+i)+uu)+abs(k1)**(*(h1+u)+uu);
                if (k1*k2>0) for (uu=0;uu<c;uu++) *(*(h2+r2)+uu)=-abs(k2)**(*(h1+i)+uu)+abs(k1)**(*(h1+u)+uu);
                r2++;
                }  
              }
          else /* no reversible row */
              {
              pos=0; neg=0; nrow=2;
              for (i=0; i<r1; i++) {if((*(*(h1+i)+ii)>0)) pos++; if((*(*(h1+i)+ii)<0)) neg++;}
              r2=r1-neg-pos+neg*pos;
              h2=(int**)calloc(r2,sizeof(/* *h2 Ferd */int*));   addressed( h2, "h2x not allocated");
              rev2=(int*)calloc(r2,sizeof(int));  addressed( rev2, "rev2x not allocated");
              for (u=0; u<r2; u++) 
              {*(h2+u)=(int*)calloc(c,sizeof(int)); addressed( *(h2+u), "*(h2+u) not allocated");}
              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++;
                }
              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; k1=*(*(h1+i)+ii); k2=*(*(h1+u)+ii);
                  for (uu=0;uu<c;uu++) *(*(h2+r2)+uu)=abs(k2)**(*(h1+i)+uu)+abs(k1)**(*(h1+u)+uu);
                  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++;}             
                  }
                }
              }
          for(i=0;i<r1;i++) free (*(h1+i)); free (h1); free(rev1); 
          h1=h2; rev1=rev2; r1=r2;
          printf("result tab %d row %d\n",ii,r1);
          }   
      help->head=h2; help->row=r2; help->col=c;
      k=cutcol(help,counter); 
      freemat(help); 
      help=simplify(k);freemat(k);
      return help;      
      }

/* modes */
  struct mat *modes (struct mat *m, struct vector *v)   
      {
      struct mat *help, *k; /* help matrices */
      int **h1, **h2; /* pointer to current and nex tab */
      int *rev1, *rev2; /* corresponding revesibilities */
      int i,u,ii,uu,tu; /*counter */
      int nzero, nrev, nipos, nineg; /*number of rev, irrev and zero rows*/  
      int r1,r2,c, counter,k1,k2, test1;
      k=transp(m);help=addi(k);freemat(k); 
      h1 = (int**)calloc(1, sizeof(int*)); addressed(h1, "h1 in modes not allocated");
      h1=help->head;
      r1=(help->row); c=help->col; counter=m->row;
      rev1=(int*)calloc(v->row,sizeof(int));   addressed( rev1, "rev1xx not allocated");
      for (i=0;i<v->row;i++) *(rev1+i)=*(v->head+i);
      for (ii=0; ii<counter; ii++)
          {
          nzero=0; nrev=0; nipos=0; nineg=0;                /* counting combinable rows */
          for (i=0; i<r1; i++) if (*(*(h1+i)+ii)) 
            {
            if (!(*(rev1+i))) nrev++;
            else {if (*(*(h1+i)+ii)>0) nipos++; else nineg++;}
            }
          nzero=r1-nrev-nipos-nineg; r2=nzero+nrev*(nrev-1)+nrev*(nipos+nineg)+nipos*nineg;
          h2=(int**)calloc(r2,sizeof(/* *h2 Ferd */int*));   addressed( h2, "h2xx not allocated");
          rev2=(int*)calloc(r2,sizeof(int));  addressed( rev2, "rev2xx not allocated");
          for (i=0; i<r2; i++)
          { *(h2+i)=(int*)calloc(c,sizeof(int)); addressed( *(h2+i), "*(h2+i) not allocated"); }r2=0;
          for (i=0; i<r1; i++) if (!(*(*(h1+i)+ii))) /* taking zero rows to the nex tab */
          {*(rev2+r2)=*(rev1+i); for(uu=0;uu<c;uu++) *(*(h2+r2)+uu)=*(*(h1+i)+uu); r2++;}       
          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)))) 
              {
              *(rev2+r2)=0; k1=*(*(h1+i)+ii); k2=*(*(h1+u)+ii);
              for (uu=0;uu<c;uu++) *(*(h2+r2)+uu)=k2**(*(h1+i)+uu)-k1**(*(h1+u)+uu);
              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++;}
              }
            }
          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))) 
              {
              *(rev2+r2)=1; k1=(*(*(h1+i)+ii)); k2=(*(*(h1+u)+ii));
              if (k1*k2<0) for (uu=0;uu<c;uu++) *(*(h2+r2)+uu)=abs(k2)**(*(h1+i)+uu)+abs(k1)**(*(h1+u)+uu);
              if (k1*k2>0) for (uu=0;uu<c;uu++) *(*(h2+r2)+uu)=-abs(k2)**(*(h1+i)+uu)+abs(k1)**(*(h1+u)+uu);                           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++;}
              }
            }
          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))) 
              {
              *(rev2+r2)=1; k1=abs(*(*(h1+i)+ii)); k2=abs(*(*(h1+u)+ii));
              for (uu=0;uu<c;uu++) *(*(h2+r2)+uu)=k2**(*(h1+i)+uu)+k1**(*(h1+u)+uu);
              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++;}
              }
            }
            
          for(i=0;i<r1;i++) free (*(h1+i)); free (h1); free(rev1);
          h1=h2; rev1=rev2; r1=r2;
          /* h1=(int**)malloc(r2*sizeof(*h1)); rev1=(int*)malloc(r2*sizeof(int));
          for (i=0; i<r2; i++) *(h1+i)=(int*)malloc(c*sizeof(int));r1=0;
          
          for(i=r2-1;i>-1;i--)
            {
            for (uu=0;uu<c;uu++) *(*(h1+r1)+uu)=*(*(h2+i)+uu); *(rev1+r1)=*(rev2+i);
            test1=1;
            for (tu=0;tu<r1;tu++) 
              {
              test1=0; 
              for (uu=counter;uu<c;uu++)
                {
                if ((*(*(h1+r1)+uu)==0)&&(*(*(h1+tu)+uu)!=0)) {test1=1;break;}
                }
              if (test1==0) 
                {
                printf(" %d against %d\n",i ,tu);
                for(uu=counter;uu<c;uu++) printf("%3d",*(*(h1+r1)+uu));printf("\n");
                for(uu=counter;uu<c;uu++) printf("%3d",*(*(h1+tu)+uu));printf("\n");
                break;
                }			
              }
            if (test1==1) {r1++;}
            }*/
          printf("result modes tab %d row %d\n",ii,r1);
          } 
      help->head=h2; help->row=r2; help->col=c;
      k=cutcol(help,counter); freemat(help); help=simplify(k);freemat(k);
      return help;    
      }  
/* ************************************************************************************ */        
/* 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;
    	  }
  /* function biggest common divisor */
  int ggt (int u, int v)
    	  {
          int t;
          if (u*v==0) return (u+v);
          while (u>0) {  if (u<v) {  t=u; u=v; v=t;  }  u=u%v;  }
          return v;
          } 
/* ************************************************************************************ */        
/* MAIN *****************************************************************************+* */
/* ************************************************************************************ */
int main(int argn, char *f[/*Ferd TXT*/])
    {
    FILE *src,*fout;					/* 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, *tnex;	/* stoich. matrix, reduced, with ext. met */
    struct mat *vkernel, *vsub;			/* kernel, subsets */
    struct mat *crel;					/* conservation relations */					
    struct mat *vbasis, *vmode;			/* basis, modes */
    struct mat *unreduced, *overall;
    struct vector *rev, *redrev, *met; 
    
    src=fout=NULL;enzlist=metlist=NULL;
    help=nex=n=nred=tnex=vkernel=vsub=NULL;
    crel=vbasis=vmode=unreduced=overall=NULL;
    rev=redrev=met=NULL;
    // printf("%d, %d", n, nred );
    if( argn != 3 ) {printf("\nOne or both of the two input filenames are missing.\nProgram prematurely finished\n"); getchar(); exit(1); }
    else 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]); getchar(); exit(1); }
/* INPUT ********************************* */  
    src=fopen(f[1],"r"); if (src==NULL) {perror("file error!"); getchar(); return 0;}  
    enzlist=getenzlist(src); 
      rev=getrev(enzlist);
    metlist=getmetlist(src);
      met=getrev(metlist);
    nex=getnex(src,metlist,enzlist); 
      n=cutnex(nex,met);
    fclose (src);
    fout=fopen(f[2],"w"); if(!fout){perror("fout-error "); getchar(); exit(1);}
    fprintf (fout,"METATOOL OUTPUT Version 2.0 %s\n\n", f[0]);
    fprintf(fout, "INPUT FILE: %s\n\n", f[1]);
    fprintf (fout,"INTERNAL METABOLITES: %d\nREACTIONS: %d\n",n->row/*+1 von Ferd*/,n->col); 
    fprintf (fout,"\nSTOICHIOMETRIC MATRIX\n"); fmatoutput(n,fout);
    fprintf(fout, "following line indicates reversible (0) and irreversible reactions (1)\n" );
    fvectoroutput (rev,fout);


/* GET KERNEL OF N **************************** */ 
    vkernel=kernel(n); 
    fprintf(fout,"\nKERNEL\n"); 
     fmatoutput(vkernel,fout); 
     fenzymeoutput(vkernel,enzlist,fout);
    tnex=transp(nex); 
      overall=mult(vkernel,tnex); 
      foveralloutput (overall,metlist,fout);
    freemat (overall);
    
/* GET SUBSETS ******************************** */
    vsub=subset(vkernel,rev); redrev=subrev(vsub,rev); 
    fprintf(fout,"\nSUBSETS OF REACTIONS (%d rows)\n", vsub->row); fmatoutput (vsub,fout);
     fenzymeoutput(vsub,enzlist,fout);
    overall=mult(vsub,tnex); foveralloutput (overall,metlist,fout);
    freemat (overall);
    
/* REDUCTION OF THE SYSTEM ******************** */
    nred=transp(vsub); help=mult(n,nred); freemat (nred);
    nred=simplify(help); freemat (help);
    if (nred->row==0) {fprintf (fout, "System reduced to zero (simple system)\nEach subset forms an elementary mode\n");
    return 0;}
    fprintf(fout,"\nREDUCED SYSTEM with %d branch point metabolites in %d reactions (columns)\n", nred->row, nred->col); fflush(fout);
    fmatoutput (nred,fout);             fflush(fout);
    freemat(vkernel);
    fprintf(fout, "following line indicates reversible (0) and irreversible reactions (1)\n" );
    fvectoroutput (redrev,fout);        fflush(fout);
    
/* CONVEX BASIS ******************************* */
    vbasis=basis(nred,redrev); 
    fprintf(fout,"\nCONVEX BASIS\n");  fflush(fout);
    fmatoutput (vbasis,fout);          fflush(fout);
    unreduced=mult(vbasis,vsub); overall=mult(unreduced,tnex);
    fenzymeoutput(unreduced,enzlist,fout); foveralloutput (overall,metlist,fout);
    freemat (vbasis); freemat(unreduced); freemat(overall);

/* CONSERVATION RELATIONS ********************* */
    help=transp(n); 
    crel=kernel(help);
    fprintf(fout,"\nCONSERVATION RELATIONS\n");  fmatoutput (crel,fout); 
    freemat (crel);
  
/* ELEMENTARY MODES *************************** */
    vmode=modes(nred,redrev); 
    fprintf(fout,"\nELEMENTARY MODES\n"); fmatoutput (vmode,fout); 
    unreduced=mult(vmode,vsub); overall=mult(unreduced,tnex); 
    fenzymeoutput(unreduced,enzlist,fout); foveralloutput (overall,metlist,fout);
    freemat (vmode); freemat(unreduced); freemat(overall);

/* FREE *************************************** */
    freevector(rev);freevector(redrev);freevector(met); 
    freemat(nex);
    freemat(n);
    freemat(nred);
    freemat(vsub);
    printf("Program finished. -> any ENTER please "); getchar();
    return 0;
    }
  
