/****************************************************************************
**
*F  CombiCollectWord( <sc>, <vv>, <w> )
**
**  If a stack overflow occurs, we simply stop and return false.
**
**  SC_PUSH_GEN( gen, exp )
**    push a generator <gen>  with exponent <exp> onto the stack.
**
**  SC_PUSH_WORD( word, exp )
**    push <word>  with global exponent <exp>  into the stack, the macro uses
**    <word> and <exp> only once.
**
**  SC_POP_WORD()
**    remove topmost word from stack
*/
#define libGAP_SC_PUSH_WORD( word, exp ) \
    if ( ++sp == max ) { \
        libGAP_TLS(libGAP_SC_MAX_STACK_SIZE) *= 2; \
        return -1; \
    } \
    *++nw = (void*)libGAP_DATA_WORD(word); \
    *++lw = *nw + (libGAP_INT_INTOBJ((((libGAP_Obj*)(*nw))[-1])) - 1); \
    *++pw = *nw; \
    *++ew = (**pw) & expm; \
    *++ge = exp

#define libGAP_SC_PUSH_GEN( gen, exp ) \
    if ( ++sp == max ) { \
        libGAP_TLS(libGAP_SC_MAX_STACK_SIZE) *= 2; \
        return -1; \
    } \
    *++nw = (void*)libGAP_DATA_WORD(gen); \
    *++lw = *nw; \
    *++pw = *nw; \
    *++ew = exp; \
    *++ge = 1

#define libGAP_SC_POP_WORD() \
    sp--;  nw--;  lw--;  pw--;  ew--;  ge--

/****************************************************************************
**
**  The following functions are  used to add  a word into the exponent vector
**  without collection.  There are three different cases that can occur:
**
**  Add   a word  into  the exponent  vector.   Here we   can  use the global
**  exponent.
**
**  Add  a commutator   into the exponent  vector.   In  this  case the first
**  generator in the conjugate has to be skipped.  Here we can use the global
**  exponent.
**
**  Add part  of a word  into the  exponent vector.   Here  we cannot use the
**  global exponent because the beginning of  the word might not commute with
**  the rest.
**/
static void libGAP_AddWordIntoExpVec( libGAP_Int *v, libGAP_UIntN *w, libGAP_Int e, 
                           libGAP_Int ebits, libGAP_UInt expm, 
                           libGAP_Int p, libGAP_Obj *pow, libGAP_Int lpow ) {

    libGAP_UIntN *    wend = w + (libGAP_INT_INTOBJ((((libGAP_Obj*)(w))[-1])) - 1);
    libGAP_Int        i;
    libGAP_Int        ex;

    for( ; w <= wend; w++ ) {
        i = ((*w) >> ebits) + 1; 
        v[ i ] += ((*w) & expm) * e;      /* overflow check necessary? */
        if ( p <= v[i] ) {
            ex = v[i] / p;
            v[i] -= ex * p;
            if ( i <= lpow && pow[i] && 0 < libGAP_NPAIRS_WORD(pow[i]) ) {
                libGAP_AddWordIntoExpVec( 
                    v, (libGAP_UIntN*)libGAP_DATA_WORD(pow[i]), ex,
                    ebits, expm, p, pow, lpow  );
            }
        }
    }
}

static void libGAP_AddCommIntoExpVec( libGAP_Int *v, libGAP_UIntN *w, libGAP_Int e, 
                           libGAP_Int ebits, libGAP_UInt expm, 
                           libGAP_Int p, libGAP_Obj *pow, libGAP_Int lpow ) {

    libGAP_UIntN *    wend = w + (libGAP_INT_INTOBJ((((libGAP_Obj*)(w))[-1])) - 1);
    libGAP_Int        i;
    libGAP_Int        ex;

    /* Skip the first generator because we need the commutator here.  */
    w++;
    for( ; w <= wend; w++ ) {
        i = ((*w) >> ebits) + 1; 
        v[ i ] += ((*w) & expm) * e;      /* overflow check necessary? */
        if ( p <= v[i] ) {
            ex = v[i] / p;
            v[i] -= ex * p;
            if ( i <= lpow && pow[i] && 0 < libGAP_NPAIRS_WORD(pow[i]) ) {
                libGAP_AddWordIntoExpVec( 
                    v, (libGAP_UIntN*)libGAP_DATA_WORD(pow[i]), ex,
                    ebits, expm, p, pow, lpow  );
            }
        }
    }
}

