#include <stdio.h>
#define TITLE "\n*lrs:Reverse Search Vertex Enumeration:"
#define VERSION "Version 3.2a,May 1,1998"
#define AUTHOR "\n*Copyright (C) 1995,1997, David Avis   avis@cs.mcgill.ca "
/* This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*Ver 3.2a  fix output bug, hull computation                    */
/*Ver 3.1g  voronoi vertices                                    */
/*Ver 3.1f  ray est,name not required,printcobasis format       */
/*Ver 3.1e  Fixes a volume computation bug                      */
/*Ver 3.1d  Geometric rays printed with geometric option        */
/*Ver 3.1c  Do not print origin as facet, H- V-representation   */
/*Ver 3.1a  Revised lexmin ray computation                      */
/*Ver 3.1  Revised lexmin ray computation                       */
/*Ver 3.0  Revised volume computation                           */
/*Ver 2.5p Cache and Hull implemented                           */
/*Ver 2.5n Read in facet list                                   */
/*Ver 2.5m Output inequality #s                                 */
/*Ver 2.5l Incorportates maximize and minimize LP operations    */
/*Ver 2.5k Incorportates build function                         */
/*Ver 2.5j Dynamically allocates maximum number of digits by    */
/*       including the line  digits nnn  before the begin       */
/*       and handles interrupts by printing cobasis             */
/*Ver 2.5i volume computation                                   */
/*Ver 2.5h revised output format                                */
/*Ver 2.5g print only parent rays                               */
/*Ver 2.5f print rays as reduced integers                       */
/*Ver 2.5e handles extreme rays                                 */
/*Ver 2.5d fixes bug in ratios, allows rational inputs          */
/*Ver 2.5a all rational arithmetic gone, reverse redone etc.    */
/*Ver 2.5: lexographic pivot selection rule                     */
/* 64bit:      compile: cc -DB64 -O                             */
/*Ver 2.4e: Reads arbitrary length integers                     */
/*Ver 2.4d: Uses Bremner's dynamic allocation of memory         */
/*Ver 2.4: Check to see if perturbation removes all degeneracy  */
/*Ver 2.3: Fix of bug for degenerate starting vertex            */
/*Ver 2.1: Uses Edmonds Qpivot scheme, may contain bugs!        */
/*Ver 2.0: combines estimator - automatic when maxdepth reached */
/*         command line argument overides seed for estimator    */
/*Ver 1.1: dynamic memory allocation */
/*Ver 1.2: bug in dratios fixed      */
                          /* these numbers are user specified    */



/**********MACHINE DEPENDENT CONSTANTS***********/
/* MAXD is 2^(k-1)-1 where k=16,32,64 word size */
/* MAXD must be at least 2*BASE^2               */
/* If BASE is 10^k, use "%k.ku" for FORMAT      */
/* INTSIZE is number of bytes for integer       */
/* 16 bit machines                              */
/* remove L from constants, change %ld to %d    */
/*#define MAXD 32767                            */
/*#define BASE 100                              */
/*#define FORMAT "%2.2u"                        */
/*#define INTSIZE 4                             */
/*#define BIT "16"                              */
/* 32/64 bit machines                           */
/* add L to constants, change %d to %ld  */
#ifndef B64
/*32 bit machines */
#define FORMAT "%4.4u"                    
#define MAXD 2147483647L                      
#define BASE 10000L                       
#define BASE_DIG 4   
#define INTSIZE 8L                        
#define BIT "32"
#else
/* 64 bit machines */                      
#define MAXD 9223372036854775807L     
#define BASE 1000000000L             
#define FORMAT "%9.9u"       
#define BASE_DIG 9
#define INTSIZE 16L 
#define BIT "64"
#endif

#define MAXINPUT 1000  /*max length of any input rational*/    
/************************************************/
/******************************************************************************/
/*  Takes input in standard form .ine file, Ax<=b     A : m x d matrix        */
/*              -last d rows of A must define a vertex                        */
/******************************************************************************/
/*P.ine                -required:name of the file, P arbitrary  .ine required */
/*optional comments    - free format                                          */
/*digits size          -maximimum size decimal digits                         */
/*begin                - required                                             */
/*m  n  integer        -required:m is the number of rows of A, n=d+1          */
/*b_1  -A_1.           -inequal 1                                             */
/*   ...                                                                      */
/*b_m  -A_m.           -inequal m                                             */
/*end                  -required       (following lines all optional)         */
/*allbases             -print all bases                                       */
/*cache size           -number of dictionaries to hold, min=1, default=10     */
/*estimates runs       -when maxdepth reached, due runs probes to get estimate*/
/*debug start end      -debug mode from basis start..end, both zero all bases */
/*geometric            -print out incident vertex after each ray              */
/*hull                 -do convex hull computation                            */
/*H-representation     -do vertex enumeration computation                     */
/*maxdepth depth       -do not search below indicated depth                   */
/*mindepth depth       -do not backtrack above indicated depth                */
/*maximize c0 c1 .. cd -LP maximization with given objective function         */
/*minimize c0 c1 .. cd -LP minimization with given objective function         */
/*mindepth depth       -do not backtrack above indicated depth                */
/*nonnegative          -last d constraints are identity, b nonnegative        */
/*printcobasis freq    -print facet indices   when count[2] mod freq  = 0     */
/*restart vertex# basis# depth   facet indices   -restart from known vertex   */
/*seed integer         -integer is seed for estimator,overidden by commandline*/
/*startingcobasis f1 f2 .. fm -list of m input facets for starting vertex     */
/*volume               -do volume computation if true                         */
/*voronoi              -compute voronoi vertices                              */
/*V-representation     -do convex hull computation                            */
/******************************************************************************/
/*                   Indexing after initialization                            */
/*               Basis                           Cobasis                      */
/*   -----------------------------    -----------------------------           */
/*  |  i  |0|1| .... |d|d+1|...|m|   | j  | 0 | 1 | ... |d-1|  d  |           */
/*  |-----|+|+|++++++|+|---|---|-|   |----|---|---|-----|---|+++++|           */
/*  |B[i] |0|1| .... |d|d+1|...|m|   |C[j]|m+1|m+2| ... |m+d|m+d+1|           */
/*   -----------------------------    -----------------------------           */
/*            Location (row for Basic, column for Cobasic variable)           */
/*  -------------------------------------------------------------------       */
/* |   i   |0|  1  |  2  | ...|d|d+1|d+2|...| m |m+1|m+2|...|m+d|m+d+1|       */
/* |-------|+|+++++|+++++|++++|+|---|---|---|---|---|---|---|---|+++++|       */
/* |LOC[i] |0|m-d+1|m-d+2| ...|m| 1 | 2 |...|m-d| 0 | 1 |...|d-1|  d  |       */
/* -----------******************-----------------***************-------       */
/*  + = remains invariant   * = indices may be permuted   # = degenerate opt  */
/******************************************************************************/




#define POS 1L
#define NEG -1L
#ifndef TRUE
#define TRUE 1L
#endif
#ifndef FALSE
#define FALSE 0L
#endif
#define ONE 1L
#define TWO 2L
#define ZERO 0L

/********* MACROS ***********/
#define positive(a)     (((a)[0] < 2 || ((a)[0]==2 && (a)[1]==0))?FALSE:TRUE)
#define negative(a)     (((a)[0] > -2 || ((a)[0]==-2 && (a)[1]==0))?FALSE:TRUE)
#define zero(a)         ((((a)[0]==2 || (a)[0]==-2) && (a)[1]==0)?TRUE:FALSE)
#define one(a)          (((a)[0]==2 && (a)[1]==1)?TRUE:FALSE)
#define length(a)       (((a)[0] > 0) ? (a)[0] : -(a)[0])
#define sign(a)         (((a)[0] < 0) ? NEG : POS)
#define storesign(a,sa) a[0]=((a)[0] > 0) ? (sa)*((a)[0]) : -(sa)*((a)[0])
#define changesign(a)   a[0]= -(a)[0]
#define storelength(a,la) a[0]=((a)[0] > 0) ? (la) : -(la)

/***********************************************************************
  Start Bremner hackery 
***********************************************************************/

/*
   this is in decimal digits, you pay in memory if you increase this,
   unless you override by a line with 
   digits n
   before the begin line of your file.
*/
#define DEFAULT_DIGITS 100L

/* 
   this is number of longwords. Increasing this won't cost you that much
   since only variables other than the A matrix are allocated this size.
   Changing affects running time in small but not very predictable ways.
*/

#define MAX_DIGITS 255L 

/* 
 *  convert between decimal and machine (longword digits). Notice lovely
 *  implementation of ceiling function :-)
 */

#define DEC2DIG(d) ( (d) % BASE_DIG ? (d)/BASE_DIG+1 : (d)/BASE_DIG)
#define DIG2DEC(d) ((d)*BASE_DIG)

typedef long mp[MAX_DIGITS+1]; /* type mp holds one multi-precision integer*/

 /* This is the max permitted, the A array is allocated to this size */
long digits;

/* this is the biggest acheived so far. */
long record_digits;  

#ifndef OMIT_SIGNALS
#include <signal.h>
#include <unistd.h>
#define errcheck(s,e) if ((long)(e)==-1L){  perror(s);exit(1);}
#endif

#ifndef OMIT_TIMES
void ptimes();
#endif 
void alloc_memory();
int check_cache();

void pushQ();
void digits_overflow();
void cache_dict();


typedef long * mp_t;

typedef long **mp_1d_array_t;

typedef long ***mp_2d_array_t;

mp_2d_array_t A; /* Current coefficient matrix */
mp_2d_array_t D; /* destination coeffiencient matrix */

typedef struct dict_rec_struct 
{
  mp_2d_array_t A;
  long *Araw;
  long i,j;
  long *det;
  struct dict_rec_struct *prev,*next;
} dict_rec;

dict_rec *Qhead,*Qtail;

unsigned long dict_count,dict_limit,cache_tries,cache_misses;

dict_rec *new_dict_rec();


/*
   If given a signal 
	USR1		print current cobasis and continue
	TERM		print current cobasis and terminate
	INT (ctrl-C) ditto
	HUP			ditto
*/


/* How often to print out current cobasis */
#define CHECKPOINT_SECONDS 60000000L /* disabled in timecheck */

long saved_count[3];
long *saved_C;
mp_1d_array_t oD; /* Denom for objective function */
mp_1d_array_t Lcm; /* Lcm for each row of input denominators */
mp_1d_array_t Gcd; /* Gcd of each row of numerators*/

mp saved_det;
long saved_flag;  /* There is something in the saved cobasis */

void *calloc(),*xcalloc();
#define CALLOC(n,s) xcalloc(n,s,__LINE__,__FILE__)

/***********************************************************************
 End Bremner hackery
************************************************************************/
long *B,*C,*LOC,*minratio;
long *inequality;             /* holds indices of inequalities corr. to       */
                              /* and cobasic indices                          */
mp det, sumdet;               /* determinant for qpivoting and its sum        */
mp Nvolume,Dvolume;           /* volume numerator and denominator             */
long detsign=POS;             /* sign of determinant for qpivoting            */
long m=0;                     /* number of rows in matrix A                   */
long d=0;                     /* number of cols in matrix A                   */

