#include "editor.h"
#include "system.h"

struct help {
	int (Editor::*proc)(void) ;
//	char *name;
	char *text;
	short *ind;
	short nr;
	};


//#define helpname(proc) &Editor::proc,#proc,proc##name,proc##ind
#define helpname(proc) &Editor::proc,proc##name,proc##ind
#include "helptext.h"
#include "helpindex.h"

struct help helplist[] = {
#include "helpdata.h"
};
#include "crc.c"
#define castcast (int (Editor::**)(void))
//#define compfunctie(x,y)  (*(castcast x) == *(castcast y))

int compfunctie(char *x,char *y)  {
 	int (Editor::**px)(void)=castcast x;
 	int (Editor::**py)(void)=castcast y;
	return memcmp(px, py, sizeof(int (Editor::*)(void)));
	}
#define hashfunctie(str) block_crc((unsigned char*)str, sizeof(int (Editor::*)(void)))
#define Hash HashHelp
#include "hash.h"
static int helpnr=20+sizeof(helplist)/sizeof(helplist[0]);
static Hash *helphash;
void addhelp(struct help *item) {
	POINTER *ptr;
	if(!helphash)
		return;
	ptr=helphash->itemptr((char *)&(item->proc));
	*ptr=(POINTER*)item;
	}
void inithelphash(void) {
	helphash=new Hash(helpnr);
	}
int fillhelp(void) {
	if(!helphash)
		inithelphash();	
	for(int i=0;i<helpnr;i++) {
		addhelp(&helplist[i]);
		}
	return helpnr;
	}
static int nothing=fillhelp();
#undef Hash
#include "main.h"
#include "getfile.h"

int (Editor::*helpproc)(void)=NULL;
int showhelp( int (Editor::*proc)(void)) {
	struct help *helpitem;
	int startlin=0;
	if(helphash&&(helpitem=(struct help*)helphash->getitem((char *)&proc))) {
		int maxlin=thelines-6;
		int maxscreen= minnum(helpitem->nr,maxlin);
		short *ind=helpitem->ind;
		for(;;) {
		int res=0,i;
		begindialog((maxscreen+4),thecols,4);
			int starty=1,startx=2;
			for(i=startlin;i<(minnum((maxscreen+startlin),helpitem->nr));i++) {
				mvwaddstr(takescr,starty+i-startlin,startx,helpitem->text+(i?ind[i-1]:0));
				}
			  oke((maxscreen+2),2);
			  if(i<helpitem->nr)
				saveact("~Next", maxscreen+2,10);
			  if(startlin)
				saveact("~Prev", maxscreen+2,16);
		  enddialog(res,res);
		  	
			if(res==LONG_MAX)  {
				edits[editfocus]->menuresized();
				wrefresh(edits[editfocus]->editscreen);
				continue;
				}
			if(res==2&&i<helpitem->nr) {
				startlin=i;
				continue;
				}
			if(res>=2&&startlin>0) {
				startlin=maxnum(startlin-maxscreen,0);
				continue;
				}
			break;
			};
		}
	else {
		edits[editfocus]->message("No help");
		}
	return -4;
	}
extern int lasthelp(void) ;
int lasthelp(void) {
	 showhelp(helpproc);
	 edits[editfocus]->editup();
	 return 0;
	}

int makehelp(char *text,int len,int  (Editor::*proc)(void)) {
	if(!helphash)
		inithelphash();	
	int innr=0;	
	short inds[len];
	for(int i=0;i<len;i++) {	
		if(text[i]=='\n') {
			inds[innr++]=i+1;
			text[i]='\0';
			}
		}
	struct 	help *item=myalloc( struct help);
	item->nr=innr+1;
	item->ind=myallocar(short,innr);
	memcpy(item->ind,inds,innr*sizeof(short));
	item->text=text;
	item->proc=proc;
	addhelp(item);
	return 0;
	}



