/***************************************************************************
* File:     hexnetfunctions.c
*
*                                       Copyright (C) 2021 Axel Bergerhoff
****************************************************************************
* 
* This file 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 3 of the License, or
* (at your option) any later version.
* 
* hexnet 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, see <http://www.gnu.org/licenses/>.
*
****************************************************************************
* Changes:
*   (1) --- 
*
*/


#include "hexnet.h"


/******************************************************************************/
unsigned char convert(char thisbyte)
{
  unsigned char   myvalue;

  myvalue = thisbyte;

  myvalue -= 48;          // 0..9
  if (myvalue < 0)
    return 128;
  if (myvalue > 9)        // A..F
  {
    if (myvalue < 17)     // 0x3a .. 0x40 eliminate
      return 128;
    else
      myvalue -= 7;
  }
  if (myvalue > 15)       // a..f
    myvalue -= 32;
  if (myvalue > 15)       // if still not fitting
    return 128;
  return myvalue;
}

/******************************************************************************/
int inputwd(unsigned char *puffer, int maxnum)
{
  int       inchar = 0;
  int       cntr = 0;
  unsigned char      newchar, ergebnis;
  char      is2nd = 0;
  unsigned char      *pufferindex;

  pufferindex = puffer;

  while (inchar != '\n' && inchar != EOF)
  {
    inchar = getchar();
    newchar = (unsigned char)inchar;
    ergebnis = convert(newchar);

    if (inchar != '\n' && inchar != EOF && ergebnis < 128 && inchar < 128)
    {
      if (is2nd)
      {
        *pufferindex += ergebnis;
        pufferindex++;
        cntr++;
        if (cntr >= maxnum)
          return -1;
      }
      else
        *pufferindex = ergebnis * 16;

      is2nd ^= 1;     // toggle
    }
  }

  return cntr;
}



