/***************************************************************************
* scan.c: scans input file, counts how many spaces will be needed for ex-  *
*         panding tab stops and linefeed codes, this count added to the    *
*         original file length is the number of bytes wfile needs to       *
*         malloc() for the write buffer                                    *
***************************************************************************/

/* ------------------------------- includes ----------------------------- */

#include <stdio.h>
#include "wfile.h"

/* ------------------------------- routines ----------------------------- */

/*##########################################################################
# scan(): reads input buffer and counts number of *NEEDED* bytes for the   #
#         output file, i.e. how many spaces will be needed for the tabs,   #
#         how many LFs (0x0d) have to be added to the CRs                  #
#         Actually one those options are taken into consideration that     #
#         would enlarge the write buffer (such as 'expand tabs to spaces'  #
#         or 'add linefeed codes). The result may not be precise but at    #
#         least it's more precise than the 'super malloc' in previos       #
#         versions.                                                        #
#                                                                          #
#   inputs: char *rbuf - pointer to the read buffer                        #
#           long len  - length of read buffer                              #
#           int Options - specified Options                                #
#           int tabsize - how many spaces will be needed for one tab       #
#   return: unsigned int count - number of bytes needed for write buffer   #
##########################################################################*/
unsigned int scan(register char *rbuf, long len, int Options, int tabsize)
{
  register unsigned int i;
  unsigned int count = 0;

  printf("scanning... ");
  fflush(stdout);
  for (i = 0; i < len; i++)
  {
    switch (rbuf[i])
    {
      case '\t':
        if (Options & EXPTABS)
          count += tabsize;
        else
          count++;
        break;
      case 0x0a:
        if (Options & ADDCR)
          count++;
        count++;
        break;
      default:
        count++;
    }
  }
  if (Options & ADD_FINAL_CHR)
    count++;
  return count;
}