long allbases=FALSE;          /* TRUE if all bases should be printed          */
long geometric=FALSE;         /* TRUE if incident vertex prints after each ray*/
long printcobasis=FALSE;      /* TRUE if all cobasis should be printed        */
long nonnegative=FALSE;       /* TRUE if last d constraints are nonnegativity */
long maxdepth=MAXD;           /* max depth to search to in treee              */
long mindepth= -MAXD;         /* do not backtrack above mindepth              */
long frequency=1;             /* frequency to print cobasis indices           */
long hull=FALSE;              /* do convex hull computation if TRUE           */
long noduprays=FALSE;         /* guaranteed no duplicate rays:polytope hull or cone*/
long getvolume=FALSE;         /* do volume calculation                        */
long voronoi=FALSE;           /* compute voronoi vertices by transformation   */

                             /************************************************/
/******* values for GCD *******/
long MAXSPLEN;			/* Maximum digits for a number that will fit */
				/* into a single long integer. */
unsigned long MAXSPVAL;		/* Max value for the last digit to guarantee */
				/* fitting into a single long integer. */

long debug=FALSE;
/* variables for estimation of tree size */
long runs=0,seed=1234;
long *isave,*jsave;    /* arrays for estimator, malloc'ed at start     */
long totalnodes=0L;    /* count total number of tree nodes evaluated   */
long count[3];         /* count[0]=rays [1]=vertices [2]=base          */
long depth=0;          /* depth of basis/vertex in reverse search tree */
long newrow=0;         /* index of latest entry into the basis         */
long *temparray;       /* for sorting indices, dimensioned to d        */
long deepest=0;        /* max depth ever reached in search             */

/**************************************************************************************************************/
void atoaa(char in[], char num[], char den[]); /* convert rational string in to num/den strings               */
void atomp(char s[], mp a);                    /*convert string to mp integer                                 */
long atos(char s[]);                           /* convert s to integer                                        */
long comprod(mp Na,mp Nb,mp Nc,mp Nd);         /* +1 if Na*Nb > Nc*Nd, -1 if Na*Nb > Nc*Nd else 0             */
void copy(mp a, mp b);                         /* assigns a=b                                                 */
void divint(mp a, mp b, mp c );                /* c=a/b, a contains remainder on return                       */
void estimate(double *best, double *vest, double *rest); /* get estimate of tree size from current node        */
void gcd(mp u, mp v);                          /* returns u=gcd(u,v) destroying v                             */
long greater(mp a, mp b);                      /* tests if a > b and returns (TRUE=POS)                       */
long ismin(long r,long s);                     /* test if A[r][s] is a min ratio for col s                    */
void itomp(long in, mp a);                     /* convert integer i to multiple precision with base BASE      */
long lexmin(long col);                         /* do a test on col of A to see if current basis is lexmin     */
void linint(mp a,long ka,mp b,long kb);        /* compute a*ka+b*kb --> a                                     */
void lcm(mp a, mp b);                          /* a = least common multiple of a, b; b is preserved           */
void mulint(mp a,mp b,mp c);                   /* multiply two integers a*b --> c                             */
long myrandom(long num, long nrange);          /* return a random number in range 0..nrange-1                 */
void normalize(mp a);                          /* normalize mp after computation                              */
void notimpl(char s[]);                        /* bail out - help!                                            */
void pimat(long r,long s,mp Nt,char name[]);   /* print the row r col s of matrix A                           */
void pivot(long bas, long cob);                /* Qpivot routine for array A                                  */ 
void pmp(char name[],mp a);                    /* print the long precision integer a                          */
void prat(char name[],mp Nt,mp Dt);            /* print the long precision rational Nt/Dt                     */
void printsol(long col,long comment);          /* Print out current solution, comment=TRUE for geometric case */
void prtotals(double best,double vest,double rest, char fname[] );   /*print final totals                     */
long ratio(long col);                          /* find lex min. ratio                                         */
void readA(long *strace, long *etrace, char fname []); /* read input and set up problem and dictionary        */
void readfacets(long facet[]);                 /* read and check facet list                                   */
void readmp(mp a) ;                            /* read an integer and convert to mp with base BASE            */
long readrat(mp Na, mp Da);                    /* read a rational or integer and convert to mp with base BASE */
void reduce(mp Na,mp Da);                      /* reduces Na Da by gcd(Na,Da)                                 */
void reorder(long a[], long range);            /* reorder array in increasing order with one misplaced element*/
long reverse(long *r, long s);                 /* TRUE if B[*r] C[s] is a reverse lexicographic pivot         */
long selectpivot(long *r, long *s);            /* select pivot indices using lexicographic rule               */
void stringcpy (char *s, char *t);             /* copy t to s pointer version                                 */
void update(long *i, long *j);                 /* update the B,C, LOC arrays after a pivot                    */
/**************************************************************************************************************/
main( int argc, char *argv[] )/* reverse search for vertex enumeration for test purposes */
{
/*long clock();*/
long strace= -1,etrace= -1;  /*turn on/off debug at vertex # s/etrace        */
long i=0,  j=0;
double best=0.0,vest=0.0,rest=0.0;          /* estimates for bases and vertices not generated*/
long tempi,tempj;                  /* indices for recovering pivot row/col          */

char fname[100];            /* input file name                              */

#ifndef OMIT_SIGNALS
setup_signals();
#endif

/*clock();*/
MAXSPVAL = MAXD;
for (MAXSPLEN = 2;MAXSPVAL >= BASE; MAXSPLEN++)
MAXSPVAL /= BASE;
count[0]=0; count[1]=0; count[2]=0;
itomp(ZERO,Nvolume); itomp(ONE,Dvolume);
itomp(ZERO,sumdet);
readA(&strace,&etrace,fname);
if(argc > 1 ) 
    {  seed=atoi(argv[1]);
       printf("\n*Control line seed=%d overides any seed in input file",seed);
    }

if (hull)
     printf("\nH-representation\nbegin\n***** %d rational",d);
   else if (voronoi)
     {
     printf("\n*Voronoi Diagram: Voronoi vertices and rays are output");
     printf("\nV-representation\nbegin\n***** %d rational",d);
     }
 	else
     		printf("\nV-representation\nbegin\n***** %d rational",d+1);
printsol(d,FALSE);
if(maxdepth==0 && runs > 0 )    /* estimate only */ 
   estimate(&best,&vest,&rest);
 else               /* Main Loop of Reverse Search */
   while ( (j < d ) || ( B[m] != m ) )
   {
    if (depth < mindepth ) break;
    if (strace == count[2] ) debug = TRUE;
    if (etrace == count[2] ) debug = FALSE;

    while ( (j < d  ) && ! reverse(&i,j) ) j++;
    if ( j < d )         /*reverse pivot found */
       {
        depth=depth+1;
        if(depth > deepest) deepest=depth;

		cache_dict(i,j); 

        pivot(i,j);
        update(&i,&j);        /*Update B,C,i,j */
        printsol(d,FALSE);
        totalnodes++;
        j=0;
       }
     if( depth >= maxdepth && runs > 0 )  /*get an estimate of remaining tree*/
           estimate(&best,&vest,&rest);
    if ( (j==d) || ( depth >= maxdepth ) )
			    /* go back to prev. dictionary, restore i,j */
    if (B[m ] != m )
       {
        depth=depth-1;
		if (!check_cache(&i,&j))
		  {
			selectpivot(&i,&j);
			pivot(i,j);
		  }
		update(&i,&j);        /*Update B,C,i,j */
		
	selectpivot(&tempi,&tempj);
	newrow=LOC[B[tempi]];  /*restore "new" pivot row */
	/*printf("\n0  +++");*/
        if(debug) {printf("\n Backtrack Pivot: indices i=%d j=%d newrow=%d ",i,j,newrow);
                   printA();
                   fflush(stdout);
                  }
        j++;       /* go to next column */
       }
   }              /* end of main while loop for reverse search */
printf("\nend");
prtotals(best,vest,rest,fname);       /* print final totals */
}        /* end of reverse search driver  */

/********************************************************/
/*  Estimation function                                 */
/********************************************************/
void estimate(double *best, double *vest, double *rest)         /*get estimate of tree size from current node    */
                                             /*current node is not counted. best is cumulative*/
                                             /*number of bases, vest of vertices, estimated   */
{
long estdepth=0;             /* depth of basis/vertex in subtree for estimate*/
long i=0,  j=0,k,nchild,runcount,col;
double prod=0.0,vave=0.0,bave=0.0,rave=0.0;
double nvertices,nbases,nrays;
long rays=0;

/* Main Loop of Estimator */

 for ( runcount=1;runcount<=runs;runcount++)
 { /* runcount counts number of random probes */
  j=0;
  nchild=1; prod=1; nvertices=0.0; nbases=0.0; nrays=0.0;
  while ( nchild != 0 ) /* while not finished yet*/
  {
    /* count number of rays at this node */
    rays=0;
    for (col=0;col<d;col++)
      if(negative(A[0][col]) &&(ratio(col)==0) && lexmin(col)) rays++; 
    nchild=0;
    while  (j < d  )
      {
      if ( reverse(&i,j) )
        {
         isave[nchild]=i;
         jsave[nchild]=j;
         nchild++;
        }
      j++;
      }
    nrays=nrays+prod*rays;               /* update ray info */ 

    if(estdepth==0 && nchild==0) 
       { *rest=*rest+rays;      /* may be some rays here */
         return;                        /*subtree is a leaf*/
       }

    prod=prod*nchild;
    nbases=nbases+prod;
    if(debug)
        { printf("   degree= %d ",nchild);
          printf("\nPossible reverse pivots: i,j=");
          for ( k=0;k<nchild;k++) printf("%d,%d ",isave[k],jsave[k]);
        }

    if ( nchild > 0 )         /*reverse pivot found choose random child */
       {
        k=myrandom(seed,nchild);
        seed=myrandom(seed,977L);
        i=isave[k]; j=jsave[k];
        if(debug) printf("  selected pivot k=%d seed=%d ",k,seed);
        estdepth++;
        totalnodes++;   /* calculate total number of nodes evaluated */
        pivot(i,j);
        update(&i,&j);        /*Update B,C,i,j */
        if(lexmin(d))    /* see if lexmin basis for vertex */
             nvertices=nvertices+prod;
        j=0;
       }
   }
    vave=vave+nvertices;
    bave=bave+nbases;
    rave=rave+nrays;

/*  backtrack to root and do it again */

    while ( estdepth > 0 )
      {
        estdepth=estdepth-1;
        selectpivot(&i,&j);
        pivot(i,j);
        update(&i,&j);        /*Update B,C,i,j */
        /*printf("\n0  +++");*/
        if(debug) {printf("\n Backtrack Pivot: indices i,j %d %d ",i,j);
                   printA();
                   fflush(stdout);
                  }
	j++;
       }

 } /* end of for loop on runcount */
        *vest=vave/runs+ *vest;
        *best=bave/runs+ *best;
        *rest=rave/runs+ *rest;
        if(debug)
        fprintf(stderr,"\n*Estimated number of vertices: %g    rays: %g    bases: %g",vave/runs,rave/runs,bave/runs);
}        /* end of estimator  */


