/*
  Copyright (c) 2007-2010 Stefan Kurtz <kurtz@zbh.uni-hamburg.de>
  Copyright (c)      2011 Sascha Steinbiss <steinbiss@zbh.uni-hamburg.de>
  Copyright (c) 2007-2011 Center for Bioinformatics, University of Hamburg

  Permission to use, copy, modify, and distribute this software for any
  purpose with or without fee is hereby granted, provided that the above
  copyright notice and this permission notice appear in all copies.

  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

static void GT_APPENDINT(allocSWtables)(GT_APPENDINT(GtSWtable) *swtable)
{
  swtable->positions = gt_malloc(sizeof (*swtable->positions) *
                                 swtable->numofpositionstostore);
  swtable->rangelengths = gt_malloc(sizeof(*swtable->rangelengths) *
                                    swtable->numofpositionstostore);
  swtable->endidxinpage = gt_malloc(sizeof(*swtable->endidxinpage) *
                                    swtable->numofpages);
}

static int GT_APPENDINT(fillSWtable)(GtEncseq *encseq,
                                     GtDustMasker *dust_masker,
                                     /* NULL if not used */
                                     Gtssptaboutinfo *ssptaboutinfo,
                                     GtSequenceBuffer *fb,
                                     GtError *err)
{
  GtUword fillwildcardrangeidx = 0, fillexceptionrangeidx = 0,
                mapposition = 0, currentposition, pagenumber = 0,
                exceptionpagenumber = 0, wildcardnextcheckpos,
                exceptionnextcheckpos = 0, widthbuffer = 0,
                lastwildcardrangelength = 0,
                lastexceptionrangelength = 0;
  int retval;
  GtUchar cc;
  char orig;
  GT_APPENDINT(GtSWtable) *wildcardrangetable
    = &(GT_APPENDINT(encseq->wildcardrangetable.st));
  GtSWtable_uint32 *exceptiontable = &(encseq->exceptiontable.st_uint32);
#ifndef NDEBUG
  GtUword sumwildcardranges = 0, countwildcards = 0;
#endif
  GtTwobitencoding *twobitencodingptr, bitwise = 0;

  encseq->unitsoftwobitencoding
    = gt_unitsoftwobitencoding(encseq->totallength);
  encseq->twobitencoding = gt_malloc(sizeof (*(encseq->twobitencoding)) *
                                     encseq->unitsoftwobitencoding);
  encseq->twobitencoding[encseq->unitsoftwobitencoding-1] = 0;
  twobitencodingptr = encseq->twobitencoding;

  GT_APPENDINT(allocSWtables)(wildcardrangetable);
  if (encseq->has_exceptiontable) {
    exceptiontable->positions = gt_malloc(sizeof (*exceptiontable->positions) *
                                         exceptiontable->numofpositionstostore);
    exceptiontable->rangelengths =
                               gt_malloc(sizeof(*exceptiontable->rangelengths) *
                                         exceptiontable->numofpositionstostore);
    exceptiontable->endidxinpage =
                               gt_malloc(sizeof(*exceptiontable->endidxinpage) *
                                         exceptiontable->numofpages);
    exceptiontable->mappositions =
                              gt_malloc(sizeof (*exceptiontable->mappositions) *
                                        exceptiontable->numofpositionstostore);
    exceptionnextcheckpos = exceptiontable->maxrangevalue;
  }
  wildcardnextcheckpos = wildcardrangetable->maxrangevalue;
  for (currentposition=0; /* Nothing */; currentposition++)
  {
    retval = gt_sequence_buffer_next_with_original(fb,dust_masker,&cc,
                                                   &orig,err);
    if (retval > 0)
    {
      if (encseq->has_exceptiontable && cc != (GtUchar) GT_SEPARATOR) {
        if (orig == encseq->maxchars[cc]) {
          if (lastexceptionrangelength > 0) {
            exceptiontable->rangelengths[fillexceptionrangeidx-1]
                           = (uint32_t) (lastexceptionrangelength-1);
            lastexceptionrangelength = 0;
          }
        } else {
          if (lastexceptionrangelength == 0)
          /* at beginning of exception range */
          {
            /* store remainder of currentposition: this value is not larger
               than maxrangevalue and this can be stored in a page */
            exceptiontable->positions[fillexceptionrangeidx++]
              = (uint32_t) (currentposition & exceptiontable->maxrangevalue);
            exceptiontable->mappositions[fillexceptionrangeidx-1]
              = mapposition;
            lastexceptionrangelength = 1UL;
          } else /* extend exception range */
          {
            if (lastexceptionrangelength == exceptiontable->maxrangevalue)
            {
              gt_assert(fillexceptionrangeidx > 0);
              exceptiontable->rangelengths[fillexceptionrangeidx-1]
                = (uint32_t) exceptiontable->maxrangevalue;
              lastexceptionrangelength = 0;
            } else
            {
              lastexceptionrangelength++;
            }
          }
          bitpackarray_store_uint32(encseq->exceptions,
                                   (BitOffset) (mapposition++),
                                   (uint32_t) encseq->subsymbolmap[(int) orig]);
        }
      }
      if (GT_ISNOTSPECIAL(cc))
      {
        if (lastwildcardrangelength > 0)
        {
          /* when seeing the first character after a wildcard range, process
             this and store the corresponding range length for the previous
             range */
          wildcardrangetable->rangelengths[fillwildcardrangeidx-1]
            = (GT_SPECIALTABLETYPE) (lastwildcardrangelength-1);
#ifndef NDEBUG
          sumwildcardranges += lastwildcardrangelength;
#endif
          lastwildcardrangelength = 0;
        }
      } else
      {
        if (cc == (GtUchar) GT_WILDCARD)
        {
#ifndef NDEBUG
          countwildcards++;
#endif
          if (lastwildcardrangelength == 0) /* at beginning of wildcard range */
          {
            /* store remainder of currentposition: this value is not larger
               than maxrangevalue and this can be stored in a page */
            wildcardrangetable->positions[fillwildcardrangeidx++]
              = (GT_SPECIALTABLETYPE) (currentposition &
                                       wildcardrangetable->maxrangevalue);
            lastwildcardrangelength = 1UL;
          } else /* extend wildcard range */
          {
            if (lastwildcardrangelength == wildcardrangetable->maxrangevalue)
                /* already at maximal length */
            {
              gt_assert(fillwildcardrangeidx > 0);
              wildcardrangetable->rangelengths[fillwildcardrangeidx-1]
                = (GT_SPECIALTABLETYPE) wildcardrangetable->maxrangevalue;
#ifndef NDEBUG
              sumwildcardranges
                += (1UL + wildcardrangetable->maxrangevalue);
#endif
              lastwildcardrangelength = 0;
            } else
            {
              lastwildcardrangelength++;
            }
          }
        } else
        {
          if (lastwildcardrangelength > 0)
          {
          /* when seeing the first character after a wildcard range, process
             this and store the corresponding range length for the previous
             range */
            wildcardrangetable->rangelengths[fillwildcardrangeidx-1]
              = (GT_SPECIALTABLETYPE) (lastwildcardrangelength-1);
#ifndef NDEBUG
            sumwildcardranges += lastwildcardrangelength;
#endif
            lastwildcardrangelength = 0;
          }
          ssptaboutinfo_processseppos(ssptaboutinfo,currentposition);
        }
      }
    } else
    { /* now retval <= 0 */
      if (retval == 0)
      {
        if (lastwildcardrangelength > 0)
        {
          /* note that we store one less than the length to prevent overflows */
          gt_assert(fillwildcardrangeidx > 0 &&
                    fillwildcardrangeidx <=
                    wildcardrangetable->numofpositionstostore);
          wildcardrangetable->rangelengths[fillwildcardrangeidx-1]
            = (GT_SPECIALTABLETYPE) (lastwildcardrangelength-1);
#ifndef NDEBUG
          sumwildcardranges += lastwildcardrangelength;
#endif
        }
        if (lastexceptionrangelength > 0)
        {
          /* note that we store one less than the length to prevent overflows */
          gt_assert(fillexceptionrangeidx > 0 &&
                    fillexceptionrangeidx <=
                    exceptiontable->numofpositionstostore);
          exceptiontable->rangelengths[fillexceptionrangeidx-1]
            = (uint32_t) (lastexceptionrangelength-1);
        }
        break;
      }
      gt_assert(retval < 0 && gt_error_is_set(err));
      return -1;
    }

    if (currentposition == wildcardnextcheckpos)
    {
      wildcardrangetable->endidxinpage[pagenumber] = fillwildcardrangeidx;
      pagenumber++;
      wildcardnextcheckpos += 1UL + wildcardrangetable->maxrangevalue;
    }
    if (encseq->has_exceptiontable) {
      if (currentposition == exceptionnextcheckpos)
      {
        exceptiontable->endidxinpage[exceptionpagenumber]
          = fillexceptionrangeidx;
        exceptionpagenumber++;
        exceptionnextcheckpos += 1UL + exceptiontable->maxrangevalue;
      }
    }

    ssptaboutinfo_processanyposition(ssptaboutinfo,currentposition);
    bitwise <<= 2;
    if (GT_ISNOTSPECIAL(cc))
    {
      bitwise |= (GtTwobitencoding) cc;
    } else
    {
      bitwise |= (GtTwobitencoding) encseq->leastprobablecharacter;
    }
    if (widthbuffer < (GtUword) (GT_UNITSIN2BITENC - 1))
    {
      widthbuffer++;
    } else
    {
      *twobitencodingptr++ = bitwise;
      widthbuffer = 0;
      bitwise = 0;
    }
  }
  UPDATESEQBUFFERFINAL(bitwise,twobitencodingptr);
  gt_assert(sumwildcardranges == countwildcards);
  while (pagenumber < wildcardrangetable->numofpages)
  {
    wildcardrangetable->endidxinpage[pagenumber] = fillwildcardrangeidx;
    pagenumber++;
  }
  if (encseq->has_exceptiontable) {
    while (exceptionpagenumber < exceptiontable->numofpages)
    {
      exceptiontable->endidxinpage[exceptionpagenumber] = fillexceptionrangeidx;
      exceptionpagenumber++;
    }
  }
  ssptaboutinfo_finalize(ssptaboutinfo);
  return 0;
}

