/*

Copyright (c) 2009-2010 Thomas Dennis.

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "csv.h"

/* Copy data from a text buffer into a cell. */

void csvCopyData( char qchr, CsvTable *csv,  long x, long y,
                  const unsigned char *data, long a, long b )
{

  long i, k, quote;

  /* Validate parameters. */

  if      (!csv || !data || x < 0 || y < 0 )    { return; }
  else if (x >= csv->width || y >= csv->height) { return; }
  else if (csv->cell[x][y])                     { return; }

  /* Allocate memory. */

  csv->cell[x][y] = (char*) malloc( (b-a)+1 );

  if( !csv->cell[x][y] ) { return; }

  /* Copy data. */

  k     = 0;
  quote = 0;

  for( i = 0; i < b-a; i++ )
  {

    /* Ignore quotes (unless they are "escaped" by being doubled as "" = "). */

    if( data[ a+i ] == qchr ) { quote++; } else { quote = 0; }

    if( !(data[ a+i ] == qchr && quote % 2 == 1) )
    {

      csv->cell[x][y][k] = data[ a+i ];

      k++;

    }

  }

  /* Add a NULL terminator. */

  csv->cell[x][y][k] = 0;

}

/* Create a table from a CSV file. */

CsvTable *csvLoadBuffer( long len, const unsigned char *data,
                          char cend, char qchr )
{

  CsvTable *csv = NULL;
  long i, j, w, max_w, h, quote, pass;
  unsigned char c, old_c;

  /* Validate buffer. */

  if( len < 1 || !data ) { return NULL; }

  /* Determine the size of the CSV table. */

  for( pass = 0; pass < 2; pass++ )
  {

    /* Initialise variables. */

    old_c = 0x0A;
    quote = 0;
    h     = 0;
    w     = 1 - pass;
    max_w = 1;
    j     = 0;

    /* Loop through every element of the buffer. */

    for( i = 0; i < len + 1; i++ )
    {

      /* Add an extra new-line on to the end of the file. */

      if( i == len ) { c = 0x0A; } else { c = data[i]; }

      /* Check for quote start and stop characters. */

      if( c == qchr ) { quote = !quote; }
      else if( !quote )
      {

        /* Check for column/row delimiters. */

        if( c == cend )
        {

          if( pass == 1 )
          {

            csvCopyData( qchr, csv, w, h, data, j, i );

            j = i + 1;

          }

          w++;

        }
        else if( c == 0x0D || c == 0x0A )
        {

          if( old_c != 0x0D && old_c != 0x0A )
          {

            if( pass == 1 )
            {

              csvCopyData( qchr, csv, w, h, data, j, i );

              j = i + 1;

            }

            if( w > max_w ) { max_w = w; }

            w = 1 - pass;
            h++;

          } else { j++; }

        }

      }

      /* Store the last character read. */

      old_c = c;

    }

    /* Allocate memory after the first pass, as the table size is now known. */

    if( pass == 0 )
    {

      csv = csvCreateTable( max_w, h );

      if( !csv ) { return NULL; }

    }

  }

  /* Return result. */

  return csv;

}

/* Load a table from a file. */

CsvTable *csvLoadFile( const char file_name[], char cend, char qchr )
{

  CsvTable *result   = NULL;
  FILE     *csv_file = NULL;
  long file_length;
  unsigned char *data = NULL;
  size_t len = 0;

  /* Attempt to open the specified file. */

  csv_file = fopen( file_name, "rb" );

  if( !csv_file ) { return NULL; }

  /* Get file length in bytes. */

  fseek( csv_file, 0, SEEK_END );
  file_length = (long) ftell( csv_file );
  rewind( csv_file );

  /* Copy file data. */

  data = (unsigned char*) malloc( file_length );

  if( data ) { len = fread( data, 1, file_length, csv_file ); }

  /* Close the file. */

  fclose( csv_file );

  /* Feed the data buffer to the csvLoadBuffer() function. */

  if( (long)len == (long)file_length )
  {

    result = csvLoadBuffer( file_length, data, cend, qchr );

  }

  /* Free the data buffer. */

  if( data ) { free( data ); }

  /* Return the result. */

  return result;

}
