/*
 * scrp.c
 *
 * Zugriff auf das GEM-Klemmbrett.
*/

#include "intern.h"

#ifdef __MINT__
#define DTA	_DTA
#endif

static char	dir[80] = "";

int get_scrapdir(char *scrap)
{

	if (dir[0] == EOS)
	{
		scrp_read(dir);
		if (dir[0] != EOS)
		{
			int	i;
			i = (int)strlen(dir);
			if (dir[i - 1] != '\\')
			{
				dir[i] = '\\';
				dir[i + 1] = EOS;
			}
		}
	}
	strcpy(scrap, dir);
	return (scrap[0] != EOS);
}

void scrap_clear(void)
{
	char		scrap[80], path[80];
	DTA		dta, *old_dta;
	int		ok;

	if (get_scrapdir(scrap))
	{
		strcpy(path, scrap);
		strcat(path, "scrap.*");
		old_dta = (DTA *)Fgetdta ();
		Fsetdta(&dta);

		ok = (Fsfirst (path, 0) == 0);
		while (ok)
		{
			strcpy(path, scrap);
#ifdef __MINT__
			strcat(path, dta.dta_name);
#else
			strcat(path, dta.d_fname);
#endif
			Fdelete(path);
			ok = (Fsnext () == 0);
		}
		Fsetdta(old_dta);
	}
}

char *scrap_rtxt(char *buf, long *len, long maxlen)
{
	char	path[80];
	int	datei;

	if (get_scrapdir(path))
	{
		strcat(path, "scrap.txt");
		if ((datei = (int)Fopen(path, 0)) >= 0)
		{
			*len = Fread(datei, maxlen, buf);
			Fclose(datei);
			buf[*len] = '\0';
			return buf;
		}
	}
	return NULL;
}

void scrap_wtxt(char *buf)
{
	char	path[150];
	int	datei;

  	if (get_scrapdir(path))
  	{
		scrap_clear();
	 	strcat (path, "scrap.txt");

	 	if ((datei = (int)Fcreate(path, 0)) >= 0)
	 	{
			Fwrite(datei, strlen(buf), buf);
			Fclose(datei);
	 	}
  	}
}
