/*
 * Get time according to system (RTC or whatever we have...)
 * This is similar to localtime() in the standard C library, except
 * only the current time is supported and some of the derived fields
 * are not produced.
 */

#ifndef SYSTIME_H
#define SYSTIME_H

#include <stdint.h>

struct tms_tick_reg {
    union {
	uint16_t ticks;
	struct {
	    unsigned int tm_tick : 15;
	    unsigned int tm_1sec : 1;
	};
    };
} __attribute__((aligned(2)));

struct tms {
    union {
	uint32_t words[2];
	struct {
	    unsigned int tm_2sec     : 5;
	    unsigned int tm_min      : 6;
	    unsigned int tm_hour     : 5;
	    unsigned int tm_mday     : 5;
	    unsigned int tm_mon      : 4;
	    unsigned int tm_year     : 7;
	    struct tms_tick_reg hold;
	    struct tms_tick_reg now;
	};
    };
} __attribute__((aligned(4)));

static inline struct tms get_systime(void)
{
    struct tms tms;

    tms.words[0] = SYSCLOCK_DATETIME;
    tms.words[1] = SYSCLOCK_TICK;

    return tms;
}

static inline void set_systime(struct tms tms)
{
    SYSCLOCK_TICK_HOLD = tms.hold.ticks;
    SYSCLOCK_DATETIME  = tms.words[0];
}

static inline unsigned int tms_sec(struct tms tms)
{
    return (tms.tm_2sec << 1) | tms.hold.tm_1sec;
}

#endif /* SYSTIME_H */