/*********************************************************/
/*              Reverse Pivot Code                       */
/*********************************************************/
long reverse(long *r, long s)  /* TRUE if B[*r] C[s] is a reverse lexicographic pivot*/
{
  long i,j,enter,row,col;

  enter=C[s];
  col=LOC[enter];
  if (debug) {printf("\n+reverse: col index %d C %d LOC %d ",s,enter,col);
              fflush(stdout);
	     }
  if (! negative(A[0][col]) )
	{ if (debug) printf(" Pos/Zero Cost Coeff");
	  return(FALSE);}

  *r=ratio(col);
  if(*r == 0 ) /* we have a ray, and decide whether to print it or not */
        { if (debug) printf(" Pivot col non-negative:  ray found");
/*             print ray only if different from parent(not used)             */
/*             if( lexmin(col) && ( ! zero( A[newrow][col]) || depth ==0 ) ) */

/*             print ray only if lex min or geometric option                 */
/*             and not in estimator mode (depth >= maxdepth)                 */
                 if (depth < maxdepth && (lexmin(col) || geometric )) 
                 {
                 printsol(col,FALSE);  
                 if (geometric)
                     printsol(d,TRUE);
                 }
          return(FALSE);
        }
  row=LOC[B[*r]];

  
/* check cost row after "pivot" for smaller leaving index    */
/* ie. j s.t.  A[0][j]*A[row][col] < A[0][col]*A[row][j]     */
/* note both A[row][col] and A[0][col] are negative          */

  for (i=0; i<d && C[i]< B[*r];i++)
    if (i != s)
      { j=LOC[C[i]];
        if( positive(A[0][j]) || negative(A[row][j])) /*or else sign test fails trivially*/
	  if ( ( ! negative (A[0][j]) && ! positive (A[row][j]) ) ||
                           comprod(A[0][j],A[row][col],A[0][col],A[row][j]) == -1 )
            {     /*+ve cost found*/
              if (debug)
                printf("\nPositive cost found: index %d C %d LOC %d",i,C[i],j);
              return(FALSE); 
            }
      }
  if (debug) {printf("\n+end of reverse : indices r %d s %d \n",*r,s);
              fflush(stdout);
             }
  return(TRUE);
}

/*********************************************************/
/*       End of Reverse Pivot Code                       */
/*********************************************************/
/*********************************************************/
/*       Code for pivoting: selectpivot & pivot          */
/******************************************************* */
long selectpivot(long *r, long *s) /* select pivot indices using lexicographic rule   */
                                   /* returns TRUE if pivot found else FALSE          */
     /* pivot variables are B[*r] C[*s] in locations LOC[B[*r]]    LOC[C[*s]]         */
{
 long j,col;
  
 *r=0; *s=d;
 j=0;

/*find positive cost coef*/
 while ( (j < d ) && ( ! positive(A[0][LOC [C[j]]])) ) j++; 

 if(j < d )                    /* pivot column found!*/
  {
   *s=j;
   col=LOC[C[j]];

  /*find min index ratio */
   *r=ratio(col);
   if(*r!=0) return (TRUE);       /* unbounded */
   }
return(FALSE);
     /******************************/
}    /* end of select pivot        */
     /******************************/

void pivot(long bas, long cob) /* Qpivot routine for array A              */ 
                     /* indices bas, cob are for Basis B and CoBasis C    */
                     /* corresponding to row LOC[B[bas]] and column       */
                     /* LOC [C[cob]]   respectively                       */
{
  long r, s;
  long lastrow=m;           /* last row to be pivoted on */
  long i,j;
  mp Ns,Nt,Ars;

  r=LOC[B[bas]];
  s=LOC[C[cob]];
/* Ars=A[r][s]    */
  if(debug){ printf("\n pivot  B[%d]=%d  C[%d]=%d ",bas,B[bas],cob,C[cob]);
             fflush(stdout);
           }
  copy(Ars,A[r][s]);
  storesign(det,sign(Ars));   /*adjust determinant to new sign*/

/* if nonnegative constraints, no need to pivot last d rows of A */
  if(nonnegative) lastrow=m-d;
  for (i=0;i<=lastrow;i++)
   if( i != r )
       for (j=0;j<=d;j++)
	 if ( j != s )
	  {
/*          A[i][j]=(A[i][j]*Ars-A[i][s]*A[r][j])/det; */
            mulint(A[i][j],Ars,Nt);
	    mulint(A[i][s],A[r][j],Ns);
	    linint(Nt,1,Ns,-1);
	    divint(Nt,det,A[i][j]);
          }
   if( sign(Ars)==POS)   
     {   for (j=0;j<=d;j++)  /* no need to change sign if Ars neg*/   
	                  /*    A[r][j]=-A[r][j];              */
	    if(! zero(A[r][j])) changesign(A[r][j]);
      }         /* watch out for above if when removing this } ! */
     else
         for (i=0;i<=lastrow;i++)	   
            if (! zero(A[i][s]) )changesign(A[i][s]);
   /*  A[r][s]=det;                  */
   copy(A[r][s],det);     /* restore old determinant */

   detsign=sign(Ars)*detsign;  /* sign of new determinant */
   if(debug) printf("new det sign %d ",detsign);

   copy(det,Ars);
   storesign(det,POS);          /* always keep positive determinant */
   if (debug) { printf(" depth=%d ",depth);
		pmp("det=",det);
              }

}                                 /* end of pivot routine */

long primalfeasible()
/* Do dual pivots to get primal feasibility */
/* Note that cost row is all zero, so no ratio test needed for Dual Bland's rule*/
{
  long  primalinfeasible=TRUE;
  long i,j;
  while (primalinfeasible)
    { primalinfeasible=FALSE;
      for (i=d+1;i<=m;i++)
      {
         if ( negative ( A[LOC[B[i]]][d] ))
             {
               primalinfeasible=TRUE;
               j=0;     /*find a positive entry for in row */
               while ( j < d && !positive( A[LOC[B[i]]][LOC[C[j]]]) )j++;
               if ( j >= d ) return(FALSE); /* no positive entry */
               pivot(i,j);
               update(&i,&j);
             }
      } /* end of for loop */
    } /* end of dual lp for feasibility */
    return(TRUE);
} /* end of primalfeasible */

void solvelp(long maximize, mp objlcm)
/* Solve primal feasible lp by least subscript and lex min basis method */
{
  long i,j;
  mp denom;

  while(selectpivot(&i,&j))
       {
	count[2]++;
        pivot(i,j);
        update(&i,&j);        /*Update B,C,i,j */
       }
  if (debug) printA();
  if(j < d && i== 0 )  /* selectpivot gives information on unbounded solution */
         {  printf("\nUnbounded solution");
            printf("\nRay is            (ignore zero in column one)");
            printsol(LOC[C[j]],FALSE);
         }
   else 
         { if (!maximize) changesign(A[0][d]);
           mulint(det,objlcm,denom);
           reduce(A[0][d],denom);
           prat("\n*Objective function has value ",A[0][d],denom);
         }

   printf("\n*Optimum vertex is (ignore one in column one)");
/* force vertex printing by printsol */
   allbases=TRUE;
   printsol(d,FALSE);
   printf("\n");
} /* end of solvelp  */

void getabasis(long givenstart,long order[])

/* Pivot Ax<=b to standard form */
/*Try to find a starting basis by pivoting in the variables x[1]..x[d] and by */
/*pivoting out the slacks with indices in order.                              */
{
  long dimension=0;
  long i,j,k;
    if (debug) { printf("\ngetabasis from inequalities given in order");
                 for (i=0;i<d;i++) printf(" %ld",order[i]);
               }
    for (j=0;j<d;j++)
	{ i=0;
	  while ( i <= m && B[i] != d+order[j] ) i++; /* find leaving basis index i */
          if (i > m && givenstart ) /* give warning that start is no good*/ 
                 printf("\n*Facet index %d invalid and is ignored",order[j]);
          if ( i <= m ) /* do a pivot */
            { k=0;
              while ( k < d && 
                      (zero(A[LOC[B[i]]][LOC[C[k]]])|| C[k] > d)) k++;
              {    if (k < d )
                        { pivot(i,k);
                          update(&i,&k);
                          dimension++;
                        }
                    else if ( givenstart ) /* give warning that start is no good*/
                         printf("\n*Facet index %d cannot enter cobasis and is ignored",order[j]);
               } /* end of while */
             }   /* end of if do a pivot */
          }      /* end of for   */
    
/* Check to see if we have a basis, if not get any basis */
        if ( C[0] <= d && givenstart )
           printf("\n*No vertex found - startingcobasis will be modified");
	while (C[0] <= d)
                 {
                      /* find a Cobasic variable that must enter basis */
                  i=m;  k=0;
		  while ( (i >=1 ) &&
                         (zero(A[LOC[B[i]]][LOC[C[k]]])|| B[i] <= d)) i--;
                  if (i >=1 )
                        { pivot(i,k);
                          update(&i,&k);
                          dimension++;
                        }
                    else
                        { printf("\n*Input Polytope does not have full dimension ");
                          if (hull) 
                            printf("\n*If input is a cone, change to H-representation, or add the origin 1 0 0 ... 0");
                          notimpl("");
                        }
                   }      /* end  while (C[0] <= d) */
/* Check feasability */
	if(givenstart)
         { i=d+1;
           while (i <=m && !negative ( A[LOC[B[i]]][d] )) i++;
           if( i <= m ) printf("\n*Infeasible startingcobasis - will be modified");
         }

}  /*  end of getabasis */

restartpivots(long facet[], long Cobasic[])
/* facet contains a list of the inequalities in the cobasis for the restart */
/* inequality contains the relabelled inequalities after initialization     */
{
 long i,j,k;

 /* set Cobasic flags */
         for(i=0;i<m+d+1;i++)  Cobasic[i]=0;
         for(i=0;i<d;i++)      /* find index corresponding to facet[i] */
             { j=0;
               while ( facet[i] != inequality[j] ) j++;
               Cobasic[j+d]=1;
             }
 /* Note that the order of doing the pivots is important, as */
 /* the B and C vectors are reordered after each pivot       */

         for (i=m ;i>=d+1;i--)  /*see if a basic variable should leave*/
              if( Cobasic[B[i]]) /* basic variable must leave  */
                 {
                      /* find a Cobasic variable that must enter basis */
                  k=d-1;
                  while ( (k >= 0 ) &&
                         (zero(A[LOC[B[i]]][LOC[C[k]]])|| Cobasic[C[k]])) k--;
                  if (k >= 0 )
                        { pivot(i,k);
                          update(&i,&k);
                        }
                  else
                          notimpl("Invalid Co-basis - does not have correct rank");
                  }      /* end of if(Cobasic..  */
         if (lexmin(d)) --count[1];      /* decrement vertex count if lexmin */
         --count[2];
/* check restarting from a primal feasible dictionary               */
   for (i=d+1;i<=m;i++)
         if ( negative ( A[LOC[B[i]]][d] )) 
                  notimpl("Trying to restart from infeasible dictionary");

}  /* end of restartpivots */

/*********************************************************/
/*           End of code for pivoting                    */
/******************************************************* */
/*           Code for ratio tests(Lexicographic)         */
/******************************************************* */

