/*
 * scbus utils to switch card settings.
 *
 * Copyright (C) 2011 Otvos Attila oattila@onebithq.com
 *
 * This 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 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 MPlayer; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>

#include "config.h"
#include "util.h"

#ifdef __cplusplus
extern "C" {
#endif

unsigned char hex2dec(const unsigned char c) {
    if(c<'0')
        return 0;
    if(c<='9')
        return c-48;
    if(c<'A')
        return 0;
    if(c<='F')
        return c-55;
    if(c<'a')
        return 0;
    if(c>'f')
        return 0;
    return c-87;
}

int validdatasize(char Cmd) {
    switch(Cmd) {
    case 'S':
        return 3;
    case 'G':
        return 1;
    case 'Q':
        return 2;
    case 'L':
        return 6;
    case 'O':
        return 6;
    case 'D':
        return 2;
    case 'E':
        return 2;
    }
    return 0;
}

int process_line(char *line, unsigned char* dst, int len) {
    int i=0;
    int n=0;
    int d=0;
    int j;
    unsigned char Magic=0;
    unsigned char Cmd=0;
    unsigned char c;

    if(dst && len)
        memset(dst,0,len);
    for(j=0;j<strlen(line);j++) {
        c=line[j];
        if(!i)
            Magic=c;
        else if(i==1) {
            Cmd=c;
            if(dst && len)
                dst[0]=Cmd;
        } else {
            if(i&0x01) {
                d|=hex2dec(c);
                if(dst && n+1<len)
                    dst[n+1]=d;
                n++;
            } else {
                d=hex2dec(c)<<4;
            }
        }
        if(c=='\n')
            break;
        if(Magic=='*' || Magic=='#')
            i++;
    }
    if(n && n==validdatasize(Cmd))
        return 1;
    return 0;
}

int str2num(char *str) {
    char *tmp;

    if(strncasecmp(str,"0x",2))
        return atoi(str);
    str+=2;
    return strtoul(str,&tmp,16);
}

double getTime(void) {
  struct timeval tv;
  double ret;

  gettimeofday(&tv,NULL);
  ret=tv.tv_usec;
  ret/=1000000;
  ret+=tv.tv_sec;
  return ret;
}

#ifdef __cplusplus
};
#endif
