//
// Copyright (c) 1999-2004 Darius Rad
//
// This file is part of the OpenOtto project.
//
// OpenOtto 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.
//

/// \file
/// \brief Packet manipulation routines
///
/// See SAE J1850, 7.4.1 (HS-3000, pp. 212-213) for checksum description.


#include <linux/types.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>

#include <otto/otto.h>
#include <otto/packet.h>
#include <otto/device.h>
#include <otto/control.h>


static const char _ID_[] __attribute__ ((unused)) =
"$Id: packet.c,v 1.2 2004/07/07 22:07:12 alpha Exp $";


static const unsigned char CRC_INIT = 0xff;
static const unsigned char CRC_POLY = 0x1c;
static const unsigned char CRC_VALID = 0xc4;


/// \brief  Calculate an 8 bit CRC.
///
/// \return Result of CRC on indicated byte.
static inline unsigned char
crc8(
  unsigned char reg,  /// Partial product register
  unsigned char data  /// Byte to accumulate CRC for
)
{
  int i;

  for( i = 0; i < 8; i++ )
  {
    reg = (reg << 1) ^ ( ((reg ^ data) & 0x80) ? CRC_POLY : 0 );
    data <<= 1;
  }

  return(reg);
}


/// \brief Calculate CRC for data buffer
static unsigned char
compute_crc(
  unsigned char *bytes,  /// Buffer to compute CRC for
  int length  /// Length of buffer
)
{
  unsigned char reg = CRC_INIT;

  while(length--)
  {
    crc8( reg, *bytes++ );
  }

  return(~reg);
}


int
otto_crc_calc(
  union otto_packet *pkt
)
{
  assert( pkt != NULL );
  assert( pkt->raw.length < OTTO_PACKET_LENGTH_MAX );

  unsigned char crc;

  crc = compute_crc( pkt->raw.data, pkt->raw.length );

  pkt->raw.data[pkt->raw.length] = crc;
  pkt->raw.length++;

  return(0);
}


int
otto_crc_valid(
  union otto_packet *pkt
)
{
  assert( pkt != NULL );
  assert( pkt->raw.length <= OTTO_PACKET_LENGTH_MAX );

  unsigned char crc;
  int ret;

  crc = compute_crc( pkt->raw.data, pkt->raw.length );

  if( pkt->raw.data[pkt->raw.length-1] == crc )
  {
    ret = 1;
  }
  else
  {
    ret = 0;
  }

  return(ret);
}


/// \todo rework without so many memcpys
int
otto_findpacket(
  union otto_packet *pkt,
  int *start,
  int *len
)
{
  assert( pkt != NULL );
  assert( start != NULL );
  assert( len != NULL );

  int ret = 0;
  union otto_packet cpkt;
  int st;
  int ln;

  for( st = 0; st < pkt->raw.length; st++ )
  {
    for( ln = 0; ln < pkt->raw.length - st; ln++ )
    {
      memcpy( cpkt.raw.data, &(pkt->raw.data[st]), ln );
      cpkt.raw.length = ln;

      ret = otto_crc_valid( &cpkt );
      if( ret )
      {
	*start = st;
	*len = ln;
	break;
      }
    }

    if( ret )
    {
      break;
    }
  }

  return(ret);
}
