#include <avr/io.h>

//time delay program,
//PORD D, eight dip switches, goes from 0 to 255T, defines time off
//set in secDelay, 1300 gives approximately 5 seconds maximum
//                 2600 gives approximately 10 seconds
//PORT B: six of the inputs are used, typically with 5 position dip switch
//since 6p dip switches are less common.
//on PORT B dip switch, all switches up (open) gives infinity time on.

void secDelay(int count){
	int i;
	for(;count>0;count--){
		for(i=1000; i>0;i--){
//		for(i=2600; i>0;i--){
			i--;
		}	
	}
}
/*
void secDelay_initStateHold(int countStart){
	int i;
	int count = countStart;
	for(;count>0;count--){
		for(i=1000; i>0;i--){
		for(i=2600; i>0;i--){
		  i--;
		  if((PINC&1)==0)  count = countStart;
		  // Hold in init state if PC0 is being pulled down.
		  // Start counting again.
		}	
	}
}
*/

int main(){

		
	PORTB	= 0xBF;   // was 3F, but now, output bits are in init state.
	DDRB	= 0xC0;

	char internalPORTD = 0;
	PORTD	= 0x00;
	DDRD	= 0xFF;

	PORTC	= 0x01;   // Input with pull-up resistor activated
	DDRC	= 0x00;

	/*PORTB	= 0xC0;
	PORTD	= 0x00;*/

	char delaytime = 1;
/*
	int timeAfter, timeBefore;
	
	PORTB	= 0xBF;   // outputs init, input pull-up resistors activated
	timeAfter = PINB;
	timeAfter &= 0x3F;

	timeBefore = PIND;
	// no need to mask since it uses all pins
*/	
  while(1) {
/*	PORTB = 0x80;    // Warning: messing with pull-up resistors
	secDelay_initStateHold(timeBefore*5);
        PORTB = 0x40;

	// BY SIMON: June 5th
	// Commented out lines below for the latest revisions
	// of the relay... it should never shut off.
	if (timeAfter != 0x3F) {
        	secDelay(timeAfter*5);  // warning: ignores PC0
		PORTB = 0x80; 
	}
        //PORTB = 0x80;

	while ((PINC&1)==1);  // Stay in steady-state ("on") if PC0 is 1
	// If we get to here, someone must have pulled PC0 to 0.
	// Loop back to the start; Outputs go back to initial state.
	// (note: limitation is that it doesn't re-read the dip switch inputs.
	// when I quickly tried to do that, the outputs just remained
	// stuck in the initial state.)
*/

	secDelay(delaytime++);
	//internalPORTD = internalPORTD << 1;
	//if(internalPORTD==0)  internalPORTD = 0x01;
	PORTD = ~PORTD;
	//if(PORTD==0)  PORTD = 0x01;
	//PORTD = internalPORTD;
  }

  return 0;
}

