#include "binary.h"
#include "avrcommon.h"
#include "mcs85bus.h"
#include <avr/io.h>

//port definitions


// OH FUTZ we have a split data bus
//  D0-1 go on port B
//  D2-7 go on port D

void BusModeOutput() {
  DDRB |= b00000011;
  DDRD |= b11111100;

  
}

void BusModeInput() {
  DDRB &= b11111100;
  DDRD &= b00000011;

}

void OutputByte(unsigned char d) {

  PORTB &= ~b00000011;
  PORTB |= (d & b00000011) ;
  PORTD &= ~b11111100;
  PORTD |= (d & b11111100);  
  NOP();
  NOP();
  NOP();
  NOP();
  NOP();
}

unsigned char InputByte() {  
  NOP();
  NOP();
  NOP();
  NOP();
  NOP();
  return ((PINB  & b00000011) | (PIND & b11111100 ));

}

unsigned char ReadMCS85(unsigned char address){
   unsigned char result;
   
  // set address
  BusModeOutput();
  OutputByte(address);
  // set CS low (chip select is established first cause its part of the address bus)
  CSLOW();  
  
  ALEHIGH();  NOP(); NOP();  ALELOW();
  BusModeInput();
  
  // set read low
  RDLOW();  
  // read data 
  NOP();
  result = InputByte();
  // release bus
  IDLE();
  
  return result;
}


void WriteMCS85(unsigned char address, unsigned char data){
  // nobody should be on the bus, so put up our signals

  // set address
  BusModeOutput();
  
  // chip select low
  CSLOW();
  
  OutputByte(address);
  ALEHIGH(); NOP(); NOP(); ALELOW();
  
  OutputByte(data);

  
  // strobe WR
  WRLOW();  NOP(); NOP();WRHIGH(); 
  // release bus
  IDLE();
  
}


void IDLE(void) {
  WRHIGH();
  RDHIGH(); 
  CSHIGH();
  BusModeInput();
}