static void GT_APPENDINT(gt_ssps_in_page_append)
                            (GtUword *arr,
                             const GT_APPENDINT(GtSWtable) *swtable,
                             GtUword offset,
                             GtUword first,
                             GtUword last)
{
  GtUword idx, *ptr;

  for (idx = first, ptr = arr; idx <= last; idx++, ptr++)
  {
    *ptr = offset + (GtUword) swtable->positions[idx];
  }
}

static GtUword *GT_APPENDINT(gt_all_ssps_get)(
                            const GT_APPENDINT(GtSWtable) *swtable)
{
  GtUword endpos0, endpos1, pgnum, offset = 0, *ssptab, *arr;

  if (swtable->numofpositionstostore == 0)
  {
    return NULL;
  }
  gt_assert(swtable->numofpages > 0 && swtable->endidxinpage != NULL);
  /* allocate one extra byte to allow inplace transformation into sequence
     length */
  ssptab = gt_malloc(sizeof *ssptab * (swtable->numofpositionstostore+1));
  arr = ssptab;
  for (pgnum=0; pgnum < swtable->numofpages; pgnum++)
  {
    if (pgnum == 0)
    {
      endpos0 = 0;
    } else
    {
      endpos0 = swtable->endidxinpage[pgnum-1];
    }
    endpos1 = swtable->endidxinpage[pgnum];
    if (endpos0 < endpos1)
    {
      GT_APPENDINT(gt_ssps_in_page_append)(arr,swtable,offset,endpos0,
                                           endpos1-1);
      arr += endpos1 - endpos0;
    }
    offset += 1UL + swtable->maxrangevalue;
  }
  return ssptab;
}

