/*
  oz263.c:   Functions for accessing the oz263 chip. Also,
             find and return the SiS96x i2c bus device for
             the digimatrix setpanel program, for both 2.4
             and 2.6 kernels.
  Copyright (c) 2005 Andrew Calkin <calkina@geexbox.org> and
                     Ben Potter <linux@bpuk.org>

  Based heavily on the codebase for the header given directly below,
  and the original setpanel.c code, written by Richard Taylor,
  Ben Potter and Cyril Lacoux.

  Original header:
    i2cbusses: Print the installed i2c busses for both 2.4 and 2.6 kernels.
               Part of user-space programs to access for I2C
               devices.
    Copyright (c) 1999-2003  Frodo Looijaard <frodol@dds.nl> and
                             Mark D. Studebaker <mdsxyz123@yahoo.com>

    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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <string.h>
#include <stdio.h>
#include <limits.h>
#include <dirent.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include "digitools.h"
#include "i2c-dev.h"
#include "it8705.h"
#include "oz263.h"

#define NAME_STR "SiS96x SMBus adapter"
#define NAME_LEN 20

extern LED led;
extern PP pp;
extern DOTS dots;
extern char digits[7];
extern int file;

int oz263_write_byte_data(int file, char reg, char data)
{
  int res;
  /* TODO: Implement kernel specific stuff here. */
  res = i2c_smbus_write_byte_data(file, reg, data);
  usleep(I2C_TRANSACTION_DELAY_MS);
  return res;
}

int oz263_write_byte(int file, char data)
{
  int res;
  /* TODO: Implement kernel specific stuff here. */
  res = i2c_smbus_write_byte(file, data);
  usleep(I2C_TRANSACTION_DELAY_MS);
  return res;
}

int oz263_read_byte(int file)
{
  int res;
  /* TODO: Implement kernel specific stuff here. */
  res = i2c_smbus_read_byte(file);
  usleep(I2C_TRANSACTION_DELAY_MS);
  return res;
}

void oz263_radio_control(int file, CONTROL control)
{
  switch (control)
  {
    case SEEK_DOWN:
      oz263_write_byte_data(file, 0x27, 0x00);
      break;
    case SEEK_UP:
      oz263_write_byte_data(file, 0x13, 0x00);
      break;
    case FINE_TUNE_DOWN:
      oz263_write_byte_data(file, 0x26, 0x00);
      break;
    case FINE_TUNE_UP:
      oz263_write_byte_data(file, 0x25, 0x00);
      break;
    case CHANNEL_PREV:
      oz263_write_byte_data(file, 0x11, 0x00);
      break;
    case CHANNEL_NEXT:
      oz263_write_byte_data(file, 0x10, 0x00);
      break;
    case STORE_START:
      oz263_write_byte_data(file, 0x15, 0x00);
      break;
    case STORE_CANCEL:
      oz263_write_byte_data(file, 0x16, 0x00);
      break;
    case STORE_COMMIT:
      oz263_write_byte_data(file, 0x19, 0x00);
      break;
  }
}

void oz263_radio_mode(int file, RADIO_MODE radio_mode)
{
  oz263_write_byte_data(file, 0x23, 0x02);

  switch (radio_mode)
  {
    case OFF_MODE: /* Turns off the Radio */
      oz263_write_byte_data(file, 0x0f, 0x00);
      break;
    case AM_RADIO: /* Turns on AM Radio */
      oz263_write_byte_data(file, 0x0e, 0x00);
      break;
    case FM_RADIO: /* Turns on FM Radio */
      oz263_write_byte_data(file, 0x0d, 0x00);
      break;
    case CD_MODE:  /* Turns on CD mode */
      oz263_write_byte_data(file, 0x0c, 0x00);
      break;
    case HD_MODE:  /* Enables HD mode */
      oz263_write_byte_data(file, 0x0b, 0x00);
      break;
    default:       /* Turns off the Radio */
      oz263_write_byte_data(file, 0x0f, 0x00);
      break;

  }
}

