/*
 *  split.cpp written by burunduk3 (Oleg Davydov)
 *  created at: 38-223 (2008-08-11) 21:27 UTC
 *  It splits all files given by command line parameter into tests using blank lines as test separators.
 *  Block of blank lines is processed with following: all but last lines are appended to previous test.
 *  Remember: line consist of only space characters is NOT a blank line!
 *  First line of test is comment and will be copied into tests.description file, not in test itself.
 *  tests: 01 02 03 etc
 *  changelog:
 *    [39-301 (2009-10-29) 17:03 UTC] Test comment support. Use with caution!
 */

#include <cstdio>
#include <cstdlib>

int counter = 1;
FILE* descFile;

bool firstLine;

FILE* openNextOutput()
{
  firstLine = true;
  char fileName[200];
  fprintf(descFile, "[%02d] ", counter);
  sprintf(fileName, "%02d", counter++);
  FILE *file = fopen(fileName, "wt");
  if (file == NULL)
  {
    perror(fileName);
    return NULL;
  }
  return file;
}

void splitFile( char *fileName )
{
  FILE *input = fopen(fileName, "rt");
  FILE *output = NULL;
  if (input == NULL)
    return perror(fileName);
  int c;
  bool startLine = true, endTest = false;
  firstLine = false;
  while ((c = fgetc(input)) != -1)
  {
    if (c != '\n')
    {
      if (endTest && output != NULL)
        fclose(output), output = NULL, endTest = false;
      if (output == NULL && (output = openNextOutput()) == NULL)
        return;
      if (firstLine)
        fputc(c, descFile);
      else
        fputc(c, output);
      startLine = false;
    }
    else if (startLine)
    {
      if (endTest)
        fputc(c, output);
      endTest = true;
    }
    else
    {
      if (firstLine)
        fputc(c, descFile);
      else
        fputc(c, output);
      firstLine = false;
      startLine = true;
    }
  }
  if (output != NULL)
    fclose(output);
  fclose(input);
}

int main( int argc, char *argv[] )
{
  descFile = fopen("tests.description", "wt");
  for (int i = 1; i < argc; i++)
//    if (argv[i][0] == '-')
//      splitFile(stdin);
//    else
      splitFile(argv[i]);
  fclose(descFile);
  return 0;
}
