/* f4info_p.cpp (c)Copyright Sequiter Software Inc., 1989-1993.  All rights reserved. */

#include "d4all.h"
#ifndef S4UNIX
#ifdef __TURBOC__
#pragma hdrstop
#endif  /* __TUROBC__ */
#endif  /* S4UNIX */

#include "d4data.hpp"

Field4info::Field4info( Code4 &code )
{
  code_base = &code ;
  size = 0 ;
  length = 0 ;
  field = NULL ;
}

Field4info::Field4info( Data4 d )
{
  size = 0 ;
  length = 0 ;
  field = NULL ;
  code_base = (Code4 *) d.data->code_base ;
  add( d ) ;
}

int Field4info::add( Data4 d )
{
  int i ;
  for( i = 1 ; i <= d4num_fields( d.data) ; i++ )
  {
    FIELD4 * f ;
    f = d4field_j( d.data, i ) ;
    if( add( f4name( f ), f4type( f ), f4len( f ),  f4decimals(f) ) < 0 )
      return -1 ;
  }
  return 0 ;
}

Field4info::~Field4info()
{
  free( ) ;
}

void Field4info::free( )
{
  for( ; size > 0; )
    u4free( field[--size].name ) ;
  if( field )
  {
    u4free( field ) ;
    field = 0 ; size = 0 ; length = 0 ;
  }
}

int Field4info::add( char *name, char type, int len , int dec )
{
  Str4ten st_name( name ) ;
  st_name.upper( ) ;
  st_name.trim( ) ;
  if( u4alloc_again( code_base, (char**)&field, &length, (size+2)*sizeof(FIELD4INFO)) != 0 )
    return -1 ;

  if( (field[size].name = (char *) u4alloc_er( code_base, 11 )) == 0 )
    return -1 ;

  u4ncpy( field[size].name, st_name.ptr( ), 11) ;

  field[size].type = type ;
  field[size].len = len ;
  field[size].dec = dec ;

  size++ ;
  return 0 ;
}

int Field4info::add( Field4 fp )
{
  return add( fp.name(), fp.type(), fp.len(), fp.decimals() ) ;
}

int Field4info::del( char *name )
{
  Str4ten st_name( name ) ;
  st_name.upper() ;
  st_name.trim() ;
  for( int i = 0 ; i < size ; i++ )
  {
    if( memcmp( field[i].name, st_name.ptr(), st_name.len() ) == 0 )
    {
      del( i ) ;
      return 0 ;
    }
  }
  code_base->error( e4parm, "Field4info::del()", name ) ;
  return -1 ;
}

int Field4info::del( int index )
{
  if( index >= size || index < 0 )
  {
    code_base->error( e4parm ) ;
    return -1 ;
  }

  u4free( field[index].name ) ;
  memcpy( field+index, field+index+1, sizeof(FIELD4INFO) * (size-index) ) ;
  size-- ;
  return 0 ;
}