void oz263_display(int file, char digits[6], LED led, PP pp,
                               DOTS dots, BOOL reinit)
{
  int n;

  if (reinit) /* Set to digit mode (-- --:--) */
    oz263_write_byte_data(file, 0x23, 0x02);
  /* Set up the Dots */
  oz263_write_byte_data(file, 0x06, (unsigned char)dots);
  /* Set the Play / Pause LEDs */
  oz263_write_byte_data(file, (unsigned char)pp, 0x01);

  /* Now set the mode LEDs:
  If a letter is used as the first digit next, the
  mode LED will be overridden */
  if (led != LED_NONE)
    oz263_write_byte_data(file, 0x00, (unsigned char) led);

  /* Set the state of each digit */
  for (n=0; n<6; n++)
  {
    if (digits[n] <= '9' && digits[n] >= '0')
      oz263_write_byte_data(file, n, digits[n] - '0');
    else
    {
      switch (digits[n])
      {
        case 'a':
          oz263_write_byte_data(file, n, 0x8b);
          break;
        case 'A':
          oz263_write_byte_data(file, n, 0x0b);
          break;
        case 'f':
          oz263_write_byte_data(file, n, 0x8a);
          break;
        case 'F':
          oz263_write_byte_data(file, n, 0x0a);
          break;
        case 'c':
        case 'd':
          oz263_write_byte_data(file, n, 0x8e);
          break;
        case 'C':
        case 'D':
          oz263_write_byte_data(file, n, 0x0e);
          break;
        case 'p':
          oz263_write_byte_data(file, n, 0x8d);
          break;
        case 'P':
          oz263_write_byte_data(file, n, 0x0d);
          break;
        case 'm':
        case 'M':
          oz263_write_byte_data(file, n, 0x0c);
          break;
        case '-':
          if (n == 1)
            oz263_write_byte_data(file, n, 0x0d);
          else
            oz263_write_byte_data(file, n, 0x0c);
          break;
        default:
          oz263_write_byte_data(file, n, 0x0f);
          break;
      }
    }
  }
}

int oz263_I2C_init(void)
{
  int address = AUDIODJ_I2C_ADDRESS;
  int file_i2cbus;
  char filename1[20];
  char filename2[20];
  char filename3[20];
  long funcs;

  if ( (int)getuid() != 0)
  {
#ifndef SILENT
    fprintf(stderr,"Must be root to run this program!\n");
#endif
    exit(1);
  }
  int i2cbus=find_i2c_sis96x();
  if ((i2cbus < 0) || (i2cbus > 0x3f))
  {
#ifndef SILENT
    fprintf(stderr,"Could not detect SiS96x i2c bus!\n");
#endif
    exit(1);
  }

  /* Try all three file location variants */
  sprintf(filename1,"/dev/i2c-%d",i2cbus);
  sprintf(filename2,"/dev/i2c%d",i2cbus);
  sprintf(filename3,"/dev/i2c/%d",i2cbus);
  if ((file_i2cbus = open(filename1,O_RDWR)) < 0)
    if ((file_i2cbus = open(filename2,O_RDWR)) < 0)
      if ((file_i2cbus = open(filename3,O_RDWR)) < 0)
      {
#ifndef SILENT
        fprintf(stderr,"Error: Could not open files: `%s', `%s', or `%s'\n",
                     filename1,filename2,filename3);
#endif
        exit(1);
      }

  /* check adapter functionality */
  if (ioctl(file_i2cbus,I2C_FUNCS,&funcs) < 0)
  {
#ifndef SILENT
    fprintf(stderr,
            "Error: Could not get the adapter functionality matrix: %s\n",
            strerror(errno));
#endif
    exit(1);
  }

  if (! (funcs &
       (I2C_FUNC_SMBUS_WRITE_BYTE_DATA | I2C_FUNC_SMBUS_READ_BYTE_DATA)))
  {
#ifndef SILENT
    fprintf(stderr, "Error: Adapter for i2c bus %d"
            " does not have byte write capability\n", i2cbus);
#endif
    exit(1);
  }

  /* use FORCE so that we can write registers even when
     a driver is also running */
  if (ioctl(file_i2cbus,I2C_SLAVE_FORCE,address) < 0)
  {
#ifndef SILENT
    fprintf(stderr,"Error: Could not set address to %d: %s\n",address,
            strerror(errno));
#endif
    exit(1);
  }

  if (file_i2cbus <= 0)
  {
#ifndef SILENT
    fprintf(stderr,"Could not open i2c bus!\n");
#endif
    exit(1);
  }
  return file_i2cbus;
}


