/*
Copyright (c) 2000-2010, Dirk Krause
All rights reserved.

Redistribution and use in source and binary forms,
with or without modification, are permitted provided
that the following conditions are met:

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.
* Redistributions in binary form must reproduce the above 
  opyright notice, this list of conditions and the following
  disclaimer in the documentation and/or other materials
  provided with the distribution.
* Neither the name of the Dirk Krause nor the names of
  contributors may be used to endorse or promote
  products derived from this software without specific
  prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/



/**	@file	klammern.c	The klammern program.
*/



#include <stdio.h>

#include <dk.h>

#if DK_HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if DK_HAVE_STRING_H
#include <string.h>
#endif

#include <dk.h>
#include <dksf.h>

#include "dktools-version.h"




#line 63 "klammern.ctr"



/**	Maximum depth of brackets and comments.
*/
#define MAXDEPTH 1024


/**	Usage information text.
*/
static char *usageStr[] = {
  "klammern <filename>",
  "--------------------",
  "",
  "filename: Name of file to process.",
  "",
  "The program shows the bracket and comment level changes",
  "(opening and closing brackets) in your program.",
  "",
  "",
  NULL
};



/**	Print usage information.
*/
static void usage DK_P0()
{
  char **ptr;
  ptr = usageStr;
  while(*ptr) {
    printf("%s\n", *(ptr++));
  }
}




/**	Write one output line.
	@param	filename	Source file name.
	@param	lineno		Line number in source file.
	@param	line		Line segment to show.
	@param	comment		Comment level.
	@param	geschweift	Curly brackets level.
	@param	rund		Normal (round) brackets level.
	@param	eckig		Square brackets level.
	@param	x		Character which triggered this output.
	@param	startline	Line number of opening bracket or comment.
*/
static void output DK_P9(char *,filename, int,lineno, char *,line, int,comment, int,geschweift, int,rund, int,eckig, char,x, int,startline)
{

  int up = 0;

  printf("File %s:\n", filename);
  printf("%-8d", lineno);
  if(startline > 0) {
    printf(" / %-8d ", startline);
  } else {
    printf("            ");
  }
  printf("/*");
  if(x == '*') printf("+");
  else {
    if(x == '/') { printf("-"); up = 1; } else printf(" ");
  }
  printf("%3d*/ {", (comment + up));
  up = 0;
  if(x == '{') {
    printf("+");
  } else {
    if(x == '}') { printf("-"); up = 1; } else printf(" ");
  }
  printf("%3d} (", (geschweift + up));
  up = 0;
  if(x == '(') printf("+");
  else {
    if(x == ')') { printf("-"); up = 1; } else printf(" ");
  }
  printf("%3d) [", (rund + up));
  up = 0;
  if(x == '[') printf("+");
  else {
    if(x == ']') { printf("-"); up = 1; } else printf(" ");
  }
  printf("%3d] %s\n", (eckig + up), (line ? line : " "));
  fflush(stdout);
}



/**	Add a character to a line.
	@param	pointer	Existing line.
	@param	anz	Buffer size of pointer.
	@param	x	Character to add.
*/
static
void
addLine DK_P3(char *,pointer, int,anz, char,x)
{
  int i, j;

  i = strlen(pointer);
  if(i >= anz - 1) {
    for(j = 0; j < (anz - 1); j++) {
      pointer[j] = pointer[j+1];
    }
    pointer[anz-2] = x;
    pointer[anz-1] = '\0';
  } else {
    pointer[i] = x; pointer[i+1] = '\0';
  }
}



/**	Current state of the internal state machine.
*/
static int current_state = 0;


/**	Flag: Is in comment.
*/
static int comment = 0;



