/*
    db_dump.c - Routines for reading dBase III files
    Copyright (c) 1995,96,2003,6  Martin Schulze <joey@infodrom.org>

    This file is part of the dbview package, a viewer for dBase II files.

    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, USA.
*/


/*
    Most of the code in this file comes from Greg Twaites anno 87. I
    only took the file and wrote a program around it. I enclude the
    whole header. I have obtained this file from a free software
    archive, namely nic.funet.fi.  It is supposed to be placed in the
    public domain.  Hence, adding GPL code around and distributinng
    the entire file under the GPL should be fine.

      ftp://nic.funet.fi/pub/msdos/languages/c/dbase.c
*/

/*
 * These functions are used to read dbase files.
 *
 * These functions are provided by Valour Software as a gift.
 *
 * The program is for test purposes only.  No warranty is expressed nor
 * implied. USE AT YOUR OWN RISK!
 *
 * Fri Jun 21 19:30:44 1996:  Martin Schulze <joey@infodrom.north.de>
 *	Fixed a bug which causes dbview to eat a character at the end
 *	of beginning of a line.  Thanks to Chris Childs
 *	<cchilds@arnold.pinc.com> for submitting a patch.
 *
 * Thu Sep 26 21:38:33 1996:  Martin Schulze <joey@infodrom.north.de>
 *	Modified on some places based on corrections from Vladimir
 *	Michl <Vladimir.Michl@upol.cz>
 *
 * Mon Sep 25 17:09:46 2006: Gergely Szasz <szaszg@hu.inter.net>
 *	Added --deleted|-D to display deleted records as well.
 *
 * Mon Oct 16 18:34:23 CEST 2006: Joey Schulze <joey@infodrom.org>
 *	Improved error handling.  Improved handling of differences between
 *	dBase III and dBase III+ files.
 *
 * Mon Nov 20 16:58:35 CET 2006: Joey Schulze <joey@infodrom.org>
 *	Adjusted type handling and proper casts.
 */
 
#include "db_dump.h"
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <malloc.h>
#include <ctype.h>
#include <string.h>
#include <endian.h>
#include <byteswap.h>
 
#define TRUE	1
#define FALSE	0

DBASE_HEAD  dbhead={0};
FLD_LIST    *db_fld_root=0;
char        *Buffer;
char        buf_work[255];
FILE        *dbfile;

/*----------------------------------------------------helpers------------*/
#if BYTE_ORDER == BIG_ENDIAN
size_t
db3_fread (void *ptr, size_t size, size_t nmemb, FILE *stream)
{
  size_t ret;
  size_t i;
  uint16_t *p = (uint16_t *) ptr;
  uint32_t *pp = (uint32_t *) ptr;

  ret = fread(ptr, size, nmemb, stream);

  switch (size)
    {
      case 2:
	for (i = 0; i < ret; i++)
	  p[i] = bswap_16(p[i]);
	break;
      case 4:
	for (i = 0; i < ret; i++)
	  pp[i] = bswap_32(pp[i]);
	break;
      default:
	break;
    }

  return ret;
}

#define fread db3_fread
#endif
 
/*------------------------------------------------------------code-------*/
int
db3_process(dbfn, flags, delim)
char    *dbfn;
int	flags;
char	delim;
{
    dbfile=fopen(dbfn,"r");
    if (dbfile == NULL) {
        printf("Unable to open file `%s'\n", dbfn);
	return FALSE;
    }
    if (db3_read_dic(flags)) {
      if ( ! (flags & DB_FL_OMIT))
        db3_print_recs(dbhead.count, flags, delim);
    }
  fclose(dbfile);
  return TRUE;
}
 

/******************************************************
                                        db3_rm_ld_spc()
This function removes leading space characters and
returns a new string;
******************************************************/

char *
db3_rm_ld_spc (var)
char	*var;
{
    static char rvar[257];	/* dBase fields can only
				 * be 256 byts long, max. 
				 */
    char *c;

    bzero (rvar, sizeof(rvar));
    for (c=var; isspace (*c); c++);
    strcpy(rvar, c);
    return rvar;
}

/******************************************************
                                        db3_rm_tr_spc()
This function removes trailing space characters and
returns a new string;
******************************************************/

char *
db3_rm_tr_spc (var)
char	*var;
{
    char *c=var;

    for (c+=strlen(var)-1; isspace (*c); c--);

    *(++c) = '\0';
    return var;
}

/******************************************************
                                         db3_cvt_fld()
This function is called with a valid db3 field
specifier. It will convert the fieldname into a
more friendly look.

This is done by tr '_' ' ' and tr [:upper:] [:lower:].
******************************************************/

void
db3_cvt_fld (fld)
DBASE_FIELD	*fld;
{
    uint8_t *c;
    uint8_t first;

    first = 1;
    for (c=fld->name; *c; c++)
	if (!first) {
	    if (isupper(*c))
		*c = tolower(*c);
	    else
		if (*c == '_')
		    { *c = ' '; first = 1; }
	    first = 0;
	}
	else
	    first = 0;
}