#ifdef GT_RANGEDEBUG

static void GT_APPENDINT(showSWtablewithpages)
                            (const GT_APPENDINT(GtSWtable) *swtable,
                             GtUword pgnum,
                             GtUword offset,
                             GtUword first,
                             GtUword last)
{
  GtUword idx, startpos;
  GtRange range;

  printf("page " GT_WU ": " GT_WU " elems at offset " GT_WU "\n",
          pgnum, last - first + 1, offset);
  for (idx=first; idx<=last; idx++)
  {
    startpos = (GtUword) swtable->positions[idx];
    range.start = offset + startpos;
    range.end = range.start + ((swtable->rangelengths == NULL)
                                ? 0
                                : swtable->rangelengths[idx]) + 1;
    showGtRange(&range);
    if (swtable->mappositions != NULL) {
      printf("\n");
      startpos = (GtUword) swtable->mappositions[idx];
      range.start = startpos;
      range.end = range.start + ((swtable->rangelengths == NULL)
                                  ? 0
                                  : swtable->rangelengths[idx]) + 1;
      printf("map: ");
      showGtRange(&range);
    }
    printf("\n");
  }
}

static void GT_APPENDINT(showallSWtablewithpages)(
                            const GT_APPENDINT(GtSWtable) *swtable)
{
  GtUword endpos0, endpos1, pgnum, offset = 0;

  gt_assert(swtable->numofpages > 0 && swtable->endidxinpage != NULL);
  for (pgnum=0; pgnum < swtable->numofpages; pgnum++)
  {
    if (pgnum == 0)
    {
      endpos0 = 0;
    } else
    {
      endpos0 = swtable->endidxinpage[pgnum-1];
    }
    endpos1 = swtable->endidxinpage[pgnum];
    if (endpos0 < endpos1)
    {
      GT_APPENDINT(showSWtablewithpages)(swtable,pgnum,offset,
                                         endpos0,endpos1-1);
    }
    offset += 1UL + swtable->maxrangevalue;
  }
}
#endif

