//-- pub log -- {
//#define PUB_LOG_IS_IN_USE
#ifdef PUB_LOG_IS_IN_USE
#include <limits.h>
extern int pub_log_handle;
extern char pub_log_buf[BUFSIZ];
extern const char * pub_log_name;
#ifndef WIN32
int lock_reg(int, int, int, off_t, int, off_t);
#define LOCK_PUB_LOG  if(pub_log_handle>=0){while(lock_reg(pub_log_handle, F_SETLK, F_WRLCK, 0, SEEK_SET, LONG_MAX)<0);}
#define UNLOCK_PUB_LOG  if(pub_log_handle>=0){lock_reg(pub_log_handle, F_SETLK, F_UNLCK, 0, SEEK_SET, LONG_MAX);}
#else
#define LOCK_PUB_LOG  if(pub_log_handle>=0){while(_locking(pub_log_handle,LK_NBLCK,LONG_MAX)<0);}
#define UNLOCK_PUB_LOG  if(pub_log_handle>=0){_locking(pub_log_handle,LK_UNLCK,LONG_MAX);}
#endif
#ifndef WIN32
#ifndef O_BINARY
#define O_BINARY 0
#endif
#endif
#define OPEN_PUB_LOG  pub_log_handle=open(pub_log_name,O_RDWR|O_CREAT|O_APPEND|O_BINARY,S_IREAD|S_IWRITE);

#define CLOSE_PUB_LOG \
	if(pub_log_handle>=0){ \
		close(pub_log_handle); \
		pub_log_handle=-1; \
	}

#define STARTPOS_PUB_LOG  if(pub_log_handle>=0){lseek(pub_log_handle,0,SEEK_END);}
//ВНИМАНИЕ! Эта функция не имеет ничего общего с той, что в vigrid_util.c
void write_pub_log(char *format, ...);
#define WRITE_PUB_LOG  write_pub_log
#else
#define WRITE_PUB_LOG  printf
#endif
//-- pub log -- }

//-- pub log -- {
#ifdef PUB_LOG_IS_IN_USE
#include <sys/types.h>
#include <sys/stat.h>
#ifdef WIN32
#include <sys/locking.h>
#include <share.h>
#include <io.h>
#else
#include <unistd.h>
#endif
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int pub_log_handle;
char pub_log_buf[BUFSIZ];
const char * pub_log_name="/work/proj/foreign/lcms11/lsms11.log";
#ifndef WIN32
int lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len)
{
  struct flock    lock;
  lock.l_type = type;     // F_RDLCK, F_WRLCK, F_UNLCK
  lock.l_start = offset;  // byte offset, relative to l_whence
  lock.l_whence = whence; // SEEK_SET, SEEK_CUR, SEEK_END
  lock.l_len = len;       // #bytes (0 means to EOF)
  return( fcntl(fd, cmd, &lock) );
}
#endif
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4996 )
#endif
//ВНИМАНИЕ! Эта функция не имеет ничего общего с той, что в vigrid_util.c
void write_pub_log(char *format, ...) {
	OPEN_PUB_LOG
	LOCK_PUB_LOG
   	STARTPOS_PUB_LOG
	if(pub_log_handle<0)goto end;
	if(format==NULL) 
		goto end;
	else {
  		va_list vlist;
  		memset(pub_log_buf,0,BUFSIZ);
  		va_start(vlist, format);
  		vsprintf(pub_log_buf, format, vlist);
  		va_end(vlist);
		lseek(pub_log_handle,0,SEEK_CUR);
		write(pub_log_handle, pub_log_buf, strlen(pub_log_buf));
	}
	end:;
	UNLOCK_PUB_LOG
	CLOSE_PUB_LOG
}
#ifdef WIN32
#pragma warning( pop )
#endif
#endif
//-- pub log -- }

