#include <windows.h>
#include <commctrl.h>
#include <stdio.h>
#include "header.h"

extern HMENU hMenuMain,hMRUSubMenu ;
DWINFO *mrulist[MAX_MRU] ;
static int MRUOffset ;


void MRUToMenu(void)
{
	MENUITEMINFO mi ;
	char buf[256] ;
	int currentoffset,i ;
	hMRUSubMenu = GetSubMenu(hMenuMain,0) ;
	currentoffset = GetMenuItemCount(hMRUSubMenu) ;
	memset(&mi,0,sizeof(mi)) ;
	if (MRUOffset == 0) {
		MRUOffset = ++currentoffset ;
		mi.cbSize = sizeof(mi) ;
		mi.fMask = MIIM_TYPE ;
		mi.fType = MFT_SEPARATOR ;
		InsertMenuItem(hMRUSubMenu,MRUOffset-1,1,&mi) ;
	}
	mi.cbSize = sizeof(mi) ;
	mi.fMask = MIIM_ID |MIIM_TYPE | MIIM_DATA;
	mi.fType = MFT_STRING ;
	
	for (i=0; i < MAX_MRU; i++) {
		mi.wID = i + ID_MRU_LIST ;
		mi.dwTypeData = buf ;
		if (mrulist[i]) {
			sprintf(buf,"%d: %s",i+1,mrulist[i]->dwTitle) ;
			if (i + MRUOffset >= currentoffset )
				InsertMenuItem(hMRUSubMenu, MRUOffset + i, TRUE, &mi) ;
			else
				SetMenuItemInfo(hMRUSubMenu, mi.wID, FALSE, &mi) ;
		}
	}
}
void MRUToProfile(void)
{
	char key[20], buf[256] ;
	int i = 0 ;
	for (i= 0 ; i < MAX_MRU; i++)
		if (mrulist[i]) {
			sprintf(key,"MRU%d",i) ;
			sprintf(buf,"%s;%s",mrulist[i]->dwName,mrulist[i]->dwTitle) ;
			StringToProfile(key,buf) ;
		}
}
void ProfileToMRU(void)
{
	int i;
	char key[50],*buf ;
	for (i=0; i < MAX_MRU; i++)
		if (mrulist[i]) {
			free(mrulist[i]) ;
			mrulist[i] = 0 ;
		}
	for (i=0; i < MAX_MRU; i++) {
      sprintf(key,"MRU%d",i) ;
		buf = ProfileToString(key,"") ;
		if (buf[0]) {
			DWINFO *x = malloc(sizeof(DWINFO)) ;
			int j = 0 ;
			memset(x,0,sizeof(*x)) ;
			
			while (*buf && *buf != ';')
				x->dwName[j++] = *buf++ ;
			j = 0 ;
			if (*buf)
				buf++ ;
			while (*buf)
				x->dwTitle[j++] = *buf++ ;
			mrulist[i] = x ;
		}
	}
		
}
void InsertMRU(DWINFO *data)
{
	int i;
	DWINFO *x = malloc(sizeof(DWINFO)) ;
	if (!x)
		return ;
	memcpy(x,data,sizeof(DWINFO)) ;
	for (i=0; i < MAX_MRU; i++)
		if (mrulist[i] && !xstricmpz(x->dwName,mrulist[i]->dwName)) {
			if (i == 0)
				return ;
			free(mrulist[i]) ;
			memmove(mrulist+1,mrulist, i * sizeof(DWINFO *)) ;
			mrulist[0] = x ;
			return ;
		}
	if (mrulist[MAX_MRU-1])
		free(mrulist[MAX_MRU-1]) ;
	memmove(mrulist+1,mrulist,(MAX_MRU - 1) * sizeof(DWINFO *)) ;
	mrulist[0] = x ;
}