// ----------------------------------------------------------------------------------------
//
//  common/util/bcdpacker.cpp
//    
//  Bob Cook Development, Robotics Library
//  http://www.bobcookdev.com/rl/
//    
//  This file provides functions to convert to or from BCD-like byte streams.
//
//  Copyright (C) 2007 Bob Cook
//
//      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., 
//      51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//
// ----------------------------------------------------------------------------------------


#include "bcdpacker.h"

#include "project_defs.h"


// ----------------------------------------------------------------------------------------

#if defined( BCDPACKER_INC_STRING )

static uint8_t convert_ascii_digit_to_packed( uint8_t digit )
{
    if ( ( digit >= '0' ) && ( digit <= '9' ) )
    {
        return digit - static_cast< uint8_t >( '0' );
    }
    else if ( digit == '.' )
    {
        return 0x0a;
    }
    
    return 0;
}

void bcdpack_number_string
    (
        const uint8_t* in,
        uint8_t        in_length,
        uint8_t*       out,
        uint8_t        out_max
    )
{
    *out = 0;

    for ( uint8_t i = 0; i < in_length; i++ )
    {
        *out |= convert_ascii_digit_to_packed( *in++ );

        if ( ( i & 0x01 ) == 0 )
        {
            *out <<= 4;
        }
        else
        {
            if ( --out_max == 0 )
            {
                return;
            }

            out++;
            *out = 0;
        }
    }
}

#endif


// ----------------------------------------------------------------------------------------

#if defined( BCDPACKER_INC_DOUBLE )

double unpack_number_to_double( const uint8_t* in, uint8_t length )
{
    // TODO
}

#endif


// ----------------------------------------------------------------------------------------
//  end of bcdpacker.cpp
// ----------------------------------------------------------------------------------------