/*@null@*/ static const GT_SPECIALTABLETYPE
                *GT_APPENDINT(binarysearchpreviousequal)(
                                           const GT_SPECIALTABLETYPE *leftptr,
                                           const GT_SPECIALTABLETYPE *rightptr,
                                           GT_SPECIALTABLETYPE pos)
{
  const GT_SPECIALTABLETYPE *midptr, *found = NULL;

  while (leftptr <= rightptr)
  {
    midptr = leftptr + GT_DIV2((GtUword) (rightptr-leftptr));
    if (pos < *midptr)
    {
      rightptr = midptr - 1;
    } else
    {
      found = midptr;
      if (pos > *midptr)
      {
        leftptr = midptr + 1;
      } else
      {
        break;
      }
    }
  }
  return found;
}

static bool GT_APPENDINT(checkspecialrange)(
                         const GT_APPENDINT(GtSWtable) *swtable,
                         GtUword *mappos,
                         GtUword pos)
{
  GtUword pagenumber = GT_POS2PAGENUM(pos);
  const GT_SPECIALTABLETYPE *found;

  gt_assert (swtable != NULL && swtable->endidxinpage != NULL);
  if (pagenumber == 0)
  {
    if (swtable->endidxinpage[0] >= 1UL)
    {
      gt_assert(swtable->endidxinpage[0] - 1 < swtable->numofpositionstostore);
      found = GT_APPENDINT(binarysearchpreviousequal)(
                        swtable->positions,
                        swtable->positions + swtable->endidxinpage[0] - 1,
                        (GT_SPECIALTABLETYPE) pos);
      if (found != NULL)
      {
        GtUword rangeend
          = 1UL + (GtUword) *found + swtable->rangelengths
                           [(GtUword) (found - swtable->positions)];
        if (swtable->mappositions != NULL) {
          GtUword rstart = GT_PAGENUM2OFFSET(pagenumber) + *found;
          gt_assert(mappos != NULL);
          *mappos = swtable->mappositions
                    [(GtUword) (found - swtable->positions)]
                    + pos - rstart;
        }
        if (pos < rangeend)
        {
          return true;
        }
      }
    }
  } else
  {
    if (swtable->endidxinpage[pagenumber-1] <
        swtable->endidxinpage[pagenumber])
    {
      gt_assert(swtable->endidxinpage[pagenumber] - 1 <
                swtable->numofpositionstostore);
      found = GT_APPENDINT(binarysearchpreviousequal)(
                        swtable->positions +
                        swtable->endidxinpage[pagenumber-1],
                        swtable->positions +
                        swtable->endidxinpage[pagenumber] - 1,
                        (GT_SPECIALTABLETYPE) pos);
      if (found != NULL)
      {
        GtUword rangeend, rstart;

        rstart = GT_PAGENUM2OFFSET(pagenumber) + *found;
        if (swtable->mappositions != NULL) {
          gt_assert(mappos != NULL);
          *mappos = swtable->mappositions
                    [(GtUword) (found - swtable->positions)]
                    + pos - rstart;
        }
        rangeend = rstart +
                   swtable->rangelengths
                   [(GtUword) (found - swtable->positions)] + 1;
        if (pos < rangeend)
        {
          return true;
        }
      }
    }
    if (pagenumber == 1UL)
    {
      if (swtable->endidxinpage[0] > 1UL)
      {
        GtUword idx, rangeend;

        idx = swtable->endidxinpage[0] - 1;
        rangeend = (GtUword) swtable->positions[idx] +
                   (GtUword) swtable->rangelengths[idx] + 1UL;
        if (pos < rangeend)
        {
          return true;
        }
      }
    } else
    {
      if (swtable->endidxinpage[pagenumber-2] <
          swtable->endidxinpage[pagenumber-1])
      {
        GtUword idx, rangeend;

        idx = swtable->endidxinpage[pagenumber-1] - 1;
        rangeend = GT_PAGENUM2OFFSET(pagenumber-1)
                   + swtable->positions[idx]
                   + swtable->rangelengths[idx]
                   + 1;
        if (pos < rangeend)
        {
          return true;
        }
      }
    }
  }
  return false;
}