void
db3_read_head(dbh)
DBASE_HEAD *dbh;
{
  fread(&dbh->version, 1, 1, dbfile);
  fread(dbh->l_update, 1, 3, dbfile);
  fread(&dbh->count, 4, 1, dbfile);
  fread(&dbh->header, 2, 1, dbfile);
  fread(&dbh->lrecl, 2, 1, dbfile);
  fread(dbh->reserv, 1, 20, dbfile);
}

void
db3_read_field(fld)
DBASE_FIELD *fld;
{
  fread(fld->name, 1, 11, dbfile);
  fread(&fld->type, 1, 1, dbfile);
  /* "duh" believe me, it used to do just that before */
  fread(&fld->data_ptr, 4, 1, dbfile);
  fread(&fld->length, 1, 1, dbfile);
  fread(&fld->dec_point, 1, 1, dbfile);
  fread(fld->fill, 1, 14, dbfile);
}

/******************************************************
                                         db3_read_dic()
This function is called with a file name to
read to create a record type to support the
dbase file
******************************************************/
 
int
db3_read_dic(flags)
int	flags;
{
    int             fields;
    DBASE_FIELD     *fld;

    if(dbfile==NULL) {
        printf("open failed");
        return FALSE;
        }
    db3_read_head(&dbhead);
    if( !(dbhead.version==3 || dbhead.version==0x83) ) {
        printf ("Version %d not supported\n",dbhead.version);
	if(dbhead.version==0x8b ) {
	    printf ("dBase IV - partially known...\n");
	}
	return FALSE;
    }

    if (flags & DB_FL_INFO) {
	printf("File version  : %d\n",dbhead.version);
	printf("Last update   : %02d/%02d/%2d\n", dbhead.l_update[1],dbhead.l_update[2],dbhead.l_update[0]+1900);
	printf("Number of recs: %d\n",dbhead.count);
	printf("Header length : %d\n",dbhead.header);
	printf("Record length : %d\n",dbhead.lrecl);
    }

    Buffer=malloc(dbhead.lrecl);
 
    fields=(dbhead.header-1)/32-1;
    
    if (flags & DB_FL_DESCR) {
	printf("Field Name\tType\tLength\tDecimal Pos\n");
    }
    while(fields--) {
	fld=(DBASE_FIELD *)malloc(sizeof(DBASE_FIELD));
	if (!fld) {
	    printf ("Not enough memory\n");
	    return FALSE;
	}
	db3_read_field(fld);
	if (! (flags & DB_FL_RESERVE))
	    db3_cvt_fld (fld);
	if (flags & DB_FL_DESCR) {
	    printf("%-10s\t  %c\t  %3d\t  %3d\n", fld->name, fld->type,
		   fld->length,fld->dec_point);
	}
	stack_field(fld);
    }
    /* Jump to where the data starts */
    fseek(dbfile, dbhead.header, SEEK_SET);

    return TRUE;
}
 
/******************************************************
                                        db3_print_recs()
Read records and print the data
******************************************************/
 
void
db3_print_recs(cnt, flags, delim)
int     cnt;
int     flags;
char	delim;
{
    int     bytes;
 
    while(cnt) {
        bytes=fread(Buffer,1,dbhead.lrecl,dbfile);
        if(bytes!=dbhead.lrecl)
            break;
	/* Check if deleted == '*' */
	if(flags & DB_FL_DELETED || Buffer[0]==' ') {
            db3_print(flags, delim, Buffer[0]);
            cnt--;
            }
        }
    return;
}
 
 
/******************************************************
                                          db3_print()
Print a single record
******************************************************/
 
void
db3_print(flags, delim, deleted)
int	flags;
char	delim;
char    deleted;
{
    FLD_LIST    *temp;
 
    temp=db_fld_root;
    if ((flags & DB_FL_DELETED) && (flags & DB_FL_BROWSE))
      printf("%c%c", deleted, delim);

    while (temp) {
        memcpy(buf_work,temp->data,temp->fld->length);
        buf_work[temp->fld->length] = '\0';
	if (flags & DB_FL_BROWSE)
	  if (flags & DB_FL_TRIM)
            printf("%s%c",db3_rm_tr_spc(db3_rm_ld_spc(buf_work)), delim);
	  else
	    printf("%s%c",buf_work, delim);
	else
	    printf("%-11s: %s\n",temp->fld->name,db3_rm_tr_spc(db3_rm_ld_spc(buf_work)));
        temp=temp->next;
        }

    if ((flags & DB_FL_DELETED) && ((flags & DB_FL_BROWSE) == 0) &&  (deleted != ' '))
      printf("*Deleted*  : %c\n", deleted);

    printf("\n");
    return;
}
 
/******************************************************
                                         stack_field()
Add a field to the linked list of fields
******************************************************/
 
void
stack_field(fld)
DBASE_FIELD *fld;
{
    FLD_LIST    *list, *temp;
 
    list=(FLD_LIST *)calloc(1,sizeof(FLD_LIST));
    if (!list) {
        printf ("Not enough memory\n");
	return;
    }
    list->fld=fld;
    if(!db_fld_root) {
        list->data = (uint8_t *)Buffer+1;                   /*skip delete byte*/
        db_fld_root=list;
        return;
        }
    temp=db_fld_root;
    while(temp->next)
        temp=temp->next;
    temp->next=list;
    list->data=temp->data + temp->fld->length;
    return;
}