long ratio(long col)        /*find lex min. ratio */
                  /* find min index ratio -aig/ais, ais<0 */
		  /* if multiple, checks successive basis columns*/
{
 long i,j,k,comp,degencount,ratiocol,basicindex,bindex,cindex;
 long firstime;      /*For ratio test, true on first pass,else false*/
 mp Nmin,Dmin;

 degencount=0;
 for(j=d+1;j<=m;j++) 
    { minratio[j]=FALSE;
      /* search rows with negative coefficient in dictionary */
      if(negative(A[LOC[B[j]]][col]))
	  { minratio[j]=TRUE;
	     degencount++;
           }
     } /* end of for loop */      
 if(degencount==0) return(degencount); /* non-negative pivot column */
 ratiocol=d;  /* column being checked, initially rhs */
 bindex=d+1;  /* index of next basic variable to consider */
 cindex=0;    /* index of next cobasic variable to consider */
 basicindex= d; /* index of basis inverse for current ratio test, except d=rhs test*/
 while (degencount > 1 )   /*keep going until unique min ratio found */
   {
   if(debug) 
	    printf("\n basicindex=%d bindex=%d cindex=%d ",basicindex,bindex,cindex);
   if(basicindex > m  )   /*should never happen in lex min ratio!*/
		       {printf("ratio test for col %d",col);
			printA();
			notimpl("failed");
                       }
   if(B[bindex]==basicindex) /*in this case basis inverse is an identity column */
			     /*so we do not perform a ratio test                */
     {
       if (minratio[bindex])
	  { degencount--;
	    minratio[bindex]=FALSE;
          }
       bindex++;
     }
   else                    /* perform ratio test on rhs or column of basis inverse*/
    { firstime=TRUE;
                           /*get next ratio column and increment cindex*/ 
      if (basicindex != d) ratiocol=LOC[C[cindex++]];
      for (j=d+1;j<=m;j++)
      if(minratio[j])
       { i=LOC[B[j]];              /* i is the row location of the next basic variable*/
         comp=1;                   /* 1:  lhs>rhs;  0:lhs=rhs; -1: lhs<rhs */
         if (firstime)
		                   /*force new min ration on first time*/
		  firstime=FALSE;
	  else
              {
               if( positive(Nmin) || negative(A[i][ratiocol])) 
                  {if ( ! negative (Nmin) && ! positive (A[i][ratiocol])) comp= -1;
		    else comp = comprod( Nmin,A[i][col],A[i][ratiocol],Dmin);
                   }

               else  if( zero(Nmin) && zero(A[i][ratiocol])) comp=0;

               if (ratiocol==d) comp= -1*comp;     /* all signs reversed for rhs */
                }
         if (comp == 1)
		      {   /*new minimum ratio */
			 for(k=d+1;k<j;k++) minratio[k]=FALSE;
		         copy(Nmin,A[i][ratiocol]);
		         copy(Dmin,A[i][col]);
			 degencount=1;
		       }
	    else if (comp == 0) degencount++;  /* repeated minimum */
		  else minratio[j]=FALSE;      /* no longer minimum in this row */

         } /* end of if(minratio[j])  */
    } /* end of else statement */
   basicindex++;           /* increment column of basis inverse to check next */
   if(debug) {
	    printf(" ratiocol=%d degencount=%d ",ratiocol,degencount);
	    printf("  Min ratios: ");
            for(i=1;i<=m;i++) 
	       if(minratio[i]) printf(" %d ",B[i]);
           }
   } /*end of while loop*/
 j=d+1;
 while ( ! minratio[j] ) j++; /* find minratio to return */
 return(j);
}                          /* end of ratio */

/*********************************************************/
/*           End of code for ratio tests                 */
/******************************************************* */
/*********************************************************/
/*                 Miscellaneous                         */
/******************************************************* */

long lexmin(long col)  /*test if basis is lex-min for vertex or ray, if so TRUE */
          /* FALSE if a_r,g=0, a_rs !=0, r > s          */
{
/*do lexmin test for vertex if col=d, otherwise for ray */
  long r,s,i,j;
  for (i=d+1; i<=m;i++)
   {
    r=LOC[B[i]];
    if(zero(A[r][col])) /* necessary for lexmin to fail */
       for (j=0;j<d;j++)
        { 
         s=LOC[C[j]];
         if( B[i] > C[j] )  /* possible pivot to reduce basis */
           {
             if (zero(A[r][d]) ) /* no need for ratio test, any pivot feasible*/
                 { if ( !zero (A[r][s]) ) return(FALSE);
                 }
             else if ( negative(A[r][s]) && ismin(r,s)) 
                  {                       
                     return(FALSE);
                  }
           } /* end of if B[i] ... */
        }
    }
   if(col != d && debug)
        {
        printf("\n lexmin ray in col=%d ",col );
        printA();
        }
   return(TRUE);
} /* end of lexmin */
    
long ismin(long r, long s ) /*test if A[r][s] is a min ratio for col s */
{ 
 long i,j;
 for (i=1;i<=m;i++)
  if( (i != r) &&
         negative(A[i][s]) && comprod(A[i][d],A[r][s],A[i][s],A[r][d] )) 
      { 
        return(FALSE);
      }

 return(TRUE);
}

long myrandom(long num, long nrange) /* return a random number in range 0..nrange-1 */

{
 long i;
 i=( num * 401 + 673 ) % nrange;
 return(i);
}

void updatevolume() /* we have to rescale determinant to update the volume */
{
 mp gcdprod,lcmprod;    /* to hold scale factors */
 mp tN,tD,temp;
 long i;
 itomp(ONE,gcdprod); itomp(ONE,lcmprod);
 for(i=0;i<d;i++) 
    if(B[i]<=m)
     { mulint(Gcd[inequality[C[i]-d]],gcdprod,gcdprod);
       mulint(Lcm[inequality[C[i]-d]],lcmprod,lcmprod);
     }
 mulint(det,gcdprod,temp);
 copy(tN,Nvolume); copy(tD,Dvolume);
 linrat(tN,tD,ONE,temp,lcmprod,ONE,Nvolume,Dvolume);
 if (debug) {prat("\n*Volume=",Nvolume,Dvolume);
             pmp(" lcmprod=",lcmprod);pmp(" gcdprod=",gcdprod);
            }
 
}
        
void printsol(long col, long comment)              /*Print out current solution*/
/*col=d vertex, otherwise ray, comment TRUE if printing vertex incident to ray as comment*/
/* in geometric option                                                                    */
{
 long lexflag=TRUE;
 long i,j;
 long firstterm;
 long origin=TRUE;                                /* true if ray is the origin */
 long row;                                        /* row containing solution */
 long sig;
 long vertex;          /* TRUE for vertex, FALSE for ray */
 long rflag;           /* used to find inequality number for ray column */
 mp mpzero,mpone;      /* zero and one */
 mp Dout;         /* numerator and denominator of reduced output */
 mp Temp,divisor;

  if(col==d) vertex=ONE;
   else      vertex=ZERO;
  itomp(ZERO,mpzero);
  itomp(ONE,mpone);

  /* print all bases - count lex min bases*/
  if(! comment) 
    {lexflag=lexmin(d); /* see if lexmin */ 
     if(vertex) 
       { ++count[2];      /* count new basis if vertex found  */
         if(getvolume) updatevolume();
         linint(sumdet,1,det,1);
         if (lexflag) ++count[1];
       }
     else ++count[0];
     /*print cobasis if printcobasis=TRUE and count[2] a multiple of frequency*/
     if(printcobasis && count[2]==(count[2]/frequency)*frequency )
      {
	if(hull)
     	printf("\nV#%d F#%d B#%d h=%d vertices/rays ",count[1],count[0],count[2],depth);
	else if(voronoi)
          printf("\nV#%d R#%d B#%d h=%d data points ",count[1],count[0],count[2],depth);
            else
     		printf("\nV#%d R#%d B#%d h=%d facets ",count[1],count[0],count[2],depth);
	rflag=-1;
	for(i=0;i<d;i++) 
		{
		temparray[i]=inequality[C[i]-d];
		if(LOC[C[i]]==col) rflag=temparray[i];  /* look for ray index */
                }
     	for(i=0;i<d;i++) reorder(temparray,d);
     	for(i=0;i<d;i++) 
                {
                 printf(" %d",temparray[i]);
                if ((!hull || voronoi) && !vertex && (rflag==temparray[i])) printf("*");
                }
     	pmp(" det=",det);
       }
     }  /* end of if !comment */
    /* if ray, find gcd of the non-zero terms */
    /* if nonnegative, decision variables are recovered from lower half of dictionary*/
  if(nonnegative)
	   for(j=m-d+1;j<=m && B[j]<=m;j++);  
    firstterm=TRUE;
    if(  vertex )
       copy(divisor, det);
    else
      {
      for(i=1;i<=d;i++)      
        {
	 row=LOC[B[i]];
	 if(nonnegative)       /* if m+i basic get correct value from dictionary */
	       {  if (j<=m && B[j]==m+i)
		       copy(Temp,A[LOC[B[j++]]][col]);
                  else mulint(A[row][col],det,Temp); 
               }
          else copy(Temp,A[row][col]);
	  storesign(Temp,POS);
          if (!zero(Temp))
	    {  
             if( i > 1 ) origin=FALSE; 
             if(firstterm)
		{ copy(divisor,Temp);
                  firstterm=FALSE;
                }
             else gcd(divisor,Temp);
            }
          }   /* end of for loop to get gcd */
         if( hull && origin )          /* ray is 1 0 ...0 which is not output as a facet */
              { --count[0];
                  return;
              }
         } /* end of else */

   /* if nonnegative, decision variables are recovered from lower half of dictionary*/
  if(nonnegative)
	   for(j=m-d+1;j<=m && B[j]<=m;j++);  
  if((lexflag || allbases || !vertex ) && !( hull && vertex ))
                                          /* skip trivial vertex for hull computation*/
    {
     if( comment ) printf(" * ");
       else        printf("\n");
     if ( ! hull )                    /* for hull we strip the first column */
           printf("%ld ",vertex);     /* output a one for vertex else zero */
     for(i=1;i<=d;i++)                /* print solution */
             /* skip last column if voronoi set */
         if( ( i < d ) || !voronoi )
	   {
	     row=LOC[B[i]];
	     if(nonnegative)       /* if m+i basic get correct value from dictionary */
		{ if (j<=m && B[j]==m+i)
		       copy(Temp,A[ LOC[B[j++]]][col]);
		    else mulint(A[row][col],det,Temp); 
                 }
             else copy(Temp,A[row][col]);
             copy(Dout,divisor);
             reduce(Temp,Dout);
             sig=sign(Temp)*sign(Dout);
             storesign(Temp,sig);
             storesign(Dout,POS);
             prat("",Temp,Dout);
	    }
     }      /* end of if (lexflag||allbases) */
  if (debug) printA();
  fflush(stdout);
 save_basis();
}


void update(long *i, long *j)    /*update the B,C, LOC arrays after a pivot */
                                 /*   involving B[bas] and C[cob]           */
{
  long leave,enter;

  leave=B[*i];
  enter=C[*j];
  newrow=LOC[leave];     /* remember latest entry into basis for ray testing*/
  LOC[leave]=LOC[enter]; 
  LOC[enter]=newrow;
  B[*i]=enter;
  reorder(B,m+1);
  C[*j]=leave;
  reorder(C,d);
/* restore i and j to new positions in basis */
  for (*i=1; B[*i] != enter ; (*i)++); /*Find basis index*/
  for (*j=0; C[*j] != leave ; (*j)++); /*Find co-basis index*/
}

