// Part of the LyX project
// 1996

#include "config.h"

#include "forms.h"

#include "lastfiles.h"
#include "definitions.h"
#include "symgen.h"
#include "paths.h"

const char *LastFiles::GetFileName(int nr)
{
   return (const char*)files[nr-1];
}

void LastFiles::ReadFile(const char *filename) 
{
	// we will not complain if we can't find filename nor will
	// we issue a warning. Lgb.
	
	SymbolGenerator sgen;
	sgen.inFileName(filename);
	sgen.getReady();

	if (StringEqual(sgen.currentSymbol(),"file1")){
		sgen.stepSymbol();
		files[0] = StringCopy(sgen.currentSymbol());
		sgen.stepSymbol();
	}
	if (StringEqual(sgen.currentSymbol(),"file2")){
		sgen.stepSymbol();
		files[1] = StringCopy(sgen.currentSymbol());
		sgen.stepSymbol();
	}
	if (StringEqual(sgen.currentSymbol(),"file3")){
		sgen.stepSymbol();
		files[2] = StringCopy(sgen.currentSymbol());
		sgen.stepSymbol();
	}
	if (StringEqual(sgen.currentSymbol(),"file4")){
		sgen.stepSymbol();
		files[3] = StringCopy(sgen.currentSymbol());
		sgen.stepSymbol();
	}

	sgen.terminate();
}

void LastFiles::WriteFile(const char *filename) 
{
   FILE *fd;
   if ((fd=fopen(filename,"w"))) 
      {
	 if (files[0])
	   fprintf(fd,"file1 %s\n",files[0]);
	 if (files[1])
	   fprintf(fd,"file2 %s\n",files[1]);
	 if (files[2])
	   fprintf(fd,"file3 %s\n",files[2]);
	 if (files[3])
	   fprintf(fd,"file4 %s\n",files[3]);
	 fclose(fd);
      } else
	 fprintf(stderr,"Warning: unable to print LastFiles `%s'!\n",filename);
}
   
LastFiles::LastFiles(const char *filename) 
{
   int n=0;
   for(n=0;n<4;n++) files[n]= NULL;
   ReadFile(filename);
}

void LastFiles::newfile(const char *file) 
{
	int n=0;
	for(n=0;n<3;n++) if (StringEqual(file,files[n])) break;
	// always move the most recent loaded file to the top of the
	// list, even if it exists in the list already.
	if (files[n])
	  delete files[n];
	for(int i=n;i>=1;i--)
	  files[i]=files[i-1];
	files[0]=StringCopy(file);
}

void LastFiles::MakeMenu(int m) 
{
	int n;
 	char * relbuf;
	for (n=0;n<=3;n++) {
		if (files[n]) {
 		  relbuf = MakeDisplayPath (NULL, files [n]);
#if !defined(__GNUG__)
		  char tmp[256];
#else
		  char tmp[strlen(relbuf)+5];
#endif
			sprintf(tmp,"%d. %s",n+1,relbuf);
			fl_addtopup(m,tmp);
 			delete relbuf;
		}
	}
}

// the global lastfiles pointer
LastFiles *lastfiles;
