#include "global.h" 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "config.h"
#include CURSES_HEADER
#ifdef _WIN32
#include <windows.h>
#endif
BEDPLUGIN
extern int withinxterm;
#if !defined(PCURSES)
static const char titlestart[]="\033]0;";
static const char titleend[]="\007";
#define setesctitle(titlebuf) if(withinxterm) {write(STDOUT_FILENO,titlestart,sizeof(titlestart)-1);write(STDOUT_FILENO ,titlebuf,strlen(titlebuf));write(STDOUT_FILENO ,titleend,sizeof(titleend)-1);}
#endif
#ifdef _WIN32
#ifdef PCURSES
#define settitle(titlebuf) SetConsoleTitle(titlebuf)
#else
void settitle(char *titlebuf) {
	SetConsoleTitle(titlebuf);
	setesctitle(titlebuf);
}
#endif
#else
void settitle(char *titlebuf) {
	setesctitle(titlebuf)
    }
#endif
void endtitle(void) {
	settitle("Unknown");
	}
#ifndef PROGRAM
#define PROGRAM "bed"
#endif
#ifndef _WIN32
#define TTYNAME
#define HOSTNAME
#endif
class Editor {
public:
int filetype(void);
int addfile(void);
char *getfilename(char *buf);
int filetitle(void) {
	const int MAXTITLE=200;
	static char nothing=(atexit(endtitle),1);
#ifdef HOSTNAME
	static char hostname[50];
	static char *ptr=(((hostname[0]='\0',gethostname(hostname, 50),(ptr=strchr(hostname,'.'))?*ptr='\0':1)),ptr);
	static int hostnamelen=strlen(hostname);
#endif
	const int proglen=sizeof(PROGRAM);
	char titlebuf[MAXTITLE+1];
	int nr=0;
	memcpy(titlebuf+nr,PROGRAM,proglen-1);
	nr+=proglen;
	titlebuf[proglen-1]=' ';
#ifdef HOSTNAME
	if(MAXTITLE>nr) {
		memccpy(titlebuf+nr,hostname,'\0',MAXTITLE-nr);
		nr+=hostnamelen;
		titlebuf[nr++]='-';
		}
#endif
#ifdef TTYNAME
#ifdef HAS_TTYNAME_R
	char nametty[15];
#else
	char *nametty;
#endif
//	ptsname_r(titlebuf,ttys[i],MAXTITLE-nr);
	if(isatty(STDOUT_FILENO)) {
#ifdef HAS_TTYNAME_R
		if(!ttyname_r(STDOUT_FILENO,nametty,15)) {
#else
		if((nametty=ttyname(STDOUT_FILENO))) {
#endif
	if(MAXTITLE>nr) {
			memccpy(titlebuf+nr,nametty+5,'\0',MAXTITLE-nr);
			nr+=strlen(titlebuf+nr);
			}
			}
		}
	if(nr<MAXTITLE)
		titlebuf[nr++]=' ';

#endif
	if(MAXTITLE>nr) {
		memccpy(titlebuf+nr,getfilename(NULL),'\0',MAXTITLE-nr);
		}
	titlebuf[MAXTITLE]='\0';
	settitle(titlebuf);
	};
};




call_on_switch(filetitle)