/**	Get state machine reaction for input character.
	@param	c	Character to process.
	@return	State machine output to indicate how to handle character.
*/
static
int
get_reaction DK_P1(int,c)
{
  int back = 0;
  int newstate;
  
  newstate = 0;
  switch(current_state) {
    case 0: {
      newstate = back = 0;
      switch(c) {
        case '\\': newstate = 4; back = 0; break;
        case '(':
        case ')':
        case '{':
        case '}':
        case '[':
        case ']':  newstate = 0; back = 2; break;
        case '/':  newstate = 1; back = 0; break;
        case '*':  newstate = 3; back = 0; break;
        case '"':  if(comment == 0) { newstate = 5; back = 0; } break;
        case '\'': if(comment == 0) { newstate = 7; back = 0; } break;
      }
    } break;
    case 1: {
      newstate = back = 0;
      switch(c) {
        case '*':  newstate = 0; back = 3; break;
        case '/':  newstate = 2; back = 0; break;
        case '(':
        case ')':
        case '{':
        case '}':
        case '[':
        case ']':  newstate = 0; back = 2; break;
      }
    } break;
    case 2: {
      newstate = 2; back = 0;
      if(c == '\n') { newstate = 0; }
    } break;
    case 3: {
      newstate = back = 0;
      switch(c) {
        case '*':  newstate = 3; back = 0; break;
        case '/':  newstate = 0; back = 4; break;
        case '(':
        case ')':
        case '{':
        case '}':
        case '[':
        case ']':  newstate = 0; back = 2; break;
      }
    } break;
    case 4: {
      newstate = back = 0;
    } break;
    case 5: {
      newstate = 5; back = 0;
      switch(c) {
        case '\\': newstate = 6; back = 0; break;
        case '"' : newstate = 0; back = 0; break;
      }
    } break;
    case 6: {
      newstate = 5; back = 0;
    } break;
    case 7: {
      newstate = 8; back = 0;
      if(c == '\\') { newstate = 9; back = 0; }
    } break;
    case 8: {
      newstate = 8; back = 0;
      switch(c) {
        case '\'': newstate = back = 0; break;
        case '\\': newstate = 9; back = 0; break;
      }
    } break;
    case 9: {
      newstate = 8; back = 0;
    } break;
  }
  current_state = newstate;
  return back;
}

/*
static int rules[] = {
  -1, -1,  0,  0,
   0, -1,  0,  0,
   0, '\\', 4, 0,
   0, '(', 0, 2,
   0, ')', 0, 2,
   0, '{', 0, 2,
   0, '}', 0, 2,
   0, '[', 0, 2,
   0, ']', 0, 2,
   0, '/', 1, 0,
   0, '*', 3, 0,
   0, '"', 5, 0,
   0, '\'', 7, 0,

   3, -1, 0, 0,
   3, '*', 3, 0,
   3, '/', 0, 4,
   3, '(', 0, 2,
   3, ')', 0, 2,
   3, '{', 0, 2,
   3, '}', 0, 2,
   3, '[', 0, 2,
   3, ']', 0, 2,

   1, -1, 0, 0,
   1, '*', 0, 3,
   1, '/', 2, 0,
   1, '(', 0, 2,
   1, ')', 0, 2,
   1, '{', 0, 2,
   1, '}', 0, 2,
   1, '[', 0, 2,
   1, ']', 0, 2,

   2, -1, 2, 0,
   2, '\n', 0, 0,

   4, -1, 0, 0,

   5, -1, 5, 0,
   5, '\\', 6, 0,
   5, '"', 0, 0,

   6, -1, 5, 0,

   7, -1, 8, 0,
   7, '\\', 9, 0,

   8, -1, 8, 0,
   8, '\'', 0, 0,
   8, '\\', 9, 0,

   9, -1, 8, 0,
  -1, -1, -1, -1
};

*/




/**	Version number.
*/
static char the_version_number[] = { VERSNUMB };



/**	License conditions.
*/
static char *license_terms[] = {
"Redistribution and use in source and binary forms, with or without",
"modification, are permitted provided that the following conditions are met:",
"* Redistributions of source code must retain the above copyright notice, this",
"  list of conditions and the following disclaimer.",
"* Redistributions in binary form must reproduce the above copyright notice,",
"  this list of conditions and the following disclaimer in the documentation",
"  and/or other materials provided with the distribution.",
"* Neither the name of the Dirk Krause nor the names of other contributors may",
"  be used to endorse or promote products derived from this software without",
"  specific prior written permission.",
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"",
"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE",
"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE",
"ARE DISCLAIMED.",
"IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY",
"DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES",
"(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;",
"LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND",
"ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT",
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS",
"SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
NULL
};



/**	Check whether the program must run normally or print
	help/version.
	@param	argc	Number of command line arguments.
	@param	argv	Command line arguments array.
	@return	1=run normally, 0=help/version.
*/
static
int
must_run DK_P2(int,argc, char **,argv)
{
  int back = 1;
  int help_wanted = 0; int vers_wanted = 0;
  int i;
  char **cptr;

  for(i = 1; i < argc; i++) {
    if(strcmp(argv[i], "-h") == 0) {
      help_wanted = 1;
    }
    if(strcmp(argv[i], "--help") == 0) {
      help_wanted = 1;
    }
    if(strcmp(argv[i], "-v") == 0) {
      vers_wanted = 1;
    }
    if(strcmp(argv[i], "--version") == 0) {
      vers_wanted = 1;
    }
  }
  if(vers_wanted || help_wanted) {
    back = 0;
    if(vers_wanted) {
      printf(
        "\nklammern (part of the dktools collection, version %s)\n",
	the_version_number
      );
      printf("(C) 2000-2007 - Dipl.-Ing. Dirk Krause\n");
      printf("http://dktools.sourceforge.net/\n\n");
      cptr = license_terms;
      while(*cptr) {
        printf("%s\n", *(cptr++));
      }
    }
    if(help_wanted) {
      usage();
    }
  }
  return back;
}



