#include "defines.h"
/*     Bed a menu-driven multi dataformat binary editor for Linux            */
/*     Copyright (C) 1998 Jaap Korthals Altes <jkaltes@hetnet.nl>       */
/*                                                                           */
/*     This program is free software; you can redistribute it and/or modify  */
/*     it under the terms of the GNU General Public License as published by  */
/*     the Free Software Foundation; either version 2 of the License, or     */
/*     (at your option) any later version.                                   */
/*                                                                           */
/*     This program is distributed in the hope that it will be useful,       */
/*     but WITHOUT ANY WARRANTY; without even the implied warranty of        */
/*     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         */
/*     GNU General Public License for more details.                          */
/*                                                                           */
/*     You should have received a copy of the GNU General Public License     */
/*     along with this program; if not, write to the Free Software           */
/*     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.             */
/* Fri Dec  8 22:14:27 2000                                                  */
#include "desturbe.h"
#include "config.h"
#ifdef PDCURSES
#include <windows.h>
extern HANDLE hConOut;
#endif
#include <features.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <stdio.h>
//#include <sys/termios.h>
#include "system.h"
#include "screen.h"

#include "cursesinit.h"
extern int redistribute;
extern void initcolor(void) ;

int after_initscr=0;
#if defined(USE_NEWTERM) || defined(GETOTHERTERM)
extern SCREEN *thescreen;
#endif

extern int		resetcolors(void) ;
extern int upmenus(void) ;
extern void delmenus(void) ;
extern void getotherterm(void ) ;
#ifndef NEWTERM
extern void scrsize(void) ;
extern char staticscreen;
extern char *linemax,*colmax;
	void nocurses_init::curses_init(void) { /*Initialize screen */

	//	on_exit(terminate,0);
		int col=80,lin=25;
		char buf[100];
#ifdef TIOCGWINSZ
		struct winsize win;
	   if (ioctl(0, TIOCGWINSZ, &win) == 0&&win.ws_row&&win.ws_col)  {
			if(!staticscreen&&getenv("DISPLAY")) {
				strcpyn(buf,"LINES=",6);
				strcpy(buf+6,linemax);
				putenv(buf);


				strcpyn(buf,"COLUMNS=" ,8);
				strcpy(buf+8,colmax);
				putenv(buf);
				}
			else {
				if (win.ws_row != 0) {
				    lin = win.ws_row;
				}
				if (win.ws_col != 0) {
				    col = win.ws_col;
				}
				}
			}
#endif
		char *collen=getenv("COLUMNS");
		char *linnen=getenv("LINES");
		if(collen) 
			 col=atoi(collen);
		if(col<60)
			putenv("COLUMNS=65");
		else {
			if(col>550)
				putenv("COLUMNS=550");
			else {
				sprintf(buf, "COLUMNS=%d",col);
				putenv(buf);
				}
			}
		if(linnen) 
			lin=atoi(linnen);

		if(lin<20)
			putenv("LINES=20");
		else {
			sprintf(buf, "LINES=%d",lin);
			putenv(buf);
			}
		initscr();
		after_initscr=1;
		thelines=LINES;
		thecols=COLS;
		
		clearok(stdscr,FALSE);
		clearok(curscr,FALSE);

		initcolor();
		setscreen();
		reset();
		OldMainScreenwidth=MainScreenwidth;
		};
	void  nocurses_init::reset(void ) {
			scrsize();
			clear();
			refresh();
		wresize(stdscr,thelines,thecols);
		 //   resizeterm( thelines,thecols);
			HIDECURSOR;
			redistribute=1;
		}
	int  nocurses_init::resized(void) { /*Reset screen for program */
		int oldlines=thelines, oldcols=thecols;
			scrsize();
			if(oldlines!=thelines||oldcols!=thecols) {
			wresize(stdscr,thelines,thecols);
		//	    resizeterm( thelines,thecols);
				clear();
				refresh();
				redistribute=1;
				HIDECURSOR;
				return 1;
				}
		HIDECURSOR;
		return 0;
		};
#else

