/* Token.c
 *
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <string.h>

#include "input.h"


/* token.c */
int readline(FILE *fhandle, char *linebuf);
int make_tokens(char *cline, char **argvec);


int readline(FILE *fhandle, char *linebuf)
{
    int ch;
    int i = 0;

    if (fhandle == stdin)
   return get_input(linebuf, 512, 1);

    for (;;) {
   ch = fgetc(fhandle);
   if (ch == EOF) {
       if (i == 0)
      return -1;
       linebuf[i] = 0;
       return i;
   }
   else if (ch == '\n' || ch == '\r') {
       linebuf[i] = 0;
       return i;
   }
   else if (ch=='\t' || ch=='@') {
       linebuf[i++]=' ';
   }
   else
       linebuf[i++] = ch;
    }
}

int make_tokens(char *cline, char **argvec)
{
    int argc, src, dst, bs, quote;
    char *q;

    argc = 0;
    dst = src = 0;

    while (cline[src] == ' ' || cline[src] == '\t' || cline[src] == '\n')
   ++src;
    do {
   if (cline[src] == 0)
       q = NULL;
   else {
       q = cline + dst;
       bs = 0;
       quote = 0;
       for (;;) {
      if (cline[src] == '"') {
          while (bs >= 2) {
         cline[dst++] = '\\';
         bs -= 2;
          }
          if (bs & 1)
         cline[dst++] = '"';
          else
         quote = !quote;
          bs = 0;
      } else if (cline[src] == '\\')
          ++bs;
      else {
          while (bs != 0) {
         cline[dst++] = '\\';
         --bs;
          }
          if (cline[src] == 0 ||
         ((cline[src] == ' ' || cline[src] == '\t') && !quote))
         break;
          cline[dst++] = cline[src];
      }
      ++src;
       }
       while (cline[src] == ' ' || cline[src] == '\t'
         || cline[src] == '\n')
      ++src;
       cline[dst++] = 0;
   }
   argvec[argc++] = q;
    } while (q != NULL);

    return argc - 1;
}