/**	Line numbers for comments.
*/
static int commentx[MAXDEPTH];

/**	Line numbers for normal (round) brackets.
*/
static int rundx[MAXDEPTH];

/**	Line numbers for curly brackets.
*/
static int geschweiftx[MAXDEPTH];

/**	Line numbers for square brackets.
*/
static int eckigx[MAXDEPTH];



/**	The main() function of the klammern program.
	@param	argc	Number of command line arguments.
	@param	argv	Command line arguments array.
	@return	0 on success, any other value indicates an error.
*/
int main(int argc, char *argv[])
{
  int exval = 1;
  FILE *input;
  int ende;
  char line[80];

  char c;
  int lineno, rund, geschweift, eckig, r, startline;
  
#line 464 "klammern.ctr"

  if(must_run(argc,argv)) {
  line[0] = '\0';
  lineno = 1; rund = geschweift = eckig = comment = 0;
  if(argc == 2) {
    input = dksf_fopen(argv[1], "r");
    if(input) {
      ende = 0; exval = 1;
      current_state = 0;
      while(ende == 0) {
        c = fgetc(input);
        if(feof(input)) {
          ende = 1;
          output(argv[1], lineno, line, comment, geschweift, rund, eckig, ' ',
	    0
	  );
        } else {
          if(c == '\n') {
            line[0] = '\0';
            lineno++;
          } else {
            addLine(line, 20, c);
          } 
          r = get_reaction(c); 
	  startline = 0;
          switch(r) {
            case 2: {
              switch(c) {
                case '(': 
			  if(comment == 0) {
			  if(rund < MAXDEPTH) {
			    rundx[rund] = lineno;
			  }
			  rund++;
			  }
                          break;
                case ')': if(comment == 0) {
			  rund--;
			  if(rund < 0) {
			    rund = 0;
			    printf(
			      "File %s:\n%-8d: WARNING: TOO MANY CLOSING BRACKETS ``)''!\n",
			      argv[1], lineno
			    );
			  }
			  if(rund < MAXDEPTH) {
			    startline = rundx[rund];
			  }
			  }
                          break;
                case '{':
			  if(comment == 0) {
			  if(geschweift < MAXDEPTH) {
			    geschweiftx[geschweift] = lineno;
			  }
			  geschweift++;
			  }
                          break;
                case '}': if(comment == 0) {
			  geschweift--;
			  if(geschweift < 0) {
			    printf(
			      "File %s:\n%-8d: WARNING: TOO MANY CLOSING BRACKETS ``}''!\n",
			      argv[1], lineno
			    );
			    geschweift = 0;
			  }
			  if(geschweift < MAXDEPTH) {
			    startline = geschweiftx[geschweift];
			  }
			  }
                          break;
                case '[':
			  if(comment == 0) {
			  if(eckig < MAXDEPTH) {
			    eckigx[eckig] = lineno;
			  }
			  eckig++;
			  }
                          break;
                case ']': if(comment == 0) {
			  eckig--;
			  if(eckig < 0) {
			    printf(
			      "File %s:\n%-8d: WARNING: TOO MANY CLOSING BRACKETS ``]''!\n",
			      argv[1], lineno
			    );
			    eckig = 0;
			  }
			  if(eckig < MAXDEPTH) {
			    startline = eckigx[eckig];
			  }
			  }
                          break;
              }
	      if(comment == 0) {
              output(
		argv[1], lineno, line, comment, geschweift, rund, eckig, c,
		startline
	      );
	      }
            } break;
            case 3: {
	      if(comment < MAXDEPTH) {
		commentx[comment] = lineno;
	      }
              comment++;
              output(
		argv[1], lineno, line, comment, geschweift, rund, eckig, c, 0
	      );
            } break;
            case 4: {
              comment--;
	      if(comment < 0) {
		printf(
		  "File %s:\n%-8d: WARNING: TOO MANY CLOSING COMMENTS!\n",
		  argv[1], lineno
		);
	        comment = 0;
	      }
	      if(comment < MAXDEPTH) {
		startline = commentx[comment];
	      }
              output(
		argv[1], lineno, line, comment, geschweift, rund, eckig, c,
		startline
	      );
            } break;
          }
        }
      }
      fclose(input);
    } else {
      printf(
        "KLAMMERN:   ERROR   -   Failed to read file \"%s\"!\n",
        argv[1]
      );
      fflush(stdout);
    }
  } else {
    usage();
  }
  } else {
  }
  exval = ((exval == 0) ? 1 : 0);
  
#line 609 "klammern.ctr"

  exit(exval); return 0;
}


