/* atmd.h - Functions useful for demons */
 
/* Written 1995-1997 by Werner Almesberger, EPFL-LRC */
 

#ifndef ATMD_H
#define ATMD_H

/*--------------------------- Common definitions ----------------------------*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/time.h>

/* doubly linked list primitives */
 
#define Q_INSERT_HEAD(r,i) ({ (i)->next = r; (i)->prev = NULL; \
  if (r) (r)->prev = i; r = i; })
#define Q_INSERT_AFTER(r,i,a) ({ if (a) { (i)->next = (a)->next; \
  (i)->prev = a; if ((a)->next) (a)->next->prev = i; (a)->next = i; } \
  else { (i)->next = r; (i)->prev = NULL; if (r) (r)->prev = i; r = i; } })
#define Q_INSERT_BEFORE(r,i,b) ({ if (b) { (i)->next = b; \
  (i)->prev = (b)->prev; if ((b)->prev) (b)->prev->next = i; else r = i; \
  (b)->prev = i; } else { (i)->next = r; (i)->prev = NULL; \
  if (r) (r)->prev = i; r = i; } })
#define Q_REMOVE(r,i) ({ if ((i)->next) (i)->next->prev = (i)->prev; \
  if ((i)->prev) (i)->prev->next = (i)->next; else r = (i)->next; })


extern struct timeval now;
extern int debug;


#define alloc_t(t) ((t *) alloc(sizeof(t)))


void *alloc(size_t size);


/*--------------------------- Diagnostic messages ---------------------------*/


#include <stdarg.h>


#define DIAG_DEBUG 	3
#define DIAG_INFO	2
#define DIAG_WARN	1
#define DIAG_ERROR	0
#define DIAG_FATAL	-1


void set_application(const char *name);

void set_logfile(const char *name);

FILE *get_logfile(void);

void set_verbosity(const char *component,int level);

int get_verbosity(const char *component);

void vdiag(const char *component,int severity,const char *fmt,va_list ap);
void diag(const char *component,int severity,const char *fmt,...);
void diag_dump(const char *component,int severity,const char *title,
  const unsigned char *data,int len);


/*------------------------------ Timer support ------------------------------*/


#include <sys/time.h>


typedef struct _timer {
    struct timeval expiration;
    void (*callback)(void *user);
    void *user;
    struct _timer *prev,*next;
} TIMER;

TIMER *start_timer(long usec,void (*callback)(void *user),void *user);
void stop_timer(TIMER *timer);
void (*timer_handler(TIMER *timer))(void *user);
struct timeval *next_timer(void);
void pop_timer(TIMER *timer);
void expire_timers(void);

#endif