void reorder(long a[], long range)   /*reorder array in increasing order with one misplaced element*/
{
  long i,temp;
  for (i=0;i<range-1;i++) 
       if (a[i] > a[i+1])
               { temp=a[i]; a[i]=a[i+1]; a[i+1]=temp; }
  for (i=range-2;i>=0;i--) 
       if (a[i] > a[i+1])
               { temp=a[i]; a[i]=a[i+1]; a[i+1]=temp; }

}    /* end of reorder */

long atos(char s[])   /* convert s to integer */
{
  long i,j;
  j=0;
  for (i=0; s[i] >= '0' && s[i] <= '9';++i)
      j=10*j+s[i]-'0';
  return(j);
}

void stringcpy (char *s, char *t) /*copy t to s pointer version*/
{
 while (((*s++) =(*t++)) != '\0');
}
/*********************************************************/
/*          End of Miscellaneous                         */
/******************************************************* */

/***************************************************************/
/*                                                             */
/*            Package of I/O routines                          */
/*                                                             */
/***************************************************************/
void readA(long *strace, long *etrace, char fname []) /* read input and set up problem and dictionary  */

{long i,j,k,n;
 long *Cobasic;               /* when restarting, Cobasic[j]=1 if j is in cobasis */
                              /*        else   Cobasic[j]=0                       */
 long *facet;
 long maximize=FALSE;         /*flag for LP maximization                          */
 long minimize=FALSE;         /*flag for LP minimization                          */
 long restart=FALSE;          /* TRUE if restarting from some cobasis             */
 long givenstart=FALSE;       /* TRUE if a starting cobasis is given              */
 mp scale,Temp,Temp2,objlcm,mpone;
 char name[100];
 long dec_digits=0;
 
 printf(TITLE);
 printf(VERSION);   printf(AUTHOR);
 printf("\n*Compiled for ");printf(BIT); printf(" bit integers");
 scanf("%s",name);
 stringcpy(fname,"");
 if (strcmp(name,"begin")!=0 && strcmp(name,"digits")!=0 &&
             strcmp(name,"V-representation")!=0 && strcmp(name,"H-representation")!=0)
	{  printf("\n%s",name);/*first line assumed polyhedra name*/
           stringcpy(fname,name);
           scanf("%s",name);
        }

 while (strcmp(name,"begin")!=0)  /*skip until "begin" found processing options */
        {
		  if ((strcmp(name,"hull")==0) || (strcmp(name,"V-representation")==0))
			{
                          hull=TRUE;
			};
		  if (strcmp(name,"digits")==0)
			{
			  if (scanf("%ld",&dec_digits)==EOF)
				notimpl("No begin line");
                          printf("\n*digits %d",dec_digits);
			};
                  if (scanf("%s",name) == EOF )
                          notimpl("No begin line");
	   
         } /* end of while */
 
 if (dec_digits == 0){
   digits=DEC2DIG(DEFAULT_DIGITS);
 } else {
   digits=DEC2DIG(dec_digits);
 } 
 record_digits=0;
 
 if (digits>MAX_DIGITS){
   printf("\nDigits must be at most %d\nChange MAX_DIGITS and recompile",
		   DIG2DEC(MAX_DIGITS));
   notimpl("");
 }
  


  if (scanf("%ld %ld %s",&m,&n,name)==EOF)notimpl("No data in file");
  printf("\n*Input size m=%d rows n=%d columns",m,n);
  d=n-1;                       /* d=col dimension of A */
  if (hull ) 
        d=n;              /* extra column for hull*/
 Cobasic=(long *)CALLOC((unsigned)m+d+2,sizeof(long));
 facet=(long *)CALLOC((unsigned)d+1,sizeof(long));
 temparray=(long *)CALLOC((unsigned)d+1,sizeof(long)); /* for sorting indices */
 itomp(ONE,mpone);


  alloc_memory(m,d);

/* Initialize determinant */
  itomp(ONE,det);

  isave=(long *)CALLOC((unsigned)(m*d),sizeof(long)); /* arrays for estimator */
  jsave=(long *)CALLOC((unsigned)(m*d),sizeof(long)); /* arrays for estimator */

  if( strcmp(name,"integer") != 0 && strcmp(name,"rational") != 0 )
	    notimpl("Data type must be integer of rational");
/*m+d+1 is the number of variables, labelled 0,1,2,...,m+d  */
/*  initialize array to zero   */
  for(i=0;i<=m;i++)
    for(j=0;j<=d;j++)
      itomp(ZERO,A[i][j]);
      
/*initialize basis and co-basis indices, and row col locations*/
  for(i=1;i<=m;i++)   { B[i]=d+i; LOC[d+i]=i;}
  B[0]=0; LOC[0]=0;
  for(j=0;j<d;j++) 
     { C[j]=1+j; LOC[1+j]=j; }    
  C[d]=m+d+1; LOC[m+d+1]=d;
/* default is to look for starting cobasis in last d rows, unless otherwise specified*/
  for (i=0;i<d;i++) inequality[i]=m+i-d+1;
  noduprays=TRUE;              /* we set this in the input loop if cone or hull of polytope*/
  for (i=1;i<=m;i++)            /* read in input matrix row by row                 */
     {
    if ( hull )   /*for hull, we have to append an extra column of zeroes*/
        {itomp(ZERO,A[i][d]);
         itomp(ONE, A[0][d]);
        }
    else
         readrat(A[i][d],A[0][d]);  /* b vector first on input line, row 0 holds denom */
     copy(Lcm[i],A[0][d]);
     copy(Gcd[i],A[i][d]);        /* Gcd of numerators */
     for (j=0;j<d;j++) 
          {  if(readrat(A[i][j],A[0][j]))
                            lcm(Lcm[i],A[0][j]);   /* update lcm of denominators */
             if( !zero(A[i][j]))
	        if (zero(Gcd[i])) copy(Gcd[i],A[i][j]);
		 else
		   {  copy(Temp,A[i][j]);
                      gcd(Gcd[i],Temp);   /* update gcd of numerators   */
                   }
		   
          }

     if (!hull && !zero(A[i][d])) noduprays=FALSE;    /* all rows must have a zero in column one  */
     if (hull && !one(A[i][0]))   noduprays=FALSE;      /* all rows must have a one in column one */

     storesign(Gcd[i],POS); storesign(Lcm[i],POS);
     if( greater(Gcd[i],mpone) || greater(Lcm[i],mpone) )
        for (j=0;j<=d;j++) 
          {
           divint(A[i][j],Gcd[i],Temp);  /*reduce numerators by Gcd  */
           mulint(Lcm[i],Temp,Temp);     /*remove denominators*/
           divint(Temp,A[0][j],A[i][j]); /*reduce by former denominator*/
          }

     } /* end of for i=       */

/* duplicates will not be printed for hull of polytope, or for a cone */
  if(noduprays) printf("\n*Lexminrays flag is set");

/* read in flags */
  while ( scanf("%s",name) != EOF )
      {
        if( strcmp(name,"debug")==0) 
	      {
	      scanf("%ld %ld",strace,etrace); 
              printf("\n*%s from B#%d to B#%d",name,*strace,*etrace);
	      if(*strace<=1) debug=TRUE; 
	      }
        if( strcmp(name,"startingcobasis")==0)
              { printf("\n*startingcobasis");
                givenstart=TRUE;
                readfacets(inequality); 
              }

        if( strcmp(name,"restart")==0)  
	    {
	     restart=TRUE; 
	     scanf("%ld %ld %ld %ld",&count[1],&count[0],&count[2],&depth);
	     printf("\n*%s V#%d R#%d B#%d h=%d facets ",name,count[1],count[0],count[2],depth);
             readfacets(facet);
              }          /* end of restart */

/* The next flags request a LP solution only */
/* The LP will be solved after initialization, and no vertex enumeration is performed */
        if( strcmp(name,"maximize")==0 || strcmp(name,"minimize")==0) 
      	 {
                if  (strcmp(name,"maximize")==0) maximize=TRUE;
                if  (strcmp(name,"minimize")==0) minimize=TRUE;
                printf ("\n*%s",name);
                readrat(A[0][d],oD[d]); /* constant term of objective row */
                prat(" ",A[0][d],oD[d]);
                copy(objlcm,oD[d]);
     		for (j=0;j<d;j++) 
                  {
          	   if(readrat(A[0][j],oD[j]))
                             lcm(objlcm,oD[j]);   /* update lcm of denominators */
                   prat(" ",A[0][j],oD[j]);
                   if (minimize) changesign(A[0][j]);
                  }
    		storesign(objlcm,POS);
     		if( greater(objlcm,mpone) )
        	for (j=0;j<=d;j++) 
                     {
                 	  mulint(objlcm,A[0][j],A[0][j]);    /*remove denominators*/
                          copy(Temp,A[0][j]);
                          divint(Temp,oD[j],A[0][j]);
                      }
                if (debug)printA();

         }     /* end of LP setup */
        if( strcmp(name,"volume")==0)
	      {
               printf("\n*%s",name);
	       getvolume=TRUE; 
	      }
        if( strcmp(name,"geometric")==0)
	      {
               printf("\n*%s",name);
	       if (hull & !voronoi)
                 printf(" - option for H-representation or voronoi only, skipped");
                else  geometric=TRUE; 
	      }
        if( strcmp(name,"allbases")==0)
	      {
               printf("\n*%s",name);
	       allbases=TRUE; 
	      }

        if( strcmp(name,"printcobasis")==0)
	      {
               scanf("%ld",&frequency);
               printf("\n*%s  %d",name,frequency);
	       printcobasis=TRUE; 
	      }

        if( strcmp(name,"cache")==0)  
	      {
	       scanf("%ld",&dict_limit);
               printf("\n*%s  %d",name,dict_limit);
               if(dict_limit < 1 ) dict_limit=1;
	      }

        if( strcmp(name,"maxdepth")==0)  
	      {
	       scanf("%ld",&maxdepth);
               printf("\n*%s  %d",name,maxdepth);
	      }
        if( strcmp(name,"mindepth")==0)  
	      {
	       scanf("%ld",&mindepth);
               printf("\n*%s  %d",name,mindepth);
	      }
        if( strcmp(name,"nonnegative")==0)  
	      {
               printf("\n*%s",name);
	       if(!hull) 
                   nonnegative=TRUE;
               else printf(" - option for H-representation only, skipped");
	      }

        if( strcmp(name,"seed")==0)
              {
               scanf("%ld",&seed);
               printf("\n*seed= %ld ",seed);
              }

        if( strcmp(name,"estimates")==0)
              {
               scanf("%ld",&runs);
               printf("\n*%ld %s",runs,name);
              }

	 if ((strcmp(name,"voronoi")==0) || (strcmp(name,"Voronoi")==0))
              {
		  if( !hull )
                        printf("\n*voronoi requires V-representation - option skipped");
                  else
		  { voronoi=TRUE;
		    printf("\n*voronoi ");
                  }
               }
         
       }        /* end of while for reading flags */

/* for voronoi convert to h-description using the transform                  */
/* a_0 .. a_d-1 -> (a_0^2 + ... a_d-1 ^2)-2a_0x_0-...-2a_d-1x_d-1 + x_d >= 0 */
/* note constant term is stored in column d, and column d-1 is all ones      */
/* the other coefficients are multiplied by -2 and shifted one to the right  */
  if(debug) printA();
  if(voronoi)
	{
         hull=FALSE;
         for(i=1;i<=m;i++)
		{
                 if (zero(A[i][0])) 
			notimpl("with voronoi option column one must be all one");
                copy(scale,A[i][0]); /*adjust for scaling to integers of rationals*/
		itomp(ZERO,A[i][d]);
		for(j=1;j<d;j++) /* transform each input row */
		{
		  copy(Temp,A[i][j]);
		  mulint(A[i][j],Temp,Temp);
		  linint(A[i][d],ONE,Temp,ONE);
		  linint(A[i][j-1],ZERO,A[i][j],-TWO);
		  mulint(scale,A[i][j-1],A[i][j-1]);
		}  /* end of for (j=1;..) */
                copy(A[i][d-1],scale);
		mulint(scale,A[i][d-1],A[i][d-1]);
                }  /* end of for (i=1;..) */
          if(debug) printA();
         }      /* end of if(voronoi)     */
  if (! ( maximize || minimize ))
        for(j=0;j<=d;j++) itomp(ZERO,A[0][j]);

/* Now we pivot to standard form, and then find a primal feasible basis       */
/* Note these steps MUST be done, even if restarting, in order to get         */
/* the same index/inequality correspondance we had for the original prob.     */
/* The inequality array is used to give the insertion order                   */
/* and is defaulted to the last d rows when givenstart=FALSE                  */

   getabasis(givenstart,inequality);


/* Reset up the inequality array to remember which index is which input inequality */
/* inequality[B[i]-d] is row number of the inequality with index B[i]              */
/* inequality[C[i]-d] is row number of the inequality with index C[i]              */

   for (i=1;i<=m;i++)  inequality[i]=i;


/* Do dual pivots to get primal feasibility */
	if (!primalfeasible()) notimpl("No feasible solution");

/* reindex basis to 0..m if necessary */
/* we use the fact that cobases are sorted by index value */
   if(debug) printA();
   while(C[0]<=m)
          { i=C[0]; k=LOC[B[i]]; j=inequality[B[i]-d];
            LOC[B[i]]=LOC[C[0]]; LOC[C[0]]=k; 
            inequality[B[i]-d]=inequality[C[0]-d]; inequality[C[0]-d]=j;
            C[0]=B[i]; B[i]=i; 
            reorder(C,d);
          }

   if(debug)
   {
   	printf("\n*Inequality numbers for indices %d .. %d : ",d+1,m+d);
   	for (i=1;i<=m;i++) printf(" %d ",inequality[i]);
   }
   if(hull)
         printf("\n*Starting facet defined by vertices/rays ");
   else
     if(voronoi)
         printf("\n*Starting vertex defined by data points ");
         else
         	printf("\n*Starting vertex defined by facets ");
     for(i=0;i<d;i++) temparray[i]=inequality[C[i]-d];
     for(i=0;i<d;i++) reorder(temparray,d);
     for(i=0;i<d;i++) printf(" %d",temparray[i]);
   printf("\n");
/* Now solve LP if that is all that is required, and go home */
   if( maximize || minimize )
   {
      solvelp(maximize,objlcm);
      printf("\n*LP solution only requested\n");
      exit(0);
   }

/* re-initialize cost row to -det */
  i=1;
  for(j=0;j<=d;j++) 
     { 
      copy(A[0][j],det);
      storesign(A[0][j],NEG);
      }  

  itomp(ZERO,A[0][d]);                       /* zero optimum objective value */

		 

  if (restart)
      {
         if (debug) printf("\nPivoting to restart co-basis");
         restartpivots(facet,Cobasic);
         if (debug) printA();
      }
}          /* end of readA() */


