#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <asm/io.h>
#include <time.h>

#define base 0x378           /* adresa LPT porta */

int value;            /* Numericka vrednost koja se salje portu */

void shownum(int dec, int c);
int bin2dec(char *bin);
void dec2bin(long decimal, char *binary);

int main()
{
  int no;
  time_t tm;
  struct tm *now = NULL;
  int hour=0;
  int min=0;

	for (no = 1; no <= 2; no++)
	{
		// Vraca brojac na 1, tako da petlja nikada ne zavrsava. Nisam smislio nista pametnije - ovo je samo test verzija :)
		no = 1;

		// Prikazuje sate
		tm = time(NULL);
		now = localtime(&tm);
		hour = now->tm_hour;
		if (hour > 12) hour = hour - 12;
		if (hour == 0) hour = 12;
		shownum(hour, 0);
		sleep(5);

		// Prikazuje minute
		min = now->tm_min;
		shownum(min, 1);
		sleep(15);
	}

  	getchar();  // Pritisnite enter za kraj...
  	return 0;
}
 

// Glavna procedura - konvertuje vreme u binari broj, menja raspored sbitova itd itd. Sve sto treba da kontrolise paljenje i gasenje dioda
// ide ovde. Za sada bas i nema mnogo toga, ali u planu su neke "sitnice" koje treba da olaksaju upotrebu sata
void shownum(int dec, int c)
{
  char bin[80] = "";
  char *p;
  char s[80] = "";
  int i, tmp, j;

	dec2bin(dec, bin);
	for (i = 1; i <= 8; i++)
		s[i-1] = bin[i];
//	printf("! %s !, %d\n", s, dec);
	value  = bin2dec(s);

// Dobijena vrednost se salje LPT portu
   	if (ioperm(base,1,1))
    		fprintf(stderr, "Couldn't get the port at %x\n", base), exit(1);

   	outb(value, base);
}

// Konverzija binarnog stringa u dekadni broj
int bin2dec(char *bin)
{
  int  b, k, m, n;
  int  len, sum = 0;
 
  len = strlen(bin) - 1;
  for(k = 0; k <= len; k++) 
  {
    n = (bin[k] - '0'); // Karakter u numericku vrednost
    if ((n > 1) || (n < 0)) 
    {
      puts("\n\n ERROR! BINARY has only 1 and 0!\n");
      return (0);
    }
    for(b = 1, m = len; m > k; m--) 
    {
      // 1 2 4 8 16 32 64 ... vrednost pozicija, u suprotnom smeru
      b *= 2;
    }
    // sumiranje
    sum = sum + n * b;
    // printf("%d*%d + ",n,b);  // testiranje... sta radi program
  }
  return(sum);
}

// Konverzija dekadnog u binarni broj
void dec2bin(long decimal, char *binary)
{
  int  k = 0, n = 0;
  int  neg_flag = 0;
  int  remain;
  int  old_decimal;  // test
  char temp[80];
 
  // Ok vreme nikada nije negativno... ali desi se :)
  if (decimal < 0)
  {
    decimal = -decimal;
    neg_flag = 1;
  }
  do 
  {
    old_decimal = decimal;   // test
    remain    = decimal % 2;
    // whittle down the decimal number
    decimal   = decimal / 2;
    // test - da se vidi sta program radi
    // printf("%d/2 = %d  ostatak = %d\n", old_decimal, decimal, remain);
    // konverzija int 0 ili 1 u karaktere '0' or '1'
    temp[k++] = remain + '0';
  } while (decimal > 0);
 
  if (neg_flag)
    temp[k++] = '-';
  else
    temp[k++] = ' ';
 
  // inverzija zapisa
  while (k >= 0)
    binary[n++] = temp[--k];
 
  binary[n-1] = 0;
}

