/*
 * Copyright (c) 1987, 1992 The Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
 *
 * Fri Nov  7 18:42:12 JST 1997: convert from CSV to tab seperated table
 *				format to use with PostgreSQL by
 *				JuK(juk@rccm.co.jp).
 *
 * Fri Feb 15 14:35:18 JST 2002: add number of fields specification option.
 *				JuK(juk@rccm.co.jp).
 */

#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef linux
#include <unistd.h>
#endif /* linux */

void usage __P((void));
void warn __P((const char *, ...));
char *fgetline __P((FILE *fp, int *len));

static char sept=',', new_sept='\t';
static char quot='"';
static char nulv[]="\\N";


char *fgetline(fp, len)
	FILE *fp;
	int *len;
{
	char *p;
	int c, maxlen = BUFSIZ;
	
	if ((p = malloc(maxlen)) == NULL) 
		return NULL;

	for (*len = 0; c = fgetc(fp), c != EOF && c != '\n'; (*len)++) {
		if (*len == maxlen-1) {
			maxlen *= 2;
			if ((p = realloc(p, maxlen)) == NULL)
				return NULL;
		}

		p[*len] = c;
	}
	p[*len] = '\0';
	return c != EOF || *len != 0 ? p : NULL;
}


int
main(argc, argv)
	int argc;
	char *argv[];
{
	register char *filename, *t;
	register char *p, *pe;
	register short pt;
	FILE *fp;
	size_t len;
	int ch, rval;
	int maxfld, nfld, nf; 

	while ((ch = getopt(argc, argv, "c:q:s:n:f:h?")) != EOF) {
		switch(ch) {
		case 'c':
		    sept=(char)*optarg;
		    break;
		case 's':
		    new_sept=(char)*optarg;
		    break;
		case 'q':
		    quot=(char)*optarg;
		    break;
		case 'n':
		    if (*optarg)
		      strcpy(nulv,optarg);
		    else
			fprintf(stderr, "No argument. using default for NULL value.\n");
		    break;
		case 'f':
		    maxfld=atoi(optarg);
		    break;
		case 'h':
		case '?':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	fp = stdin;
	filename = "stdin";
	rval = 0;
	do {
		if (*argv) {
			if ((fp = fopen(*argv, "r")) == NULL) {
				warn("%s: %s", *argv, strerror(errno));
				rval = 1;
				++argv;
				continue;
			}
			filename = *argv++;
		}
		while (p = fgetline(fp, &len)) {
			pe = p+len;
			pt = 0;
			nfld=0;
			for (t = p; t < pe ; t++) {
				if ( *t == quot ) {
					for (++t ; t < pe ; t++) { /* proccess bytes between quotes */
						if ( *t == quot ) { /* check if quote in field value? */
						    if (*(++t) != quot ) 
							break;
						}
						putchar(*t);
						pt++;
					}
					if (t==pe) break;
				}
				if ( *t == sept ) {
					if (nulv) /* check if NULL field? */
						if (!pt) {
							printf("%s",nulv);
							++pt;
						}
				  	/* break loop if field reatch max */
				  	++nfld;
					if (maxfld > 0) {
					  if (nfld >= maxfld)
				    		break;
					}
					putchar( new_sept );
					pt=0;
				} else {
					putchar(*t);
					pt++;
				}
			}
			if (nulv) /* check if NULL field? */
				if (!pt)
					printf("%s",nulv);
			free(p);
			/* fill the rest fields with nulls */
			if (maxfld > 0) {
			    for (nf = nfld+1; nf < maxfld; nf++) {
				putchar( new_sept );
				printf("%s",nulv);
			    }
			}
			putchar('\n');
		}
		if (ferror(fp)) {
			warn("%s: %s", filename, strerror(errno));
			rval = 1;
		}
		(void)fclose(fp);
	} while(*argv);
	exit(rval);
}

#if __STDC__
#include <stdarg.h>
#else
#include <varargs.h>
#endif

void
#if __STDC__
warn(const char *fmt, ...)
#else
warn(fmt, va_alist)
	char *fmt;
        va_dcl
#endif
{
	va_list ap;
#if __STDC__
	va_start(ap, fmt);
#else
	va_start(ap);
#endif
	(void)fprintf(stderr, "csvtopg: ");
	(void)vfprintf(stderr, fmt, ap);
	va_end(ap);
	(void)fprintf(stderr, "\n");
}

void
usage()
{
	(void)fprintf(stderr, "usage: csvtopg [-s <s>] [-c <c>] [-q <q>] [-n <n>] [-h] [file ...]\n");
	(void)fprintf(stderr, "        -s <s>: specify output Separator(default: tab code)\n");
	(void)fprintf(stderr, "        -c <c>: specify input separator(default: Comma ',')\n");
	(void)fprintf(stderr, "        -q <q>: specify Quote code(default: double quote '\"')\n");
	(void)fprintf(stderr, "        -n <n>: specify Null value character(default: ander bar '\\N')\n");
	(void)fprintf(stderr, "        -f <f>: specify number of fields\n");
	(void)fprintf(stderr, "        -h: show help\n");
	exit(1);
}
