/*
* Filter multiple line feeds from text.
* Filter initial white space in a line.
* Hack: turn on and off with \001.
*
* Usage: lf [-b] [-c n] < in > out 
*  -b: turn on leading blank elimination
*  -c: allow n consecutive blank lines
*/
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include "ansi.h"

int main(int argc, char *argv[])
{
  int c;
  int non_white = 0;
  int iswhite;
  int verbatim = 0;
  int skip = 0;
  int remove_leading_blank = 0;
  int consecutive = 1;
  int count;
  extern char *optarg;

  while ((c = getopt(argc, argv, "bc:")) != -1) {
    switch(c) {
    case 'b':
      remove_leading_blank = 1;
      break;
    case 'c':
      consecutive = atoi(optarg);
      break;
    case '?':
      fprintf(stderr, "Unrecognized option: -%c\n", c);
      fprintf(stderr, "Usage: lf [-b]\n");
      exit(1);
      break;
    }
  }

  while ((c = getchar()) != EOF) {
    count = (c == '\n') ? count+1 : 0;
    iswhite = remove_leading_blank ? isspace(c) : (c == '\n') 
       && count >= consecutive;

    /* \001 enters and exits verbatim mode */
    if (c == 1) {
      verbatim = !verbatim;
    }
    /* \002 enters and exits skip mode */
    else if (c == 2) {
      skip = !skip;
    }
    else if (!skip && !verbatim && iswhite) {
      if (non_white) {
        putchar(c); 
        if (c == '\n') non_white = 0;
      }
    }
    else if (!skip) {
      non_white = 1;
      putchar(c);
    }
  }
  return 0;
}