static void libGAP_AddPartIntoExpVec( libGAP_Int *v, libGAP_UIntN *w, libGAP_UIntN *wend,
                           libGAP_Int ebits, libGAP_UInt expm, 
                           libGAP_Int p, libGAP_Obj *pow, libGAP_Int lpow ) {

    libGAP_Int        i;
    libGAP_Int        ex;

    for( ; w <= wend; w++ ) {
        i = ((*w) >> ebits) + 1; 
        v[ i ] += ((*w) & expm);     /* overflow check necessary? */
        if ( p <= v[i] ) {
            ex = v[i] / p;
            v[i] -= ex * p;
            if ( i <= lpow && pow[i] && 0 < libGAP_NPAIRS_WORD(pow[i]) ) {
                libGAP_AddWordIntoExpVec( 
                    v, (libGAP_UIntN*)libGAP_DATA_WORD(pow[i]), ex,
                    ebits, expm, p, pow, lpow  );
            }
        }
    }
}

libGAP_Int libGAP_CombiCollectWord ( libGAP_Obj sc, libGAP_Obj vv, libGAP_Obj w )
{
    libGAP_Int         ebits;      /* number of bits in the exponent              */
    libGAP_UInt        expm;       /* unsigned exponent mask                      */
    libGAP_UInt        exps;       /* sign exponent mask                          */

    libGAP_Obj         vnw;        /* word stack                                  */
    libGAP_UIntN **    nw;         /* address of <vnw>                            */
    libGAP_Obj         vlw;        /* last syllable stack                         */
    libGAP_UIntN **    lw;         /* address of <vlw>                            */
    libGAP_Obj         vpw;        /* current syllable stack                      */
    libGAP_UIntN **    pw;         /* address of <vpw>                            */
    libGAP_Obj         vew;        /* unprocessed exponent stack                  */
    libGAP_UIntN *     ew;         /* address of <vew>                            */
    libGAP_Obj         vge;        /* global exponent stack                       */
    libGAP_Int *       ge;         /* address of <vge>                            */

    libGAP_Obj         vpow;       /* rhs of power relations                      */
    libGAP_Int         lpow;       /* length of <vpow>                            */
    libGAP_Obj *       pow;        /* address of <vpow>                           */

    libGAP_Obj         vcnj;       /* rhs of conjugate relations                  */
    libGAP_Int         lcnj;       /* length of <vcnj>                            */
    libGAP_Obj *       cnj;        /* address of <vcnj>                           */

    libGAP_Obj *       avc;        /* address of the avector                      */
    libGAP_Obj *       avc2;       /* address of the avector 2                    */
    libGAP_Obj *       wt;         /* address of the weights array                */
    libGAP_Obj *       gns;        /* address of the list of generators           */
    libGAP_Obj *       ro;         /* address of the list of relative orders      */
    libGAP_Obj *       inv;        /* address of the list of inverses             */

    libGAP_Int *       v;          /* address of <vv>                             */

    libGAP_Int         max;        /* maximal stack size                          */
    libGAP_Int         sp;         /* stack pointer                               */
    libGAP_Int         i, j;       /* loop variable                               */
    libGAP_Int         gn;         /* current generator number                    */
    libGAP_Int         ex;         /* current exponent                            */
    libGAP_Int         cl;         /* p-class of the collector                    */
    libGAP_Int         p;          /* the prime                                   */

    libGAP_Obj         tmp;        /* temporary obj for power                     */

    libGAP_Int         resized = 0;/* indicates whether a Resize() happened       */

    /* if <w> is the identity return now                                   */
    if ( libGAP_NPAIRS_WORD(w) == 0 ) {
        return libGAP_SC_NUMBER_RWS_GENERATORS(sc);
    }

    /* get the number of bits for exponents                                */
    ebits = libGAP_EBITS_WORDTYPE( libGAP_SC_DEFAULT_TYPE(sc) );

    /* get the exponent mask                                               */
    expm = (1UL << ebits) - 1;

    /* get the exponent sign masks                                         */
    exps = 1UL << (ebits-1);

    /* <nw> contains the stack of words to insert                          */
    vnw = libGAP_TLS(libGAP_SC_NW_STACK);

    /* <lw> contains the word end of the word in <nw>                      */
    vlw = libGAP_TLS(libGAP_SC_LW_STACK);

    /* <pw> contains the position of the word in <nw> to look at           */
    vpw = libGAP_TLS(libGAP_SC_PW_STACK);

    /* <ew> contains the unprocessed exponents at position <pw>            */
    vew = libGAP_TLS(libGAP_SC_EW_STACK);

    /* <ge> contains the global exponent of the word                       */
    vge = libGAP_TLS(libGAP_SC_GE_STACK);

    /* get the maximal stack size                                          */
    max = libGAP_TLS(libGAP_SC_MAX_STACK_SIZE);

    /* ensure that the stacks are large enough                             */
    if ( libGAP_SIZE_OBJ(vnw)/sizeof(libGAP_Obj) < max+1 ) {
        libGAP_ResizeBag( vnw, sizeof(libGAP_Obj)*(max+1) );
        libGAP_RetypeBag( vnw, libGAP_T_STRING );
        resized = 1;
    }
    if ( libGAP_SIZE_OBJ(vlw)/sizeof(libGAP_Obj) < max+1 ) {
        libGAP_ResizeBag( vlw, sizeof(libGAP_Obj)*(max+1) );
        libGAP_RetypeBag( vlw, libGAP_T_STRING );
        resized = 1;
    }
    if ( libGAP_SIZE_OBJ(vpw)/sizeof(libGAP_Obj) < max+1 ) {
        libGAP_ResizeBag( vpw, sizeof(libGAP_Obj)*(max+1) );
        libGAP_RetypeBag( vpw, libGAP_T_STRING );
        resized = 1;
    }
    if ( libGAP_SIZE_OBJ(vew)/sizeof(libGAP_Obj) < max+1 ) {
        libGAP_ResizeBag( vew, sizeof(libGAP_Obj)*(max+1) );
        libGAP_RetypeBag( vew, libGAP_T_STRING );
        resized = 1;
    }
    if ( libGAP_SIZE_OBJ(vge)/sizeof(libGAP_Obj) < max+1 ) {
        libGAP_ResizeBag( vge, sizeof(libGAP_Obj)*(max+1) );
        libGAP_RetypeBag( vge, libGAP_T_STRING );
        resized = 1;
    }
    if( resized ) return -1;

    /* from now on we use addresses instead of handles most of the time    */
    v  = (libGAP_Int*)libGAP_ADDR_OBJ(vv);
    nw = (libGAP_UIntN**)libGAP_ADDR_OBJ(vnw);
    lw = (libGAP_UIntN**)libGAP_ADDR_OBJ(vlw);
    pw = (libGAP_UIntN**)libGAP_ADDR_OBJ(vpw);
    ew = (libGAP_UIntN*)libGAP_ADDR_OBJ(vew);
    ge = (libGAP_Int*)libGAP_ADDR_OBJ(vge);

    /* conjugates, powers, order, generators, avector, inverses            */
    vpow = libGAP_SC_POWERS(sc);
    lpow = libGAP_LEN_PLIST(vpow);
    pow  = libGAP_ADDR_OBJ(vpow);

    vcnj = libGAP_SC_CONJUGATES(sc);
    lcnj = libGAP_LEN_PLIST(vcnj);
    (void) lcnj; /* please compiler -- lcnj not actually used */
    cnj  = libGAP_ADDR_OBJ(vcnj);

    avc = libGAP_ADDR_OBJ( libGAP_SC_AVECTOR(sc) );
    gns = libGAP_ADDR_OBJ( libGAP_SC_RWS_GENERATORS(sc) );

    cl   = libGAP_INT_INTOBJ( libGAP_SC_CLASS(sc) );
    wt   = libGAP_ADDR_OBJ( libGAP_SC_WEIGHTS(sc) );
    avc2 = libGAP_ADDR_OBJ( libGAP_SC_AVECTOR2(sc) );

    ro  = libGAP_ADDR_OBJ( libGAP_SC_RELATIVE_ORDERS(sc) );
    p   = libGAP_INT_INTOBJ(ro[1]);
    inv = libGAP_ADDR_OBJ( libGAP_SC_INVERSES(sc) );

    /* initialize the stack with <w>                                        */
    sp = 0;
    libGAP_SC_PUSH_WORD( w, 1 );

    /* run until the stack is empty                                        */
    while ( 0 < sp ) {

        /* if <ew> is negative use inverse                                 */
        if ( *ew & exps ) {
            gn = ((**pw) >> ebits) + 1;
            ex = ( *ew & (exps-1) ) - exps;
            *ew = 0;
            libGAP_SC_PUSH_WORD( inv[gn], -ex );
        }

        /* if <ew> is zero get next syllable                               */
        else if ( 0 == *ew ) {

            /* if <pw> has reached <lw> get next & reduce globale exponent */
            if ( *pw == *lw ) {

                /* if the globale exponent is greater one reduce it        */
                if ( 1 < *ge ) {
                    (*ge)--;
                    *pw = *nw;
                    *ew = (**pw) & expm;
                }

                /* otherwise get the next word from the stack              */
                else {
                    libGAP_SC_POP_WORD();

                }
            }

            /* otherwise set <ew> to exponent of next syllable             */
            else {
                (*pw)++;
                *ew = (**pw) & expm;
            }
        }

        /* now move the next generator/word to the correct position        */
        else {

            /* get generator number                                        */
            gn = ((**pw) >> ebits) + 1;

            /* collect a single generator on the stack                     */
            if( *lw == *nw && libGAP_INT_INTOBJ(avc[gn]) == gn ) {
              v[gn] += *ew * *ge;
              *ew = *ge = 0;
              if ( p <= v[gn] ) {
                ex = v[gn] / p;
                v[gn] -= ex * p;
                if ( gn <= lpow && pow[gn] && 0 < libGAP_NPAIRS_WORD(pow[gn]) ) {
                    libGAP_AddWordIntoExpVec( 
                      v, (libGAP_UIntN*)libGAP_DATA_WORD(pow[gn]), ex, 
                      ebits, expm, p, pow, lpow  );
                }
              }

              continue;
            }

            /* collect a whole word exponent pair                          */
            else if( sp > 1 && *pw == *nw && libGAP_INT_INTOBJ(avc[gn]) == gn ) {
              libGAP_AddWordIntoExpVec( 
                   v, *pw, *ge, ebits, expm, p, pow, lpow  );
              *pw = *lw;
              *ew = *ge = 0;

              continue;
            }

            /* collect the rest of a word                                  */
            else if( sp > 1 && libGAP_INT_INTOBJ(avc[gn]) == gn ) {
              libGAP_AddPartIntoExpVec( 
                   v, *pw, *lw, ebits, expm, p, pow, lpow  );
              *pw = *lw;
              *ew = 0;

              continue;
            }

            else if( sp > 1 && 3*libGAP_INT_INTOBJ(wt[gn]) > cl ) {
                /* Collect <gn>^<ew> without stacking commutators.  
                   This is step 6 in (Vaughan-Lee 1990).                   */
                i = libGAP_INT_INTOBJ(avc[gn]);
                for ( ;  gn < i;  i-- ) {
                    if ( v[i] && gn <= libGAP_LEN_PLIST(cnj[i]) ) {
                        tmp = libGAP_ELM_PLIST( cnj[i], gn );
                        if ( tmp != 0 && 0 < libGAP_NPAIRS_WORD(tmp) ) {
                            libGAP_AddCommIntoExpVec( 
                                v, (libGAP_UIntN*)libGAP_DATA_WORD(tmp), v[i] * (*ew),
                                ebits, expm, p, pow, lpow );
                        }
                    }
                }
                
                v[gn] += (*ew);
                (*ew) = 0;

                /* If the exponent is too big, we have to stack up the 
                   entries in the exponent vector.                         */
                if ( p <= v[gn] ) {
                    ex  = v[gn] / p;
                    v[gn] -= ex * p;
                    if ( gn <= lpow && pow[gn] && 0 < libGAP_NPAIRS_WORD(pow[gn]) ) {
                        /* stack the exponent vector first. */
                        i = libGAP_INT_INTOBJ(avc[gn]);
                        for ( ; gn < i;  i-- ) {
                            if ( v[i] ) {
                                libGAP_SC_PUSH_GEN( gns[i], v[i] );
                                v[i] = 0;
                            }
                        }
                        libGAP_AddWordIntoExpVec( 
                             v, (libGAP_UIntN*)libGAP_DATA_WORD(pow[i]), ex,
                             ebits, expm, p, pow, lpow  );
                    }
                }
            }
            /* we have to move <gn> step by step                           */
            else {
              
              (*ew)--;
              v[gn]++;

              i = libGAP_INT_INTOBJ(avc[gn]);
              if( sp > 1 ) {
                  /* Do combinatorial collection as far as possible.       */
                  j = libGAP_INT_INTOBJ(avc2[gn]);
                  for( ; j < i; i-- )
                      if( v[i] && gn <= libGAP_LEN_PLIST(cnj[i]) ) {
                          tmp = libGAP_ELM_PLIST( cnj[i], gn );
                          if ( tmp != 0 && 0 < libGAP_NPAIRS_WORD(tmp) )
                              libGAP_AddCommIntoExpVec( 
                                  v, (libGAP_UIntN*)libGAP_DATA_WORD(tmp), v[i],
                                  ebits, expm, p, pow, lpow );
                      }
              }

              /* Find the first position in v from where on ordinary
                 collection  has to be applied.                            */
              for( ; gn < i; i-- )
                  if( v[i] && gn <= libGAP_LEN_PLIST(cnj[i]) ) {
                      tmp = libGAP_ELM_PLIST( cnj[i], gn );
                      if ( tmp != 0 && 0 < libGAP_NPAIRS_WORD(tmp) )
                        break;
                  }

              /* Stack up this part of v if we run through the next 
                 for-loop or if a power relation will be applied           */ 
              if( gn < i || (p <= v[gn] &&
                  gn <= lpow && pow[gn] && 0 < libGAP_NPAIRS_WORD(pow[gn])) ) {
                j = libGAP_INT_INTOBJ(avc[gn]);
                for( ; i < j; j-- )
                  if( v[j] ) {
                    libGAP_SC_PUSH_GEN( gns[j], v[j] );
                    v[j] = 0;
                  }
              }

                /* We finish with ordinary collection from the left        */
                for ( ;  gn < i;  i-- ) {
                    if ( v[i] ) {
                      if ( libGAP_LEN_PLIST(cnj[i]) < gn ) {
                        libGAP_SC_PUSH_GEN( gns[i], v[i] );
                      }
                      else {
                        tmp = libGAP_ELM_PLIST( cnj[i], gn );
                        if ( tmp == 0 || libGAP_NPAIRS_WORD(tmp) == 0 ) {
                          libGAP_SC_PUSH_GEN( gns[i], v[i] );
                        }
                        else {
                          libGAP_SC_PUSH_WORD( tmp, v[i] );
                        }
                      }
                      v[i] = 0;
                    }
                }
            }

            /* check that the exponent is not too big                      */
            if ( p <= v[gn] ) {
                i = v[gn] / p;
                v[gn] -= i * p;
                if ( gn <= lpow && pow[gn] && 0 < libGAP_NPAIRS_WORD(pow[gn]) ) {
                    libGAP_SC_PUSH_WORD( pow[gn], i );
                }
            }
        }
    }
    return libGAP_SC_NUMBER_RWS_GENERATORS(sc);
}
#undef libGAP_SC_PUSH_WORD
#undef libGAP_SC_PUSH_GEN
#undef libGAP_SC_POP_WORD

#undef libGAP_AddWordIntoExpVec
#undef libGAP_AddCommIntoExpVec
#undef libGAP_AddPartIntoExpVec
#undef libGAP_CombiCollectWord
#undef libGAP_UIntN