int find_i2c_sis96x(void)
{
  FILE *fptr;
  char s[100];
  struct dirent *de, *dde;
  DIR *dir, *ddir;
  char dev[NAME_MAX], fstype[NAME_MAX], sysfs[NAME_MAX], n[NAME_MAX];
  int foundsysfs = 0;
  char *i2cdev;
  char *name_str;

  void print_error_msg(void);
  int sysfs_i2c_check(FILE *f);

  /* look in /proc/bus/i2c first (2.4 kernels) */
  if((fptr = fopen("/proc/bus/i2c", "r")))
  {
    while(fgets(s, 100, fptr))
    {
      i2cdev=s;
      name_str=strchr(s,'\t'); /* Find 1st tab */
      *name_str='\0'; /* Terminate string for i2cdev */
      name_str=strchr((name_str+1),'\t'); /* Find 2nd tab */
      if (!strncmp((name_str+1),NAME_STR, NAME_LEN))
      {
#ifndef SILENT
        printf("Found SiS96x SMBus adapter at i2c bus #%s\n",
          (i2cdev+4));
#endif
        fclose(fptr);
        return atoi((i2cdev+4));
      }
    }
  }

  /* Now look in sysfs, since not in /proc
     First figure out where sysfs was mounted */
  if ((fptr = fopen("/proc/mounts", "r")) == NULL)
  {
    /* proc not mounted, quit with error msg */
    print_error_msg();
    return -1;
  }

  while (fgets(n, NAME_MAX, fptr))
  {
    sscanf(n, "%[^ ] %[^ ] %[^ ] %*s\n", dev, sysfs, fstype);
    if (strcasecmp(fstype, "sysfs") == 0)
    {
      foundsysfs++;
      break;
    }
  }
  fclose(fptr);

  if (foundsysfs == 0)
  {
    /* sysfs not mounted, quit with error msg */
    print_error_msg();
    return -1;
  }

  /* Bus numbers in i2c-adapter don't necessarily match those in
  i2c-dev and what we really care about are the i2c-dev numbers.
  Unfortunately the names are harder to get in i2c-dev */
  strcat(sysfs, "/class/i2c-dev");
  if((dir = opendir(sysfs)) == NULL)
  {
    print_error_msg();
    return -1;
  }

  /* go through the busses */
  while ((de = readdir(dir)) != NULL)
  {
    if (!strcmp(de->d_name, "."))
      continue;
    if (!strcmp(de->d_name, ".."))
      continue;

    /* this should work for kernels 2.6.5 or higher and
       is preferred because is unambiguous */
    sprintf(n, "%s/%s/name", sysfs, de->d_name);
    if((fptr = fopen(n, "r")) != NULL)
      if (!sysfs_i2c_check(fptr))
      {
        fclose(fptr);
#ifndef SILENT
        printf("Found SiS96x SMBus adapter at i2c bus #%s\n",
          (de->d_name+4));
#endif
        return atoi((de->d_name+4));
      }

    /* this seems to work for ISA */
    sprintf(n, "%s/%s/device/name", sysfs, de->d_name);
    if((fptr = fopen(n, "r")) != NULL)
      if (!sysfs_i2c_check(fptr))
      {
        fclose(fptr);
#ifndef SILENT
        printf("Found SiS96x SMBus adapter at i2c bus #%s\n",
          (de->d_name+4));
#endif
        return atoi((de->d_name+4));
      }

    /* non-ISA is much harder
       and this won't find the correct bus name if a driver
       has more than one bus */
    sprintf(n, "%s/%s/device", sysfs, de->d_name);
    if(!(ddir = opendir(n)))
      continue;
    while ((dde = readdir(ddir)) != NULL)
    {
      if (!strcmp(dde->d_name, "."))
        continue;
      if (!strcmp(dde->d_name, ".."))
        continue;
      if ((!strncmp(dde->d_name, "i2c-", 4)))
      {
        sprintf(n, "%s/%s/device/%s/name",
              sysfs, de->d_name, dde->d_name);
        if((fptr = fopen(n, "r")) != NULL)
          if (!sysfs_i2c_check(fptr))
          {
            fclose(fptr);
#ifndef SILENT
            printf("Found SiS96x SMBus adapter at i2c bus #%s\n",
              (de->d_name+4));
#endif
            return atoi((dde->d_name+4));
          }
      }
    }
    closedir(ddir);
  }
  closedir(dir);

  /* If it has reached this point, then all attempts have failed.
     Print error msg and exit. */
  print_error_msg();
  return -1;
}

void print_error_msg(void)
{
#ifndef SILENT
  fprintf(stderr,"Error: No I2C busses found!\n"
    "Be sure you have modprobed the i2c-dev and\n"
    "SiS96x modules. The proc (and sysfs, if using\n"
    "a 2.6.x kernel) filesystems must also be mounted.\n");
#endif
}

int sysfs_i2c_check(FILE *f)
{
  char  x[120];
  fgets(x, 120, f);
  if(!strncmp(x, NAME_STR, NAME_LEN))
    return 0;
  else
    return 1;
}
