#include <avr/io.h>
#include <util/delay.h>

#define BITCOUNT 6

#define D_PORT		PORTC
#define D_PIN			PINC
#define D_DDR			DDRC
#define D_CLK			PC0
#define D_STR			PC1
#define D_D1			PC2
#define D_D2			PC3
#define D_D3			PC4
#define D_D4			PC5

#define PIN_DCF		PD0


#define splitdigits( v, a, b )  \
    /*{{{*/                     \
    a = 0;                      \
    b = v;                      \
    while (b >= 10) {           \
        b -= 10;                \
        a++;                    \
    }                           \
    /*}}}*/

void Clock(void);
void Strobe(void);


void Clock(void) {
	D_PORT |= _BV(D_CLK);
	D_PORT &= ~_BV(D_CLK);
}

void Strobe(void) {
	D_PORT |= _BV(D_STR);
	D_PORT &= ~_BV(D_STR);
}

void ShowNumber(unsigned char z1,unsigned char z2, unsigned char z3, unsigned char z4) {
	unsigned char bit;
	
	for(bit=0;bit<BITCOUNT;bit++) {
		if( (z1 & _BV(bit)) == _BV(bit) ) {
  		D_PORT |= _BV(D_D1);
		}
		else {
			D_PORT &= ~_BV(D_D1);
		}

		if( (z2 & _BV(bit)) == _BV(bit) ) {
  		D_PORT |= _BV(D_D2);
		}
		else {
			D_PORT &= ~_BV(D_D2);
		}

		if( (z3 & _BV(bit)) == _BV(bit) ) {
  		D_PORT |= _BV(D_D3);
		}
		else {
			D_PORT &= ~_BV(D_D3);
		}
		
		if( (z4 & _BV(bit)) == _BV(bit) ) {
  		D_PORT |= _BV(D_D4);
		}
		else {
			D_PORT &= ~_BV(D_D4);
		}
		
		Clock();
	}
	Strobe();
}

int main(void) {
	unsigned char j = 0;

  unsigned char hour=14, minute=15, second=0;
  unsigned char *data;

	D_DDR = _BV(D_CLK) | _BV(D_STR) | _BV(D_D1) | _BV(D_D2) | _BV(D_D3) | _BV(D_D4);
	D_PORT = 0;

	while(1) {

		if(second < 59){
			second++;
		}
		else{
		  second=0;
			if(minute < 59){
				minute++;
			}
			else{
				minute=0;
				if(hour < 23){
					hour++;
				}
				else {
					hour=0;
				}
			}
		}

	
	  /* input and output */
    unsigned short int hms[] = {15,42, 23};
    unsigned short int rows[] = {0, 0, 0, 0};
	
		hms[0] = hour;
		hms[1] = minute;
		hms[2] = second;

    /* power array */
    unsigned short int pow[] = {1, 2, 4, 8, 16, 32};

    /* fill time array */
    unsigned short int a, b, i;
    unsigned short int time[] = {0, 0, 0, 0, 0, 0};
    for (i = 0; i < 3; i++) {
        splitdigits(hms[i], a, b);
        time[i*2] = a; 
        time[i*2+1] = b;
    }

    /* fill rows array */
    unsigned short int r = 0, power = 0; 
    for (r = 0; r < 4; r++) {
        int power = pow[r];
        for (i = 0; i < 6; i++) {
            if ((time[i] & power) > 0) {
                rows[r] += pow[i];
            }
        }
    }
	
		ShowNumber(rows[0],rows[1],rows[2],rows[3]);
		//ShowNumber(12,9,45,56);
		
		for(j=0;j<100;j++) 
			_delay_ms(10);
	}
}