static void GT_APPENDINT(determinerange)(GtRange *range,
                                         const GT_APPENDINT(GtSWtable)
                                           *swtable,
                                         GT_UNUSED GtUword transpagenum,
                                         GtUword cellnum)
{
  gt_assert(swtable->positions != NULL &&
            cellnum < swtable->numofpositionstostore);
  range->start = GT_PAGENUM2OFFSET(transpagenum) + swtable->positions[cellnum];
  range->end = (swtable->rangelengths != NULL)
                  ? range->start + swtable->rangelengths[cellnum] + 1
                  : range->start + 1;
  /*
  printf("new range [" GT_WU "," GT_WU "] for rangelength=%s,maxvalue=" GT_WU
         ",transpagenum=" GT_WU ",positions[cellnum=" GT_WU "]=" GT_WU "\n",
         range->start,range->end,
         swtable->rangelengths == NULL ? "NULL" : "not NULL",
         swtable->maxrangevalue,transpagenum,cellnum,
         (GtUword) swtable->positions[cellnum]);
  */
}

static void GT_APPENDINT(binpreparenextrangeGtEncseqReader)(
                                                GtEncseqReader *esr,
                                                KindofSWtable kindsw)
{
  GtUword endpos0, endpos1, cellnum, pagenum;
  bool found = false,
       moveforward = GT_ISDIRREVERSE(esr->readmode) ? false : true;
  GtRange range;
  GT_APPENDINT(GtSWtable) *swtable = NULL;
  GtEncseqReaderViatablesinfo *swstate = NULL;

  if (kindsw == SWtable_wildcardrange)
  {
    swtable = &(GT_APPENDINT(esr->encseq->wildcardrangetable.st));
    swstate = esr->wildcardrangestate;
  } else
  {
    swtable = &(GT_APPENDINT(esr->encseq->ssptab.st));
    swstate = esr->ssptabstate;
  }
  swstate->hasprevious = swstate->hascurrent = swstate->hasmore = false;
  swstate->exhausted = false;
  pagenum = GT_POS2PAGENUM(esr->currentpos);
  if (pagenum > 0)
  {
    endpos0 = swtable->endidxinpage[pagenum-1];
  } else
  {
    endpos0 = 0;
  }
  swstate->firstcell = endpos0;
  swstate->lastcell = endpos1 = swtable->endidxinpage[pagenum];
  if (esr->currentpos > 0)
  {
    while (endpos0  < endpos1)
    {
      cellnum = endpos0 + GT_DIV2(endpos1 - endpos0 - 1);
      GT_APPENDINT(determinerange)(&range,swtable,pagenum,cellnum);
#ifdef GT_RANGEDEBUG
      printf("%s: kindsw=%d: binsearch in [" GT_WU "," GT_WU "] => mid = "
             GT_WU " => ",
             __func__, (int) kindsw, endpos0, endpos1, cellnum);
      showGtRange(&range);
      printf("\n");
#endif
      if (moveforward)
      {
        if (esr->currentpos > range.end)
        {
          found = true;
          swstate->firstcell = cellnum;
          endpos0 = cellnum+1;
        } else
        {
          if (esr->currentpos >= range.start)
          {
            found = true;
            swstate->firstcell = cellnum;
            break;
          }
          endpos1 = cellnum;
        }
      } else
      {
        if (esr->currentpos < range.start)
        {
          found = true;
          swstate->lastcell = cellnum+1;
          endpos1 = cellnum;
        } else
        {
          if (esr->currentpos < range.end)
          {
            found = true;
            swstate->lastcell = cellnum+1;
            break;
          }
          endpos0 = cellnum+1;
        }
      }
    }
  } else
  {
    if (endpos0  < endpos1)
    {
      GT_APPENDINT(determinerange)(&range,swtable,pagenum,0);
      if (moveforward)
      {
        if (range.start == 0)
        {
          found = true;
          swstate->firstcell = 0;
        }
      } else
      {
        found = true;
        swstate->lastcell = 1UL;
      }
    }
  }
  if (moveforward && !found && pagenum > 0)
  {
    if (pagenum == 1UL)
    {
      endpos0 = 0;
    } else
    {
      endpos0 = swtable->endidxinpage[pagenum-2];
    }
    endpos1 = swtable->endidxinpage[pagenum-1];
    if (endpos0 < endpos1)
    {
      swstate->firstcell = endpos1-1;
      swstate->lastcell = endpos1;
      pagenum--;
      found = true;
    }
  }
#ifdef GT_RANGEDEBUG
  if (found)
  {
    GT_APPENDINT(determinerange)(&range,swtable,pagenum,
                                 moveforward
                                   ? swstate->firstcell
                                   : (swstate->lastcell-1));
    printf("%s: kindsw=%d,binary found pos " GT_WU " in ",
            __func__,(int) kindsw,esr->currentpos);
    showGtRange(&range);
    printf(" at cell " GT_WU " in page " GT_WU "\n",
           moveforward ? swstate->firstcell
                       : (swstate->lastcell-1),
           pagenum);
  } else
  {
    printf("no nearby interval found for startpos " GT_WU "\n",esr->currentpos);
  }
#endif
  if (found)
  {
    GT_APPENDINT(determinerange)(&swstate->previousrange,
                                 swtable,
                                 pagenum,
                                 moveforward
                                   ? swstate->firstcell
                                   : (swstate->lastcell-1));
#ifdef GT_RANGEDEBUG
    printf("%s: kindsw=%d,previousrange=",__func__,(int) kindsw);
    showGtRange(&swstate->previousrange);
    printf("\n");
#endif
    if (swstate->previousrange.start <= esr->currentpos &&
        esr->currentpos < swstate->previousrange.end)
    {
      swstate->hasprevious = true; /* only here hasprevious becomes true */
    }
    if (moveforward)
    {
      if (pagenum+1 < swtable->numofpages)
      {
        swstate->morepagesleft = true;
        swstate->nextpage = pagenum+1;
      } else
      {
        swstate->morepagesleft = false;
        swstate->nextpage = pagenum;
      }
    } else
    {
      if (pagenum > 0)
      {
        swstate->morepagesleft = true;
        swstate->nextpage = pagenum-1;
      } else
      {
        swstate->morepagesleft = false;
        swstate->nextpage = 0;
      }
    }
  } else
  {
    swstate->firstcell = swstate->lastcell = 0;
    if (pagenum < swtable->numofpages)
    {
      swstate->morepagesleft = true;
    } else
    {
      swstate->morepagesleft = false;
    }
    swstate->nextpage = pagenum;
  }
}

