#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include "dbf.h"

#define CENTURY 1900
#define FILLER_DBT 508
#define HAS_MEMO 0x83
#define NO_MEMO 3

FIELD_REC field_rec;

main(int argc, char **argv) {
char *fnames[4];
char ftypes[4];
unsigned flens[4];
unsigned fdecs[4];

fnames[0]="polje1";
ftypes[0]='C';
flens[0]=4;

fnames[1]="polje2";
ftypes[1]='C';
flens[1]=4;

fnames[2]="polje3";
ftypes[2]='C';
flens[2]=4;

fnames[3]="polje4";
ftypes[3]='C';
flens[3]=4;

if(dbfcreate("ff.dbf", 4, fnames, ftypes, flens, fdecs))
   printf("Done ...\n");
else
   printf("Noo ...\n");

}

int dbfcreat(char *filename, unsigned num_fields, char **fnames, char ftypes[], unsigned flens[], unsigned fdecs[]) {
int dbf_handle, dbt_handle;
int i;
unsigned rec_size;

char *dbt_name;
char dbt_head;
char *dbt_data;

int is_memo;
DBF_HEAD dbf_head;
FIELD_REC field_rec;

is_memo=0;

if ((dbf_handle=open(argv[1], O_CREAT | O_TRUNC | O_RDWR | O_BINARY))<0) {
   printf("\nCan not open database file: '%s'\n", argv[1]);
   exit(0);
   }

if (read(handle, (char*)&dbf_head, sizeof(dbf_head))!=sizeof(DBF_HEAD)) {
   printf("\nError: Short file ... header dammaged!\n");
   exit(0);   
   }
printf("Database:      %s\n", argv[1]);
printf("DBF ID:        %d\n", dbf_head.dbf_id);
printf("Last update:   %d %d %d\n", dbf_head.last_update[0], dbf_head.last_update[1], dbf_head.last_update[2]);
printf("Data position: %d\n", dbf_head.data_offset);
printf("Record size:   %d\n", dbf_head.rec_size);
printf("Record number: %1d\n", dbf_head.last_rec);

/* Record counter */
num_fields=0;
more_fields=1;

while(more_fields) {
   more_fields=(read(handle, (char*)&field_rec, sizeof(FIELD_REC))==sizeof(FIELD_REC));
   if (more_fields) {
      more_fields=(field_rec.field_name[0]!=0x0D);
      if (more_fields) {
         switch(field_rec.field_type) {
            case 'N':
               printf("%-11s %-4c %3d %3d\n", field_rec.field_name, field_rec.field_type, field_rec.len_info.num_size.len, field_rec.len_info.num_size.dec);
               break;
            default:
               printf("%-11s %-4c %3d\n", field_rec.field_name, field_rec.field_type, field_rec.len_info.char_len);
               break;
            }
         }
      }
   }


close(handle);

}
