/* cmanalog.c
   L. Stewart September 24, 1982  9:52 AM
   L. Stewart December 3, 1982  2:44 PM
 */

#include	"Env.h"
#include	"Lark.h"
#include	"LarkSlave.h"

/* pioml */
extern PIOOn();
extern PIOOff();
extern SetPIO();
extern GetPIO();
extern SetCodec();

/* runtime */
extern StoreW();
extern OutByte();

#define	SwData	0x0001
#define	SwStb0	0x0010
#define	ipioa	0
#define	ipiob	1
#define	ipioc	2
#define	iapioa	3
#define	iapiob	4
#define	iapioc	5

InitAnalog()
  {
  int row, col;
  /* set up apio */
  OutByte(apioctl, 0x0088);
  SetPIO(0x00c0, iapioa);  /* both relays OFF */
  SetPIO(0x000c, iapioc);  /* no ring or sidetone */
  SetPIO(0x0000, iapiob);
  SetPIO(0x00e1, ipioa);  /* LED Off */
  SetPIO(0x0030, ipioc);  /* both relays off */
  SetCodec(0x0c);   /* timeslot 13 */
  /* open all crossbar switches */
  XbarClear();
  ResetAnalogInt();
  ResetEncInt();
  StoreW(InTab00, In1Gain);
  StoreW(InTab00, In2Gain);
  StoreW(OutTab00, OutGain);
  };

static ClearXbar(row, col)
  int row, col;
  {
  PIOOff(SwData, iapioc);
  xbarcom(row, col);
  };

SetXbar(row, col)
  int row, col;
  {
  PIOOn(SwData, iapioc);
  xbarcom(row, col);
  };

static xbarcom(row, col)
  int row, col;
  {
  int	data, clock, shift;
  data = (col & 3) | ((row & 3) << 2);
  if (row < 4) shift = 0;
  else shift = 1;
  if (col >= 4) shift += 2;
  clock = (SwStb0 << shift);
  SetPIO(data, iapiob);
  SetPIO(clock + data, iapiob);
  SetPIO(data, iapiob);
  };

static ResetAnalogInt()
  {
  PIOOff(0x0080, ipioa);
  PIOOn(0x0080, ipioa);
  };

static ResetEncInt()
  {
  PIOOff(0x0001, ipioa);
  PIOOn(0x0001, ipioa);
  };

/* 0 means default, 1 means O3I1, 2 means O2I2 */
StartSlave(prog, length)
  int prog, length;
  {
  int i;
  StoreW(prog, CodeLoc);
  StoreW(length, CodeLen);
  PIOOn(0x20, ipioa);
  for (i=0; i< 20; i+= 1);
  OutByte(dmamode, 0xc0);
  OutByte(dmasmsk, 0x00);
  PIOOff(0x20, ipioa);
  for (i=0; i< 20; i+= 1);
  if (prog != 0) {
    PIOOff(0x10, ipioa);
    PIOOn(0x10, ipioa);
    PIOOff(0x10, ipioa);
    };
  };

static XbarClear()
  {
  int row, col;
  for (row = 0; row < 8; row += 1) {
    for (col = 0; col < 8; col += 1) ClearXbar(row, col);
    };
  };