/*
   find next not empty page and set firstcell to the first index in the
   page and lastcell to the last plus 1 index of the page.
*/

static bool GT_APPENDINT(nextnonemptypage)(
                          GT_APPENDINT(GtSWtable) *swtable,
                          GtEncseqReaderViatablesinfo *swstate,
                          bool moveforward)
{
  GtUword endpos0, endpos1, pagenum;

  while (swstate->morepagesleft)
  {
    pagenum = swstate->nextpage;
    if (moveforward)
    {
      if (swstate->nextpage == swtable->numofpages-1)
      {
        swstate->morepagesleft = false;
      } else
      {
        swstate->nextpage++;
      }
    } else
    {
      if (swstate->nextpage == 0)
      {
        swstate->morepagesleft = false;
      } else
      {
        swstate->nextpage--;
      }
    }
    if (pagenum == 0)
    {
      endpos0 = 0;
    } else
    {
      endpos0 = swtable->endidxinpage[pagenum-1];
    }
    endpos1 = swtable->endidxinpage[pagenum];
    if (endpos0 < endpos1)
    {
      swstate->firstcell = endpos0;
      swstate->lastcell = endpos1;
      return true;
    }
  }
  return false;
}

static void GT_APPENDINT(advancerangeGtEncseqReader)(GtEncseqReader *esr,
                                                     KindofSWtable kindsw)
{
  GtUword cellnum;
  bool moveforward = GT_ISDIRREVERSE(esr->readmode) ? false : true;
  GT_APPENDINT(GtSWtable) *swtable = NULL;
  GtEncseqReaderViatablesinfo *swstate = NULL;

  if (kindsw == SWtable_wildcardrange)
  {
    swtable = &(GT_APPENDINT(esr->encseq->wildcardrangetable.st));
    swstate = esr->wildcardrangestate;
  } else
  {
    swtable = &(GT_APPENDINT(esr->encseq->ssptab.st));
    swstate = esr->ssptabstate;
  }
  gt_assert(swstate != NULL);
  while (true)
  {
    if (swstate->hascurrent)
    {
      swstate->previousrange = swstate->currentrange;
      swstate->hascurrent = false;
    }
    if (moveforward)
    {
      swstate->firstcell++;
    } else
    {
      swstate->lastcell--;
    }
#ifdef GT_RANGEDEBUG
    printf("%s: kindsw=%d, firstcell=" GT_WU ", lastcell=" GT_WU "\n",
            __func__,(int) kindsw,
            swstate->firstcell,swstate->lastcell);
#endif
    /* do not let comparison values become negative, hence compare with + 1 */
    if (swstate->firstcell + 1 <
        swstate->lastcell + 1 ||
        GT_APPENDINT(nextnonemptypage)(swtable,swstate,moveforward))
    {
      if (moveforward)
      {
        cellnum = swstate->firstcell;
      } else
      {
        cellnum = swstate->lastcell - 1;
      }
      GT_APPENDINT(determinerange)(&swstate->currentrange,
                                   swtable,
                                   swstate->morepagesleft
                                     ? (moveforward
                                         ? (swstate->nextpage-1)
                                         : (swstate->nextpage+1))
                                     : swstate->nextpage,
                                   cellnum);
      swstate->hasmore = true; /* only here hasmore becomes true */
    } else
    {
      swstate->hasmore = false; /* only here hasmore becomes false*/
      break;
    }
    if (swstate->hasprevious)
    {
      if (moveforward)
      {
        if (swstate->previousrange.end == swstate->currentrange.start)
        {
          swstate->previousrange.end = swstate->currentrange.end;
          swstate->hascurrent = false;
        } else
        {
          swstate->hascurrent = true;
          break;
        }
      } else
      {
        if (swstate->currentrange.end == swstate->previousrange.start)
        {
          swstate->previousrange.start = swstate->currentrange.start;
          swstate->hascurrent = false;
        } else
        {
          swstate->hascurrent = true;
          break;
        }
      }
    } else
    {
      swstate->previousrange = swstate->currentrange;
      swstate->hasprevious = true; /* only here hasprevious becomes true */
      swstate->hascurrent = false;
    }
  }
  gt_assert(swstate->hasprevious || !swstate->hasmore);
}

