/*********************************************************************

  d4ascii.c     (c)Copyright Sequiter Software Inc., 1990-1991.
  All rights reserved.

  Creates a database file from an ASCII file.

  NOTE: Make sure that the accompanying ascii file, 'INVENTOR.ASC' 
  is with this file when executing the program.

  *********************************************************************/

#include "d4all.h"

#ifdef __TURBOC__
extern unsigned  _stklen =  10000 ;  /* Borland only */
#endif

#define DESC_LEN      20
#define CODE_LEN      4
#define VALUE_LEN     6
#define QUANTITY_LEN  5

#define DESC_POS      0
#define CODE_POS      (DESC_POS + DESC_LEN)
#define VALUE_POS     (CODE_POS + CODE_LEN)
#define QUANTITY_POS  (VALUE_POS+ VALUE_LEN)

/* The carriage return and line feed characters are included. */

#ifdef S4UNIX
#define TOTAL_LEN     (QUANTITY_POS + QUANTITY_LEN + 1)
#else
#define TOTAL_LEN     (QUANTITY_POS + QUANTITY_LEN + 2)
#endif

CODE4   code_base ;
DATA4  *inventory ;
FIELD4 *descrip, *code, *value, *quantity ;

FILE4   ascii ;
FILE4SEQ_READ seq_read ;

char     ascii_buf[TOTAL_LEN], seq_read_buf[1024] ;

FIELD4INFO inventory_fields[] =
{
{ "CODE",     'C',  4, 0 },
{ "DESCRIP",  'C', 30, 0 },
{ "DATE",     'D',  8, 0 },
{ "VALUE",    'N',  8, 2 },
{ "QUANTITY", 'N',  6, 0 },
{ 0,0,0,0 }
} ;


void main()
{
  d4init( &code_base ) ;

  code_base.safety = 0 ;

  /* Create the data file; open the ASCII file.  */
  inventory = d4create( &code_base, "INVENTOR", inventory_fields,0);
  file4open( &ascii, &code_base, "inventor.asc", 0 ) ;
  e4exit_test( &code_base ) ;

  descrip  =  d4field( inventory, "DESCRIP" ) ;
  code     =  d4field( inventory, "CODE" ) ;
  value    =  d4field( inventory, "VALUE" ) ;
  quantity =  d4field( inventory, "QUANTITY" ) ;

  /* Initialize to read the ASCII file with extra fast performance. */

  file4seq_read_init( &seq_read, &ascii, 0, seq_read_buf,
                     sizeof(seq_read_buf) ) ;

  for(;;)
  {
    unsigned len_read ;

    /* Read one ASCII record. */
    len_read =  file4seq_read( &seq_read, ascii_buf, sizeof(ascii_buf) );

    if ( len_read != sizeof(ascii_buf) )  break ;

    /* Start the Append Operation */
    d4append_start( inventory, 0 ) ;

    /* Assign the fields. */
    f4assign_n( descrip, ascii_buf+DESC_POS, DESC_LEN ) ;
    f4assign_n( code,    ascii_buf+CODE_POS, CODE_LEN ) ;

    f4assign_double( value, c4atod( ascii_buf+VALUE_POS, VALUE_LEN) ) ;
    f4assign_double( quantity, c4atod( ascii_buf+QUANTITY_POS,
                                      QUANTITY_LEN) ) ;

    /* Append the new record */
    d4append( inventory ) ;
  }

  d4close(inventory) ;
  file4close( &ascii ) ;
  d4init_undo( &code_base ) ;
  mem4reset() ;

  exit(0) ;
}