void readfacets(long facet[])  /* read and check facet list for obvious errors during start/restart*/
{
	long i,j;

        for (j=0;j<d;j++) 
                {
                 scanf("%ld",&facet[j]);
		 printf(" %d",facet[j]);
                 if (facet[j] < 1 || facet[j] > m ) 
                    { printf("\n Facet indices must be in range 1 .. %d ",m);
                      notimpl("");
                    }
                 for(i=0;i<j;i++) 
                    if (facet[i]==facet[j])
                    { printf("\n Facet indices must be distinct and in range 1 .. %d ",m);
                      notimpl("");
                    }
                 }
} /* end of readfacets */

long readrat(mp Na, mp Da) /* read a rational or integer and convert to mp with base BASE */
               /* returns true if denominator is not one                      */
{
  char in[MAXINPUT],num[MAXINPUT],den[MAXINPUT];
  scanf("%s",in);
  atoaa(in,num,den);     /*convert rational to num/dem strings*/
  atomp(num,Na);
  if (den[0]=='\0') 
        {
        itomp(1L,Da);
        return(FALSE);
        }
   atomp(den,Da);
   return(TRUE);
}
void atomp(char s[], mp a)  /*convert string to mp integer*/
{
	mp mpone;
 	long diff,ten,i,sig;
 	itomp(1L,mpone);
        ten=10L;
	for (i=0; s[i]==' ' || s[i]=='\n' || s[i]=='\t'; i++);
               /*skip white space*/
        sig=POS;
        if( s[i] == '+' || s[i]=='-' ) /* sign */
           sig=(s[i++]=='+') ? POS : NEG;
	itomp(0L,a);
	while ( s[i] >= '0' && s[i] <= '9')
        { diff=s[i] - '0';
          linint(a,ten,mpone,diff);
          i++;
        }
	storesign(a,sig);
}  /* end of atomp */

void readmp(mp a)      /* read an integer and convert to mp with base BASE */
{
  long in;
  scanf("%ld",&in);
  itomp(in,a);
}

void itomp(long in, mp a)     /* convert integer i to multiple precision with base BASE */
{
  long i;
  a[0]=2;          /* initialize to zero */
  for(i=1;i<digits;i++) a[i]=0;
  if (in < 0 ) {
                storesign(a,NEG);
                in=in*(-1);
                }
  i=0;
  while (in != 0) {
                   i++;
                   a[i]= in-BASE*(in/BASE);
                   in=in/BASE;
                   storelength(a,i+1);
                   }
}        /* end of itomp  */

void atoaa(char in[], char num[], char den[])  /* convert rational string in to num/den strings*/
{
 long i,j;
 for(i=0;in[i] != '\0' && in[i] != '/';i++) num[i]=in[i];
 num[i]='\0';
 den[0]='\0';
 if (in[i] == '/')
    {
     for(j=0;in[j+i+1] != '\0' ;j++) den[j]=in[i+j+1];
     den[j]='\0';
    }
}               /* end of atoaa */


printA()        /* print the integer m by n array A 
                   with B,C,and LOC vectors         */
{
  long i,j;
  printf("\n Basis    ");
  for(i=0;i<=m;i++) printf("%d ",B[i]);
  printf(" Location ");
  for(i=0;i<=m;i++) printf("%d ",LOC[B[i]]);
  printf("\n Co-Basis ");
  for(i=0;i<=d;i++) printf("%d ",C[i]);
  printf(" Location ");
  for(i=0;i<=d;i++) printf("%d ",LOC[C[i]]);
  pmp(" det=",det);
  printf("\n");
  for (i=0;i<=m;i++)
  {
  for (j=0;j<=d;j++) 
       pimat(i,j,A[LOC[B[i]]][LOC[C[j]]],"A");
  printf("\n");
  }
}

void prat(char name[],mp Nt,mp Dt)  /*print the long precision rational Nt/Dt  */
{
	long i;
        printf("%s",name);
	if (sign(Nt)==NEG) printf("-");
        printf("%u",Nt[length(Nt)-1]);
	for (i=length(Nt)-2;i>=1;i--) printf(FORMAT,Nt[i]);
	if( !(Dt[0]==2 && Dt[1]==1))  /* rational */
	     { printf("/");
	       if (sign(Dt)==NEG) printf("-");
               printf("%u",Dt[length(Dt)-1]);
	       for (i=length(Dt)-2;i>=1;i--) printf(FORMAT,Dt[i]);
              }
        printf(" ");
}

void prtotals(double best,double vest,double rest, char fname[] ) /*print final totals*/
{
mp temp,dfactorial;
long i;

printf(TITLE); printf(VERSION);
if (  strcmp(fname,"") != 0 )
  printf("\n*End of processing for %s",fname);
if (hull)
      printf("\n*Number of: facets=%ld  bases=%ld",count[0],count[2]);
else
      printf("\n*Number of: vertices=%ld  rays=%ld  bases=%ld",count[1],count[0],count[2]);
if( maxdepth < MAXD )
      {
      printf("\n*Tree evaluation truncated at depth %ld",maxdepth);
      if( !hull || voronoi)
            printf(": Rays at this depth not reported");
      if(hull)
            printf(": Facets at this depth not reported");
      }
itomp(ONE,dfactorial);
for(i=2;i<=d;i++)
   { itomp(i,temp);
     mulint(temp,dfactorial,dfactorial);
   }
printf("\n*Max digits= %d/%d", DIG2DEC(record_digits),DIG2DEC(digits));
printf("\n*Dictionary Cache: max size= %d misses= %d/%d   Tree Depth= %d",dict_count,cache_misses,cache_tries,deepest);

printf("\n*Sum of det(B)=");
pmp("",sumdet);
if(getvolume)
 {
     if(!hull)
             if(voronoi)
             	printf("\n*Volume results unpredictable when voronoi option set");
              else  printf("\n*Volume results unpredictable for input H-representation");
     /*reduce(Nvolume.dfactorial);*/
     mulint(dfactorial,Dvolume,Dvolume);
     if(hull)
      { /* For hull option multiply by d to correct for lifting */
        itomp(d,temp);
        mulint(temp,Nvolume,Nvolume);
      }

     reduce(Nvolume,Dvolume);
     printf("\n*Volume=");
     prat("",Nvolume,Dvolume);
 }
if(count[0] > 1 && !noduprays  ) /* don't need warning if noduprays TRUE */ 
   { if (hull)
                printf("\n*Note! Duplicate facets may be present");
     else
                printf("\n*Note! Duplicate rays may be present");
   }
if(hull)
       printf("\n*Replace ***** after begin line by number of facets");
else
       printf("\n*Replace ***** after begin line by number of vertices+rays");
if((best > 0) || (rest > 0) )
  {
   if (hull)
      printf("\n*Estimates:  facets=%g  bases=%g",count[0]+rest,count[2]+best);
   else
      printf("\n*Estimates: vertices=%g    rays=%g    bases=%g",count[1]+vest,count[0]+rest,count[2]+best);
   printf("\n*Total number of tree nodes evaluated: %ld",totalnodes);
  }
#ifndef OMIT_TIMES
ptimes();
#endif
printf("\n");
}    /* end of print final totals */