static bool GT_APPENDINT(checknextSW)(GtEncseqReader *esr,
                                      KindofSWtable kindsw)
{
  GtEncseqReaderViatablesinfo *swstate = assignSWstate(esr,kindsw);

#ifdef GT_RANGEDEBUG
  gt_assert(swstate != NULL);
  printf(" %s(kindsw=%d,pos=" GT_WU ",previous=(" GT_WU "," GT_WU "))\n",
         __func__, (int) kindsw,
         esr->currentpos,
         swstate->previousrange.start,
         swstate->previousrange.end);
#endif
  if (swstate->hasprevious)
  {
    if (!GT_ISDIRREVERSE(esr->readmode))
    {
      if (esr->currentpos >= swstate->previousrange.start)
      {
        if (esr->currentpos < swstate->previousrange.end)
        {
          return true;
        }
        if (swstate->hasmore)
        {
          advancerangeGtEncseqReader(esr,kindsw);
        }
      }
    } else
    {
      if (esr->currentpos < swstate->previousrange.end)
      {
        if (esr->currentpos >= swstate->previousrange.start)
        {
          return true;
        }
        if (swstate->hasmore)
        {
          advancerangeGtEncseqReader(esr,kindsw);
        }
      }
    }
  }
  return false;
}

static GtUchar GT_APPENDINT(seqdelivercharSpecial)(GtEncseqReader *esr)
{
  GtUchar cc = 0;
  bool defined = false;

  /* it is important that both calls of checknextSW are done to
     correctly maintain the corresponding swstates */

  if (esr->encseq->numofdbsequences > 1UL &&
      GT_APPENDINT(checknextSW)(esr,SWtable_ssptab))
  {
    cc = (GtUchar) GT_SEPARATOR;
    defined = true;
  }
  if (GT_APPENDINT(esr->encseq->wildcardrangetable.st).numofpositionstostore
      > 0 &&
      GT_APPENDINT(checknextSW)(esr,SWtable_wildcardrange))
  {
    gt_assert(!defined);
    cc = (GtUchar) GT_WILDCARD;
    defined = true;
  }
  if (defined)
  {
    return cc;
  }
  return (GtUchar) EXTRACTENCODEDCHAR(esr->encseq->twobitencoding,
                                      esr->currentpos);
}

