/* cleia - table.c
 *
 * Copyright (C) 2005 Sebastien Gonzalve
 *
 *   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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <errno.h>
#include <string.h>

int table[10][10] = {
  {0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C},
  {0x04, 0x03, 0x06, 0x05, 0x08, 0x07, 0x0A, 0x09, 0x0C, 0x0B},
  {0x05, 0x06, 0x03, 0x04, 0x09, 0x0A, 0x07, 0x08, 0x0D, 0x0E},
  {0x06, 0x05, 0x04, 0x03, 0x0A, 0x09, 0x08, 0x07, 0x0E, 0x0D},
  {0x07, 0x08, 0x09, 0x0A, 0x03, 0x04, 0x05, 0x06, 0x0F, 0x10},
  {0x08, 0x07, 0x0A, 0x09, 0x04, 0x03, 0x06, 0x05, 0x10, 0x0F},
  {0x09, 0x0A, 0x07, 0x08, 0x05, 0x06, 0x03, 0x04, 0x11, 0x12},
  {0x0A, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x12, 0x11},
  {0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x03, 0x04},
  {0x0C, 0x0B, 0x0E, 0x0D, 0x10, 0x0F, 0x12, 0x11, 0x04, 0x03}
};


static int get_voip_endpoint_name(const char *phone_num, const char *key,
				  char *voip_endpoint_name, size_t len)
{
  char *ptr;
  int i, nb=0;
  int num[10];
  int cle[10];
  if(!voip_endpoint_name || len < 21)
      return -EINVAL;

  for (i = 0; i < 10; i++)
    {
      num[i] = phone_num[9 - i] - '0';
    }

  for (i = 0; i < 10; i++)
    {
      cle[i] = key[9 - i] - '0';  /* FIXME if key is in hexa */
    }
  for (i = 0; i < 10; i++)
    {
      nb += sprintf(voip_endpoint_name + i * 2, "%02X",
	           (cle[i] ^ num[i]) + 3  );
    }

#if 0
  for (i = 0; i < 10; i++)
    {
      int j;
      for (j=0; j < 10; j++)
        {

          if ((i ^ j) + 3  != table[i][j])
            {
              printf("0x%02X != 0x%02X ", (i ^ j) + 3, table[i][j]  );
            }

        }
    }
  printf("\n");
  printf("\n");
#endif
  return nb;
}

int main(int argc, char **argv)
{
  int i, ji, retval;
  char result[21];

  if(argc != 3)
    {
      return -EINVAL;
    }

  if(strlen(argv[1]) != 10 || strlen(argv[2]) != 10)
    {
      return -EINVAL;
    }

  retval = get_voip_endpoint_name(argv[1], argv[2], result, sizeof(result));
  if (retval < 0)
    return -retval;
  return printf("%s\n", result);
}