void pimat(long r,long s,mp Nt,char name[])  /*print the long precision integer
                   in row r col s of matrix A */
{
 int i;
	if (s==0) printf("%s[%d][%d]=",name,B[r],C[s]);
           else   printf("[%d]=",C[s]);
        if (sign(Nt)==NEG) printf("-");
	printf("%u",Nt[length(Nt)-1]);
		for (i=length(Nt)-2;i>=1;i--) printf(FORMAT,Nt[i]);

}

void pmp(char name[],mp a)  /*print the long precision integer a*/
{
	long i;
	printf("%s",name);
	if (sign(a)==NEG) printf("-");
        printf("%u",a[length(a)-1]);
	for (i=length(a)-2;i>=1;i--) printf(FORMAT,a[i]);
}
/***************************************************************/
/*                                                             */
/*     End of package of I/O routines                          */
/*                                                             */
/***************************************************************/
/***************************************************************/
/*                                                             */
/*     Package of routines for multiple precision arithmetic   */
/*                                                             */
/***************************************************************/
void gcd(mp u, mp v)   /*returns u=gcd(u,v) destroying v */
             /*Euclid's algorithm.  Knuth, II, p.320  
             modified to avoid copies r=u,u=v,v=r
	     Switches to single precision when possible for greater speed */
{
  mp r;
  unsigned long ul,vl;
  long i;
    
  if(greater(v,u)) goto bigv;
  bigu:
       if(zero(v))  return;
  if ((i=length(u))<MAXSPLEN || i==MAXSPLEN && u[MAXSPLEN-1]<MAXSPVAL) goto quickfinish;
       divint(u,v,r);
       normalize(u);

  bigv:
       if(zero(u)) { copy(u,v); return;}
  if ((i=length(v))<MAXSPLEN || i==MAXSPLEN && v[MAXSPLEN-1]<MAXSPVAL) goto quickfinish;
       divint(v,u,r);
       normalize(v);
 goto bigu;
  /* Base 10000 only at the moment */
  /* when u and v are small enough, transfer to single precision integers */
  /* and finish with euclid's algorithm, then transfer back to mp */
 quickfinish:
  ul = vl = 0;
  for (i=length(u)-1;i>0;i--)
    ul = BASE*ul+u[i];
  for (i=length(v)-1;i>0;i--)
    vl = BASE*vl+v[i];
  if (ul>vl) goto qv;
 qu:
  if (!vl) 
  {
    for (i=1;ul;i++)
    {
      u[i]=ul%BASE;
      ul=ul/BASE;
    }
    storelength(u,i);
    return;
  }
  ul %= vl;
 qv:
  if (!ul) 
  {
    for (i=1;vl;i++)
    {
      u[i]=vl%BASE;
      vl=vl/BASE;
    }
    storelength(u,i);
    return;
  }
  vl %= ul;
  goto qu;
}

void reduce(mp Na,mp Da)    /* reduces Na Da by gcd(Na,Da) */
{
  mp Nb,Db,Nc,Dc;
  copy(Nb,Na);  copy(Db,Da); storesign(Nb,POS); storesign(Db, POS);
  copy(Nc,Na);  copy(Dc,Da); 
  gcd(Nb,Db); /* Nb is the gcd(Na,Da) */
  divint(Nc,Nb,Na); divint(Dc,Nb,Da);
}

void lcm(mp a, mp b)      /* a = least common multiple of a, b; b is preserved */
{
  mp u,v;
  copy(u,a); copy(v,b);
  gcd(u,v);
  divint(a,u,v);   /* v=a/u   a contains remainder = 0 */
  mulint(v,b,a);
}             /* end of lcm */
long greater(mp a, mp b)  /* tests if a > b and returns (TRUE=POS) */
{
  long i;

  if(a[0] > b[0]) return(TRUE);
  if(a[0] < b[0]) return(FALSE);

  for (i=length(a)-1;i>=1;i--)
     {
      if(a[i] < b[i]) 
              {
              if(sign(a) == POS) return (0);
                        else return (1);
              }
      if(a[i] > b[i]) 
              {
              if(sign(a) == NEG) return (0);
                        else return (1);
              }
     }
  return(0);
}

void copy(mp a, mp b)   /* assigns a=b  */
{
   long i;
   for (i=0;i<=length(b);i++) a[i]=b[i];
}



void linint(mp a,long ka,mp b,long kb) /*compute a*ka+b*kb --> a */
/***Handbook of Algorithms and Data Structures P.239 ***/
{long i,la,lb;
la=length(a);   lb=length(b);
for (i=1;i<la;i++) a[i] *= ka;
if(sign(a) != sign(b)) kb=(-kb);
if(lb>la) {
	storelength(a,lb);
	for (i=la; i<lb; i++) a[i]=0;
	  }
for (i=1;i<lb;i++) a[i] += kb*b[i];
normalize(a);
}   /***end of linint***/

void normalize(mp a)
{long cy,i,la;
la=length(a);
start:
cy=0;
for(i=1;i<la;i++){
	cy=(a[i]+=cy)/BASE;
	a[i]-=cy*BASE;
	if(a[i]<0){a[i]+=BASE;cy--;}
	}
while(cy>0) {
	a[i++]=cy%BASE;
	cy/=BASE;}
if(cy<0) {
	a[la-1]+=cy*BASE;
	for (i=1;i<la;i++) a[i]=(-a[i]);
	storesign(a,sign(a)==POS ? NEG : POS );
	goto start;
	}
while (a[i-1]==0 && i>2) i--;
if ( i > record_digits) {
        if ( ( record_digits= i  ) > digits)
          digits_overflow(la);
  };
storelength(a,i);
if(i==2 && a[1]==0) storesign(a,POS);
}  /* end of normalize */

void mulint(mp a,mp b,mp c) /* multiply two integers a*b --> c */

     /***Handbook of Algorithms and Data Structures, p239  ***/
{long nlength,i,j,la,lb;
 /*** b and c may coincide ***/
 la=length(a);
 lb=length(b);
 nlength=la+lb-2;
 if(nlength > digits ) 
  digits_overflow(nlength);

for (i=0;i<la-2;i++) c[lb+i]=0;
for (i=lb-1;i>0;i--) {
	for(j=2;j<la;j++)
		if((c[i+j-1]+=b[i]*a[j]) >
		      MAXD-(BASE-1)*(BASE-1)-MAXD/BASE){
		      c[i+j-1] -= (MAXD/BASE)*BASE;
		      c[i+j] += MAXD/BASE;
		      }
	c[i] = b[i]*a[1];
	}
storelength(c,nlength);
storesign(c,sign(a)==sign(b) ? POS : NEG );
normalize(c);
}  /***end of mulint ***/

long comprod(mp Na,mp Nb,mp Nc,mp Nd)      /* +1 if Na*Nb > Nc*Nd  */
                          /* -1 if Na*Nb < Nc*Nd  */
                          /*  0 if Na*Nb = Nc*Nd  */
{
 mp mc,md;
 mulint(Na,Nb,mc);
 mulint(Nc,Nd,md);
 linint(mc,ONE,md,-ONE);
 if(positive(mc)) return (1);
 if(negative(mc)) return (-1);
 return(0);
}

/********************************************************/
/* Divide two multiple precision integers (c=a/b).      */
/* a is destroyed and contains the remainder on return. */
/* From Knuth Vol.2 SemiNumerical Algorithms            */
/********************************************************/
void divint(mp a, mp b, mp c ) /* c=a/b, a contains remainder on return */
{
  long cy, la, lb, lc, d1, s, t, sig;
  long i, j, qh;
  
/*  figure out and save sign, do everything with positive numbers*/
  sig=sign(a)*sign(b);

  la = length(a);
  lb = length(b);
  lc = la-lb+2;
  if ( la<lb )
  {
    storelength(c,TWO);
    storesign(c,POS);
    c[1] = 0;
    normalize(c);
    return;
  }
  for( i=1; i<lc; i++ ) c[i] = 0;
  storelength(c,lc);
  storesign(c, (sign(a)==sign(b)) ? POS : NEG );

  /******************************/
  /* division by a single word: */
  /*  do it directly            */
  /******************************/

  if( lb==2 ) {
    cy = 0;
    t = b[1];
    for (i=la-1; i>0; i--)  {
      cy = cy*BASE+a[i];
      a[i] = 0;
      cy -= (c[i] = cy/t) * t;
    }
    a[1] = cy;
    storesign(a,(cy==0) ? POS : sign(a));
    storelength(a,TWO);
    /*      set sign of c to sig  (**mod**)            */
    storesign(c,sig);
    normalize(c);
    return;
  }
  else
  {
    /* mp's are actually DIGITS+1 in length, so if length of a or b = */
    /* DIGITS, there will still be room after normalization. */
    /****************************************************/
    /* Step D1 - normalize numbers so b > floor(BASE/2) */
    d1 = BASE/(b[lb-1] + 1);
    if (d1 > 1)
    {
      cy = 0;
      for (i=1;i<la;i++)
      {
	cy = (a[i]=a[i]*d1+cy)/BASE;
	a[i] %= BASE;
      }
      a[i] = cy;
      cy = 0;
      for (i=1;i<lb;i++)
      {
	cy = (b[i]=b[i]*d1+cy)/BASE;
	b[i] %= BASE;
      }
      b[i] = cy;
    }
    else
    {
      a[la] = 0;		/* if la or lb = DIGITS this won't work */
      b[lb] = 0;
    }
    /*********************************************/
    /* Steps D2 & D7 - start and end of the loop */
    for (j = 0;j<=la-lb;j++)
    {
      /*************************************/
      /* Step D3 - determine trial divisor */
      if (a[la-j] == b[lb-1])
	qh = BASE - 1;
      else
      {
	s = (a[la-j]*BASE + a[la-j-1]);
	qh = s/b[lb-1];
	while (qh*b[lb-2] > (s - qh*b[lb-1])*BASE + a[la-j-2])
	  qh--;
      }
      /*******************************************************/
      /* Step D4 - divide through using qh as quotient digit */
      cy = 0;
      for (i=1;i<=lb;i++)
      {
	s = qh*b[i] + cy;
	a[la-j-lb+i] -= s%BASE;
	cy = s/BASE;
	if (a[la-j-lb+i] < 0)
	{
	  a[la-j-lb+i] += BASE;
	  cy++;
	}
      }
      /*****************************************************/
      /* Step D6 - adjust previous step if qh is 1 too big */
      if (cy)
      {
	qh--;
	cy = 0;
	for (i=1;i<=lb;i++)	/* add a back in */
	{
	  a[la-j-lb+i] += b[i] + cy;
	  cy = a[la-j-lb+i]/BASE;
	  a[la-j-lb+i] %= BASE;
	}
      }
      /***********************************************************************/
      /* Step D5 - write final value of qh.  Saves calculating array indices */
      /* to do it here instead of before D6 */
      
      c[la-lb-j+1] = qh;
      
    }
    /**********************************************************************/
    /* Step D8 - unnormalize a and b to get correct remainder and divisor */
    
    for (i=lc;c[i-1]==0 && i>2;i--); /* strip excess 0's from quotient */
    storelength(c,i);
    if(i==2 && c[1]==0) storesign(c,POS);
    cy = 0;
    for (i=lb-1;i>=1;i--)
    {
      cy = (a[i]+=cy*BASE)%d1;
      a[i] /= d1;
    }
    for (i=la;a[i-1]==0 && i>2;i--); /* strip excess 0's from quotient */
    storelength(a,i);
    if(i==2 && a[1]==0) storesign(a,POS);
    if (cy) printf("divide error");
    for (i=lb-1;i>=1;i--)
    {
      cy = (b[i]+=cy*BASE)%d1;
      b[i] /= d1;
    }
  }
}