static GtUword GT_APPENDINT(fwdgetnexttwobitencodingstopposSW)(
                                   GtEncseqReader *esr,KindofSWtable kindsw)
{
  GtEncseqReaderViatablesinfo *swstate = assignSWstate(esr,kindsw);

  gt_assert(esr != NULL && esr->encseq != NULL);
  gt_assert(!GT_ISDIRREVERSE(esr->readmode));
  while (swstate->hasprevious)
  {
    if (esr->currentpos >= swstate->previousrange.start)
    {
      if (esr->currentpos < swstate->previousrange.end)
      {
        return esr->currentpos; /* is in current special range */
      }
      /* follows current special range */
      if (swstate->hasmore)
      {
        GT_APPENDINT(advancerangeGtEncseqReader)(esr,kindsw);
      } else
      {
        break;
      }
    } else
    {
      return swstate->previousrange.start;
    }
  }
  return esr->encseq->totallength;
}

static GtUword GT_APPENDINT(revgetnexttwobitencodingstopposSW)(
                                      GtEncseqReader *esr,KindofSWtable kindsw)
{
  GtEncseqReaderViatablesinfo *swstate = assignSWstate(esr,kindsw);

  gt_assert(esr != NULL && esr->encseq != NULL);
  gt_assert(GT_ISDIRREVERSE(esr->readmode));
  while (swstate->hasprevious)
  {
    if (esr->currentpos < swstate->previousrange.end)
    {
      if (esr->currentpos >= swstate->previousrange.start)
      {
        return esr->currentpos+1; /* is in current special range */
      }
      /* follows current special range */
      if (swstate->hasmore)
      {
        GT_APPENDINT(advancerangeGtEncseqReader)(esr,kindsw);
      } else
      {
        break;
      }
    } else
    {
      return swstate->previousrange.end;
    }
  }
  return 0; /* virtual stop at -1 */
}
