#include"mylib.h"
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>

#include "panel.h"
#include "pcd8544.h"
#include "timelib.h"
#include "fat.h"
#include "fat_config.h"
#include "partition.h"
#include "sd_raw.h"
#include "sd_raw_config.h"
#include "uart.h"

void PwmInit()
{
    DDRB |= (1<<DDB7);
    TCCR2 |= (1<<WGM21) | (1<<WGM20) | (1<<COM21) | (0<<COM20) | (0<<CS22) | (0<<CS21) | (1<<CS20) ;
}
void SoftReset()
{
    cli(); // disable interrupts
    wdt_enable(WDTO_15MS); // enable watchdog
    while(1); // wait for watchdog to reset processor
}

unsigned char MySDcard_init(sSdCard *fSdCard)
{

    (*fSdCard).partition = partition_open(sd_raw_read,
                                          sd_raw_read_interval,
    #if SD_RAW_WRITE_SUPPORT
                                          sd_raw_write,
                                          sd_raw_write_interval,
    #else
                                          0,
                                          0,
    #endif
                                          0
                                          );

    if(!(*fSdCard).partition)
    {
        (*fSdCard).partition = partition_open(sd_raw_read,
                                           sd_raw_read_interval,
    #if SD_RAW_WRITE_SUPPORT
                                           sd_raw_write,
                                           sd_raw_write_interval,
    #else
                                           0,
                                           0,
    #endif
                                           -1
                                          );
    if(!(*fSdCard).partition)
        return 0;
    }

    (*fSdCard).fs = fat_open((*fSdCard).partition);
    if(!(*fSdCard).fs)
        return 0;

    struct fat_dir_entry_struct directory;
    fat_get_dir_entry_of_path((*fSdCard).fs, "/", &directory);
    (*fSdCard).dd = fat_open_dir((*fSdCard).fs, &directory);
    if(!(*fSdCard).dd)
        return 0;

    return 1;
}

unsigned char nsd(unsigned char ta, unsigned char tb)
{
  unsigned char A, B, C;

  if(ta > tb)
  {
    A = ta;
    B = tb;
  }
  else if(ta < tb)
  {
    A = tb;
    B = ta;
  }
  else
  {
    return ta;
  }

  do{
    C = A%B; // % je operator modulo
    A = B;
    B = C;
  } while(B != 0);
  return A;
}