void notimpl(char s[])
{fprintf(stderr,"\nAbnormal Termination  %s\n",s);
 exit(1);
}
/***************************************************************/
/*                                                             */
/*  End of package for multiple precision arithmetic           */
/*                                                             */
/***************************************************************/

/* start of db routines */


#include <string.h>

void cache_dict(i,j)
{

  if (dict_limit > 1)
	{


	 /*
	  * The _current_ record is the one that we will be restoring.
	  */
	  Qtail->i = i;
	  Qtail->j = j;
	  copy(Qtail->det,det);

	  /*
	   * Now move Qtail forward and copy the Amatrix accross.
	   *
	   */

	  pushQ();			/* Make sure there is somewhere to move the tail to*/


	  memcpy(Qtail->Araw,(Qtail->prev)->Araw,(d+1)*(digits+1)*(m+1)*sizeof(long));

	  A=(Qtail->A);
	  
	}
  
}

/* 
 * pushQ():
 * this routine ensures that Qtail points to a record that 
 * may be copied into.
 *
 * It may create a new record, or it may just move the head pointer
 * forward so that know that the old record has been overwritten.
 */
#if 0
#define TRACE(s) fprintf(stderr,"\n%s %p %p\n",s,Qhead,Qtail);
#else
#define TRACE(s)
#endif

void pushQ()
{
  dict_rec *p;

  if ( (Qtail->next) == Qhead ) 
	{
	  /* the Q is full */
	  if (dict_count < dict_limit) 
		{
		  /* but we are allowed to create more */
		  p=new_dict_rec(m,d);
  
		  if (p) 
			{
		
			  /* we successfully created another record */
			  
			  p->next = Qtail->next;
			  (Qtail->next)->prev = p;
			  (Qtail->next)=p;
			  p->prev = Qtail;
		
			  dict_count++;
			  Qtail=p;	  

			  TRACE("Added new record to Q");
			  
			}
		  else
			{
			  /* virtual memory exhausted. bummer */
			  Qhead=Qhead->next;
			  Qtail=Qtail->next;	  

			  TRACE("VM exhausted");
			  
			}
		}
	  else
		{
		  /*
		   * user defined limit reached. start overwriting the
		   * beginning of Q 
		   */
		  Qhead=Qhead->next;
		  Qtail=Qtail->next;	  
		  TRACE("User  limit");
		  
		}
	}
  
  else
	{
	  Qtail=Qtail->next;
	  TRACE("Reusing");
	}		  
}


#define NULLRETURN(e) if (!(e)) return NULL;


dict_rec *new_dict_rec(m,d)
{
  dict_rec *p;
  void *calloc(),*malloc();
  int i,j;
  int mp_width,row_width;
  
  NULLRETURN(p=(dict_rec *)malloc(sizeof(dict_rec)));
  
  mp_width=digits+1;
  row_width=(d+1)*mp_width;

  NULLRETURN(p->det=calloc(mp_width,sizeof(long)));
  
  
  NULLRETURN((p->Araw)=calloc((m+1)*row_width,sizeof(long)));
  
  NULLRETURN((p->A)=calloc((m+1),sizeof(mp_1d_array_t)));
  
  for (i=0; i<m+1; i++){
	NULLRETURN(p->A[i]=calloc((d+1),sizeof(mp *)));
		
	for(j=0; j<d+1; j++)
	  {
		p->A[i][j]=(p->Araw+i*row_width+j*mp_width);
	  }
   }
  return p;
}



int check_cache(i_p,j_p)
	 long *i_p,*j_p;
{

  cache_tries++;
  
  
  if (Qtail == Qhead) 
	{
	  TRACE("cache miss");
	  /* Q has only one element */
	  cache_misses++;
	  return 0;

	}
  else
	{
	  Qtail = Qtail->prev;
	  
	  selectpivot(i_p,j_p);
	  

	  A=Qtail->A;
	/*  *i_p = Qtail->i; 
	  *j_p = Qtail->j; */
	  

	  copy(det,Qtail->det);
	  TRACE("restoring dict");
	  return 1;
	}
}




void *xcalloc(n,s,l,f)
     int n,s;
     int l;
     char *f;
{
  void *tmp,*calloc();

  tmp=calloc(n,s);
  if (tmp==0) {
    char buf[200];

    sprintf(buf,"\n\nFatal error on line %d of %s",l,f);
    perror(buf);
    exit(1);
  }
  return tmp;
}




void alloc_memory(m,d)
	 int m,d;
{
  

  int j;
  dict_rec *p;
    
  p=new_dict_rec(m,d);
  if (!p){
    perror("\nlrs: Could not allocate starting dictionary");
    exit(1);
  }
  p->next=p;
  p->prev=p;
  Qhead=p;
  Qtail=p;
  
  A=p->A;
  
  
  dict_count=1;
  dict_limit=10;
  cache_tries=0;
  cache_misses=0;
  
  
  B=CALLOC((m+1),sizeof(long));
  C=CALLOC((d+1),sizeof(long));

  minratio=CALLOC((m+1),sizeof(long));
  inequality=CALLOC((m+1),sizeof(long));
  


  Lcm=CALLOC((m+1),sizeof(mp *));
  for (j=0; j<m+1; j++)
	Lcm[j]=CALLOC(1,sizeof(mp));

  Gcd=CALLOC((m+1),sizeof(mp *));
  for (j=0; j<m+1; j++)
	Gcd[j]=CALLOC(1,sizeof(mp));

  oD=CALLOC((d+1),sizeof(mp *));
  for (j=0; j<d+1; j++)
	oD[j]=CALLOC(1,sizeof(mp));
  
  saved_C=CALLOC(d+1,sizeof(long));

   LOC=CALLOC((d+m+2),sizeof(long));

}
 
void digits_overflow()
{
  printf("Overflow at digits=%d\n",DIG2DEC(digits));
  print_basis();
  exit(1);
}


/* 
   this routine makes a copy of the information needed to restart, 
   so that we can guarantee that if a signal is received, we 
   can guarantee that nobody is messing with it.
   This as opposed to adding all kinds of critical regions in 
   the main line code.

   It is also used to make sure that in case of overflow, we
   have a valid cobasis to restart from.
*/
 save_basis()
{
  int i;

#ifndef OMIT_SIGNALS
  sigset_t oset, blockset;
  sigemptyset(&blockset);
  sigaddset(&blockset,SIGTERM);
  sigaddset(&blockset,SIGHUP);
  sigaddset(&blockset,SIGUSR1);

  errcheck("sigprocmask",sigprocmask(SIG_BLOCK,&blockset,&oset));
#endif


  saved_flag=1;
  
  for (i=0; i<3; i++)
	saved_count[i]=count[i];
  
  for (i=0; i<d+1; i++) 
	saved_C[i]=C[i];

  copy(saved_det,det);

#ifndef OMIT_SIGNALS
  errcheck("sigprocmask",sigprocmask(SIG_SETMASK,&oset,0));
#endif
}

/* print out the saved copy of the basis */
print_basis()
{
  int i;

  if (saved_flag)
	{
	  
	  printf("\nV#%d R#%d B#%d h=%d facets ",saved_count[1],saved_count[0],saved_count[2],depth);
	  for(i=0;i<d;i++) printf("%d ",inequality[saved_C[i]-d]);
	  pmp(" det=",saved_det);
	  printf("\n");
	
  } else 	{
	printf("\nComputing initial basis\n");
  }
  fflush(stdout);  
  
}

#ifndef OMIT_SIGNALS

setup_signals()
{

  void die_gracefully();
  void checkpoint();
  void timecheck();
  
  
  errcheck("signal",signal(SIGTERM,die_gracefully));
  errcheck("signal",signal(SIGALRM,timecheck));
  errcheck("signal",signal(SIGHUP,die_gracefully));
  errcheck("signal",signal(SIGINT,die_gracefully));
  errcheck("signal",signal(SIGUSR1,checkpoint));
  alarm(CHECKPOINT_SECONDS);
}

void timecheck()
{
  /*print_basis();*/
  errcheck("signal",signal(SIGALRM,timecheck));
  alarm(CHECKPOINT_SECONDS);
}
  

void checkpoint()
{
  print_basis();
  errcheck("signal",signal(SIGUSR1,checkpoint));
}

void die_gracefully()
{
  print_basis();
  exit(1);
}  


#endif
/***************************************************************/
/*                                                             */
/*     Package of routines for rational arithmetic             */
/*     (Built on top of package for multiprecision arithmetic  */
/*     Not currently used, but may be useful                   */
/***************************************************************/


linrat(Na,Da,ka,Nb,Db,kb,Nc,Dc) /* computes Nc/Dc = ka*Na/Da  +kb* Nb/Db
                             and reduces answer by gcd(Nc,Dc) */
mp Na,Da,Nb,Db,Nc,Dc;
long ka,kb;
{
mp c;
mulint(Na,Db,Nc);
mulint(Da,Nb,c);
linint(Nc,ka,c,kb);  /* Nc = (ka*Na*Db)+(kb*Da*Nb)  */
mulint(Da,Db,Dc);  /* Dc =  Da*Db           */
reduce(Nc,Dc);
}


divrat(Na,Da,Nb,Db,Nc,Dc) /* computes Nc/Dc = (Na/Da)  / ( Nb/Db )
                             and reduces answer by gcd(Nc,Dc) */
mp Na,Da,Nb,Db,Nc,Dc;
{
mulint(Na,Db,Nc);
mulint(Da,Nb,Dc);
reduce(Nc,Dc);
}
 

mulrat(Na,Da,Nb,Db,Nc,Dc) /* computes Nc/Dc = Na/Da  * Nb/Db
                             and reduces answer by gcd(Nc,Dc) */
mp Na,Da,Nb,Db,Nc,Dc;
{
mulint(Na,Nb,Nc);
mulint(Da,Db,Dc);
reduce(Nc,Dc);
}

/***************************************************************/
/*                                                             */
/*     End package of routines for rational arithmetic         */
/*                                                             */
/***************************************************************/

#ifndef OMIT_TIMES
/* 
 * Not sure about the portability of this yet, 
 *		- db
 */
#include <sys/resource.h>
#define double_time(t) ((double)(t.tv_sec)+(double)(t.tv_usec)/1000000) 

void ptimes()
{
  struct rusage rusage;
  getrusage(RUSAGE_SELF,&rusage);
  fprintf(stdout,"\n* %0.3fu %0.3fs %ldKb %ld flts %ld swaps %ld blks-in %ld blks-out \n",
	  double_time(rusage.ru_utime),
	  double_time(rusage.ru_stime),
	  rusage.ru_maxrss,rusage.ru_majflt,rusage.ru_nswap,
	  rusage.ru_inblock,rusage.ru_oublock);

}

#endif

