/*! \file ascii.c
    \brief ASCII and CSV output for xlhtml
*/

/*
   Copyright 2002  Charles N Wyble  <jackshck@thewybles.com>

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published  by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 */


#include "xlhtml.h"
#include "support.h"



void OutputPartialTableAscii(void)
{
	int i, j, k;

	SetupExtraction();

	/* Here's where we dump the Html Page out */
	for (i=first_sheet; i<=last_sheet; i++)	/* For each worksheet */
	{
		if (ws_array[i] == 0)
			continue;
		if ((ws_array[i]->biggest_row == -1)||(ws_array[i]->biggest_col == -1))
			continue;
		if (ws_array[i]->c_array == 0)
			continue;

		/* Now dump the table */
		for (j=ws_array[i]->first_row; j<=ws_array[i]->biggest_row; j++)
		{
			for (k=ws_array[i]->first_col; k<=ws_array[i]->biggest_col; k++)
			{
				int safe, numeric=0;
				cell *c = ws_array[i]->c_array[(j*ws_array[i]->max_cols)+k]; /* This stuff happens for each cell... */

				if (c)
				{
					numeric = IsCellNumeric(c);
					if (!numeric && Csv)
						printf("\"");
					safe = IsCellSafe(c);

					if (c->ustr.str)
					{
						if (safe)
							output_formatted_data(&(c->ustr), xf_array[c->xfmt]->fmt_idx, numeric, IsCellFormula(c));
						else
							OutputString(&(c->ustr));
					}
					else if (!Csv)
						printf(" ");	/* Empty cell... */
				}
				else
				{   	/* Empty cell... */
					if (!Csv)
						printf(" ");
					else
						printf("\"");
				}
				if (ws_array[i]->c_array[(j*ws_array[i]->max_cols)+k])	/* Honor Column spanning ? */
				{
					if (ws_array[i]->c_array[(j*ws_array[i]->max_cols)+k]->colspan != 0)
						k += ws_array[i]->c_array[(j*ws_array[i]->max_cols)+k]->colspan-1;
				}
				if (!numeric && Csv)
					printf("\"");

				if (Csv && (k < ws_array[i]->biggest_col))
				{	/* big cheat here: quoting everything! */
					putchar(',');	/* Csv Cell Separator */
				}
				else
				{
					if (( !Csv )&&( k != ws_array[i]->biggest_col ))
						putchar('\t');	/* Ascii Cell Separator */
				}
			}
			if (Csv)
				printf("\r\n");
			else
				putchar(0x0A);		/* Row Separator */
		}
		if (!Csv)
			printf("\n\n");		 	/* End of Table 2 LF-CR */
	}
}