#if defined(PDCURSES)&& !defined(USE_NEWTERM)
#include <stdlib.h>
#include <process.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <windows.h>
extern int margc;
extern char **margv;
static int beforeinitscr=0;
static void exitinitscr(void) {
	if(beforeinitscr) {
		char *NBED
#ifdef SEARCHPATHNAME
,*thisprog
#endif
;
		if(!(NBED=getenv(NCURSES_BEDENV))) {
			NBED=NCURSES_BED;
			}
		fprintf(stderr,"%s failed, execute %s ...\n",margv[0],NBED);

#ifdef SEARCHPATHNAME
		thisprog=margv[0];
#endif
		margv[0]= NBED; /*ENV+conf*/
		if(execvp(margv[0], margv)==-1) {
			if(errno==ENOENT) {
				char fullname[MAX_PATH];
				char *filcmp;
#ifndef SEARCHPATHNAME
	if( GetModuleFileName(
			NULL,	// handle of module to find filename for 
			fullname,	// address of buffer for module path 
			MAX_PATH 	// size of buffer, in characters 
		 )>0) {
#else
	 if(SearchPath(

				NULL,	// address of search path 
				thisprog,	// address of filename 
				".exe",	// address of extension 
				MAX_PATH,	// size, in characters, of buffer 
				fullname,	// address of buffer for found filename 
			&filcmp 	// address of pointer to file component 
		 )>0)	 {
#endif
	if(access(NCURSES_BED,0)) {
			char binpatch[]= CONFDIR"\\binpatch.exe";
			char bedpatch[]= CONFDIR"\\bedpatch";

			char command[MAX_PATH];
			sprintf(command,"\"%s\" \"%s\" \"%s\" \"%s\" -a",binpatch,fullname,NCURSES_BED,bedpatch);
			fprintf(stderr,"create %s:\n%s\n",NCURSES_BED, command);
			system(command);
			margv[0]=NCURSES_BED;
		execvp(margv[0], margv);
		}
	else {
	  fprintf(stderr,"%s does exists, but execvp failed\n",NCURSES_BED);
		}

				}
	else {

#ifdef SEARCHPATHNAME
		fprintf(stderr,"Can't execute %s, can't find %s to create %s\n",margv[0],thisprog,NCURSES_BED);
#else
		fprintf(stderr,"Can't execute %s, can't find program name",margv[0]);
#endif
		}
			}
		else {
			perror(NBED);
			}
		}
        }
	}
#endif
	void nocurses_init::curses_init(void) { /*Initialize screen */
#ifdef USE_NEWTERM
		thescreen=newterm(NULL, stdout,stdin);
		if(!thescreen) {
			char *term=getenv("TERM");
			fprintf(stderr,"newterm/3 failed, ");
			if(!term) 
				fprintf(stderr,"give environmental variable TERM a value and try again\n");
			else
				fprintf(stderr,"is TERM=%s alright?\n",term);
			exit(1	);
			}
		set_term(thescreen);
#else
#ifdef PDCURSES
beforeinitscr=1;
    atexit(&exitinitscr);
#endif

		if(initscr()==NULL) {
#ifdef PDCURSES
			beforeinitscr=0;
			exitinitscr();
#endif
			}
after_initscr=1;
#ifdef PDCURSES
beforeinitscr=0;
#endif
#endif
		thelines=LINES;
		thecols=COLS;
/*
#ifdef PDCURSES
		mouse_set(BUTTON2_PRESSED|BUTTON3_PRESSED);
#endif
#ifdef NCURSES_VERSION
mmask_t oldmask,newmask=BUTTON2_PRESSED;
 mousemask( newmask,  &oldmask);
#endif
*/
			
		initcolor();
		setscreen();
		clearok(stdscr,TRUE);
		redistribute=1;
		OldMainScreenwidth=MainScreenwidth;
		HIDECURSOR;
		refresh();
		};
	void  nocurses_init::reset(void ) {
		resized();
		}
	int  nocurses_init::resized(void) { /*Reset screen for program */

#ifdef TIOCGWINSZ
		struct winsize win;
	   if (
#ifdef GETOTHERTERM
!thescreen||
#endif //GETOTHERTERM
(ioctl(0, TIOCGWINSZ, &win) == 0 && (thelines != win.ws_row || thecols != win.ws_col))) {
#else // TIOCGWINSZ
#ifdef PDCURSES
    
CONSOLE_SCREEN_BUFFER_INFO csbi;      
 GetConsoleScreenBufferInfo(hConOut, &csbi);
if(csbi.dwSize.Y!=thelines||csbi.dwSize.X!=thecols) {
	resize_term(csbi.dwSize.Y,csbi.dwSize.X);
#endif //PDCURSES
#endif // TIOCGWINSZ
			INCDEST();
			delmenus();
#ifndef  NOENDWIN
if(!isendwin())
			endwin();
#endif
#ifdef NEWTERMRESIZE
#ifdef HASDELSCREEN
			if(thescreen)
				delscreen(thescreen);
#endif // HASDELSCREEN
			thescreen=newterm(NULL, stdout,stdin);
			if(!thescreen) {
				NODEST();
				getotherterm();
				return 0;
				}				
			thelines=LINES;
			thecols=COLS;
			resetcolors() ;
			setscreen();
			clearok(stdscr,TRUE);
	//		refresh();
#else //NEWTERMRESIZE
#ifndef PDCURSES
			refresh(); /*back from endwin*/
#endif
			flushinp();
			thelines=LINES;
			thecols=COLS;
#ifndef PDCURSES
DEBUGGING("Resized: thelines=%d,thecols=%d win_ws_row=%d, win.ws_col=%d LINES=%d, COLS=%d\n", thelines,thecols,win.ws_row,win.ws_col,LINES,COLS );
#endif
			redistribute=1;
			HIDECURSOR;
			OldMainScreenwidth=MainScreenwidth;
			if(upmenus()<0) {
				DECDEST();
				return -1;
				}
			refresh();
			DECDEST();
			return 0;
#endif //NEWTERMRESIZE
#if defined(PDCURSES)||defined(TIOCGWINSZ)
			}

		else
		{
			setscreen();
			clearok(stdscr,TRUE);
			redistribute=1;
			thelines=LINES;
			thecols=COLS;
			HIDECURSOR;
			OldMainScreenwidth=MainScreenwidth;
			refresh();
			return 0;
			}
#endif
		};
#endif
	void  nocurses_init::restore(void) { /*restore screen from before start program */
		move(thelines-1,0);
		clrtoeol();
		touchline(stdscr,thelines-1,1);
	if(!isendwin())
		endwin();
		};
	void  nocurses_init::setscreen(void) { /*Set screen for program */
		noecho();
	   	cbreak();
	   	nonl();
#ifdef USE_KEYPAD 
	keypad(stdscr,TRUE);
meta(stdscr,TRUE);
/*#ifdef PDCURSES
PDC_save_key_modifiers(FALSE);
PDC_return_key_modifiers(FALSE);
#endif
*/
#endif
	   	};





