/*
    LIB - a librarian for compatible OBJ/LIB files
    Copyright (C) 1995,1996  Steffen Kaiser

    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.
*/
/* $RCSfile: LIST.C $
   $Locker: ska $	$Name: v3_2 $	$State: Rel $

	List h‘ndling functions

	The far memory storage manager has a simple interface:
		There is no place in the librarian, where more than one
		module name is retreived by the inList() function.
		When a new name is added to the list, it is duplicated, thus,
		has no connection to the caller no longer.

	Therefore, storing/retreiving the names is simple:
		1) When a name is added, it is duplicated into the far memory.
		2) When a name is retreived, it is duplicated into the heap.
			The name retreived last time will be automaticly freed.

	Because of some quirks, the first far memory block will not
	extend the program's segment, but becomes a new block from the DOS API.
	This also brings on the requirement to explizitly free all the
	far memory blocks, although DOS claims to do it itself.

	All far memory blocks consist of the following structure:
		+0	word	next far block (segment address) (or 0 for none)
		+2	dword	huge pointer to (last byte of block) + 1
		+6	--		buffer area

	Each buffer has the following structure:
		+0	dword	next buffer in the chain (NULL if last)
		+8	dword	length of the data area (may be zero)
		+12	byte	buffer flags (see below)
		+13	--		data area

	The buffer flags will initially set to zero, the following meanings
	describe the state, when the bit is set:
		Bit 0:	Buffer in >usedBuffers< chain.

	There are three lists dealing with the far memory:
		1) The far memory block list chains all blocks together.
			The head is >farBlkHead< and it addresses the segment.
		2) The used buffer list chains all used buffers together.
			The head is >usedBuffers< and it addresses via huge pointers.
		3) The unused buffer list chains all unused buffers together.
			The head is >unusedBuffers< and it addresses via huge pointers.
			The unused buffers fill up a far memory block completely,
			in order all bytes of a block are allocated within a buffer.

	All pointers are normalized in that way that the offset falls into
	the range of 0..127.

	To use both lists and a DWord length seems to be overestimated,
	espacially because only 64KB buffers are in use today. Well, it
	eases the implementation quite much and I hope that there won't
	be wasted too much bytes.

*/

#ifndef _MICROC_
#pragma hdrfile "list.csm"
#include <string.h>
#include <dos.h>
#endif

#include <mcb.h>
#include <suppl.h>
#include <portable.h>

#include "types.h"
#include "lib.h"
#include "list.h"
#include "yerror.h"

#define FARBUF_FIRST 6		/* offest of first buffer in a block */

#define FARBUF_NEXT 0
#define FARBUF_SIZE 4
#define FARBUF_TYPE 8
#define FARBUF_DATA 9

#define FTYPE_USED 1

#ifndef lint
static char const rcsid[] = 
	"$Id: LIST.C 3.3 1999/02/17 05:18:08 ska Rel ska $";
#endif

word farBlkHead = 0;		/* 1st far memory block */
static dword usedBuffers = inM("", 0);
static dword unusedBuffers = inM("", 0);

static word segm_, ofs_;		/* segm:ofs of last retreival via inList() */
struct cmdList *last_ = NULL;	/* the retreival itself */

word Falloc(word paragraphes)
/* allocate a new far memory block via the DOS API */
{	USEREGS
	word segm, largest;

	DB_ENTER("Falloc");
	DB_PRINT("arg", ("paras = %u", paragraphes));

	if(paragraphes == 0)
		paragraphes = 0xffff;

retry:
	_BX = paragraphes;
	_AH = 0x48;				/* DOS API "Allocate memory" */
	geninterrupt(0x21);
	segm = _AX;
	largest = _BX;
	if(_FLAGS & 1) {		/* Allocation failed */
		if(paragraphes == 0xffff) {	/* allocate the largest block */
			paragraphes = largest;
			goto retry;
		}
		DB_RETURN(0);
	}

	pokedd(segm, 0, paragraphes, farBlkHead);
	//pokew(segm, 0, farBlkHead);			/* chain in the allocated block */
	//pokew(segm, 2, paragraphes);	/* return the actual size of the block */
	farBlkHead = segm;

	DB_PRINT("inf", ("allocated %u @%04x", paragraphes, segm));
	DB_RETURN(segm);
}

void Fdealloc(nM(word) segm)
/* free a far memory block allocated via the DOS API */
{	DB_ENTER("Fdealloc");
	DB_PRINT("arg", ("segment = %04x", segm));

	asm {
		mov es, asmName(segm, 4)
		mov ah, 49h	;	/* DOS API "Free Memory" */
		int 21h
	}
	DB_EXIT
}

void Faddp(word *segm, word *ofs, dword iM(*)p)
{	word a, o, s, l;
	s = *segm;
	a = (l = DWP_LO(p)) + (o = *ofs);
	if(a < l || a < o)	/* overflow */
		++s;
	/* normalize new address */
	*ofs = a & 0xf;
	*segm = s + (a >> 4) + DWP_HI(p);
}

word FidBlock(word segm)
/* Identify the far memory block, in which the buffer segm is located */
{	word s, blk;

	assert(segm != 0);

	/* Search the block, which start segment is the largest less then segm */
	s = farBlkHead;
	blk = 0;
	do if(blk < s && s <= segm)
			blk = s;
	while((s = peekw(s, 0)) != 0);

	assert(blk != 0);
	return blk;
}

int Fnext(word *segm, word *ofs)
/* go to the next buffer in the chain;
	Return 0, if last. */
{	return peekdd(*segm, *ofs + FARBUF_NEXT, segm, ofs);
}

int Fvalidate(dword iM(*)chain, word segm, word ofs, dword *prev)
/* Validate the buffer @segm:ofs relative to the chain and update prev
	with the predecessor of segm:ofs, if prev != NULL.

	Return: 0: if not found
*/
{	word s, o;

	if(prev)		/* first in the chain */
		setDWP(prev, 0, 0);

	if((s = DWP_HI(chain)) | (o = DWP_LO(chain))) do {	/* chain not empty */
		if(s == segm && o == ofs) return 1;
		if(prev) setDWP(prev, s, o);
	} while(Fnext(&s, &o));

	return 0;
}

int Fskip(word *segm, word *ofs, dword iM(*)endAddr)
/* Skip to the next buffer in the block; endAddr is the huge address
	immediately behind the far memory block.
	Return:	0: if no predecessor was available. */
{	dword len;

	/* the seg/ofs pairs are pointers, with an offset below 128 */
	peekd(*segm, *ofs + FARBUF_SIZE, len);
	*ofs += FARBUF_DATA;		/* skip the buffer header */
	Faddp(segm, ofs, len);		/* add & normalize pointers */

	return endAddr? *segm < DWP_HI(endAddr)
		 || (*segm == DWP_HI(endAddr) && *ofs < DWP_LO(endAddr))
	 : 1;
}

void *Fdup(word segm, word ofs)
/* Duplicate the first 64KB of the buffer's data area into the heap */
{	void *h;
	int len;

	h = getmem(len = peekw(segm, ofs + FARBUF_SIZE));
	_fmemcpy(TO_FP(h), MK_FP(segm, ofs + FARBUF_DATA), len);
	return h;
}

void FinitBuffer(word segm, word ofs, dword iM(*)len)
/* initialize the buffer header of segm:ofs */
{
	poked(segm, ofs + FARBUF_SIZE, len);
	pokeb(segm, ofs + FARBUF_TYPE, 0);
		/* prepend this buffer to the unused chain */
	poked(segm, ofs + FARBUF_NEXT, unusedBuffers);
	setDW(unusedBuffers, segm, ofs);
}

word FcreatBlk(void)
/* create a new far memory block and return its segment address */
{	word segm, l;
	dword len;

	DB_ENTER("FcreatBlk");

	if((segm = Falloc(0xffff)) == 0)
		error(E_noFarMem);

#ifdef _MICROC_
	longsetu(len, l = peekw(segm, 2));	/* size of alloc'ed block */
	longshln(len, 4);		/* len *= 16 */
	longsubu(len, FARBUF_FIRST + FARBUF_DATA);	/* these bytes are headers */
#else
	len = ((dword)(l = peekw(segm, 2)) << 4) - (FARBUF_FIRST + FARBUF_DATA);
#endif

	DB_PRINT("inf", ("allocated = %u paras", l));

	if(l <= ((FARBUF_DATA + FARBUF_FIRST) >> 4))
	/* not enough bytes to construct one far memory buffer header */
		return FcreatBlk();		/* The little chunk remains allocated, but
									is not chained into the unusedBuffers
									chain. */

	pokedd(segm, 2, l + segm, 0);	/* huge pointer to first byte
			behind the far memory block, thus, end of block marker */

	/* set up a new unused buffer */
	FinitBuffer(segm, FARBUF_FIRST, len);
	DB_RETURN( segm);
}

void FdetachChain(dword iM(*)chain, word segm, word ofs)
/* Detach the buffer @segm:ofs from the chain */
{	dword prev, nxt;

	if(!Fvalidate(chain, segm, ofs, aS(prev)))
	/* validate the buffer address relative to the chain
		& get previous buffer */

		/* validation failed -> NOP */
		return;

	peekd(segm, ofs + FARBUF_NEXT, nxt);

	if(!longtst(prev))		/* first in chain? */
		/* yes, update the chain's head */
		longcpy(chain, nxt);
	else		/* no, update previous buffer in chain */
		poked(DW_HI(prev), DW_LO(prev) + FARBUF_NEXT, nxt);

	poked(segm, ofs + FARBUF_NEXT, 0);	/* mark the buffer as end of chain */
}

void Fdetach(word segm, word ofs)
/* Detach the buffer @segm:ofs from its chain */
{	FdetachChain((peekb(segm, ofs + FARBUF_TYPE) & FTYPE_USED)
		? usedBuffers: unusedBuffers, segm, ofs);
}

void FjoinBlk(word s, word o)
/* join the current block with the immediately following one */
{	dword len, len1;
	word ns, no;			/* successor */

	peekd(ns = s, (no = o) + FARBUF_SIZE, len);
	Fskip(&ns, &no, NULL);		/* advance to the successor */
	Fdetach(ns, no);			/* Detach the successor */
	peekd(ns, no, len1);
	longaddu(len, FARBUF_DATA);			/* size of next buffer's header */
	longadd(len, len1);					/* length of both blocks together */
	poked(s, o, len);
}

void Fsplit(word s, word o, dword iM(*)lenR)
/* split the buffer s:o into two buffer, the first with the length lenR,
	the second with the remaining bytes.
	The second buffer will be attached to the unusedBuffers chain. */
{	dword len;

	peekd(s, o + FARBUF_SIZE, len);
	assert(longcmp_(len, lenR) >= 0);
	longsub(len, lenR);					/* remaining bytes of the buffer */
	longsubu(len, FARBUF_DATA);		/* length of successor's buffer header */
	if(longsgn(len) >= 0) {
		/* buffer large enough to be splitted */
		poked(s, o + FARBUF_SIZE, lenR);	/* first buffer is of this length */
		Fskip(&s, &o, 0);					/* s:o := second buffer */
		FinitBuffer(s, o, len);
	}
}

int Ffindfree(word *segm, word *ofs, dword iM(*)lenR)
/* search for and return, if found, a buffer in the unusedBuffers chain
	with at least the requested length */
{	word s, o;
	dword l, len;

	DB_ENTER("Ffindfree");

	longcpy(len, lenR);
	longaddu(len, FARBUF_DATA);		/* the needed bytes for the header */

	DB_PRINT("arg", ("req len = %ld", len));

	if((s = DW_HI(unusedBuffers)) | (o = DW_LO(unusedBuffers))) do {
		peekd(s, o + FARBUF_SIZE, l);
		DB_PRINT("inf", ("found len = %ld", l));
		if(longcmp_(l, len) >= 0) {	/* buffer large enough */
			*segm = s;
			*ofs = o;
			DB_PRINT("inf", ("found @%04x:%04x", *segm, *ofs));
			DB_RETURN( 1);
		}
	} while(Fnext(&s, &o));
	DB_RETURN( 0);
}

void FgetBuffer(word *segm, word *ofs, dword iM(*)len)
/* get a buffer with the length len. If failed, terminate with error */
{	while(!Ffindfree(segm, ofs, len)) {	/* the current chain of unused
			buffer have no buffer greater than or equal to the requested
			length; that means, a new block must be allocated */
		FcreatBlk();			/* allocate next block */
	}		/* this loop breaks, if a buffer was found, otherwise
				the program terminates with an error */
}

void Fappend(void *buf, unsigned len)
/* append buf behind the last buffer */
{	dword last;
	word s, o;		/* far memory buffer of requested length */

	DB_ENTER("Fappend");
	DB_PRINT("arg", ("length = %u", len));

	assert(len <= 65535 - FARBUF_DATA);

	longsetu(last, len);
	FgetBuffer(&s, &o, last);		/* get a buffer large enough */
	Fsplit(s, o, last);				/* split the buffer to the requested len */
	Fdetach(s, o);					/* detach buffer from the unused chain */

	/* validating 0:0 causes that no match can be made and, thus, last
		becomes the last buffer in the chain */
	Fvalidate(usedBuffers, 0, 0, aS(last));
	if(!longtst(last))
		setDW(usedBuffers, s, o);	/* none in the chain */
	else pokedd(DW_HI(last), DW_LO(last), s, o);

	pokeb(s, o + FARBUF_TYPE, FTYPE_USED);

	_fmemcpy(MK_FP(s, o + FARBUF_DATA), TO_FP(buf), len);

	DB_EXIT
}

void Fdelete(word segm, word ofs)
/* Delete the buffer.
	Deleting will detach the buffer from the NEXT references.
	Then the predessor of the buffer within the block is determined and,
	if this buffer is unused, both are joined.
	Then the successor is determined and, if this buffer is unused,
	both are joined. */
{	dword end;
	word s, o, ns, no;

	if(segm == segm_ && ofs == ofs_) {
		/* the last retreival is about to be deleted */
		U_free(last_);
		last_ = NULL;
	}

	Fdetach(segm, ofs);

/* Search predecessor within the block */
	ns = FidBlock(segm);		/* identify block of the buffer */
	peekd(ns, 2, end);			/* end address for Fskip() */
	for(no = FARBUF_FIRST, s = o = 0 ; ns != segm || no != ofs;) {
		/* skip to next buffer */
		assert(ns > s || (ns == s && no > o));
		s = ns;
		o = no;
		assert(s < segm || (s == segm && o < ofs));
		if(!Fskip(&ns, &no, end))
			assert(Fskip(&ns, &no,end) != 0);
	}
	if((s || o) && !(peekb(s, o + FARBUF_TYPE) & FTYPE_USED))
	/* unused predecessor found, join them */
		FjoinBlk(segm = s, ofs = o);
	if(Fskip(&s, &o, end) && !(peekb(s, o + FARBUF_TYPE) & FTYPE_USED))
	/* unused successor found, join them */
		FjoinBlk(segm, ofs);
}

static void Fupdate_(const word segm, const word ofs, const void *buffer)
/* Update the data area. The entry must not have been
	changed in its length! */
{	
	_fmemcpy(MK_FP(segm, ofs + FARBUF_DATA), TO_FP(buffer)
	 , peekw(segm, ofs + FARBUF_SIZE));
}




void clrList(void)
/* clear the list head, free all entries & NULL the head */
{	DB_ENTER("clrList");

	/* When the complete list is free'ed, there is no "last retreived" */
	U_free(last_);
	last_ = NULL;

	if((segm_ = farBlkHead) != 0) {
		do {
			ofs_ = peekw(segm_, 0);
			Fdealloc(segm_);
		} while((segm_ = ofs_) != 0);
		farBlkHead = 0;
	}
	longclr(usedBuffers);
	longclr(unusedBuffers);
	chkHeap()

	DB_EXIT
}


unsigned matchFnam(char *nam1, char *nam2)
/*	Match both names.
	Return:	0: exact match, even wildcards are equal
			1: wildcard match, nam1 superceeds nam2
			2: wildcard match, nam2 superceeds nam1
			3: wildcard match, at least one wildcard in each name matched
				a non-wildcard in the other name.
			4: no match at all
*/
{	char *p, *h;
	FLAG8 c1, c2;
	int r;

	p = namePart(nam1);
	h = namePart(nam2);
	r = 0;

	do {
		c2 = *++h;
		if(((c1 = *++p) == '.' || c1 == NUL) && (c2 == '.' || c2 == NUL))
			return r;
		if(c1 == '*') {
			if(c2 == '*')	/* exact match of wildcards */
				return r;
			return r | 1;
		}
		if(c2 == '*') return r | 2;
	} while((c1 == c2 || (c1 == '?' && (r |= 1)) || (c2 == '?' && (r |= 2))));

	return 4;	/* no match at all */
}

static struct cmdList *inList_(int flags, char *s
, word *segm, word *ofs, struct cmdList **Xlast)
/* check if the name s is in the list with at least one of the flags
	set
	*Xlast is free'ed before the search process starts.
	The values of segm, ofs,& Xlast are updated with the current found
	far buffer; otherwise, *Xlast becomes NULL.
*/
{	struct cmdList *last;

	DB_ENTER("inList_");
	DB_PRINT("arg", ("flags = %x; name = %s", flags, s));

	U_free(last = *Xlast);

   	chkHeap()
	if(s && *s
	 && ((*segm = DW_HI(usedBuffers)) | (*ofs = DW_LO(usedBuffers))) != 0) {
		do if((last = Fdup(*segm, *ofs)) != NULL) {	/* used block? */

			if((last->fl_flags & flags) && matchFnam(s, last->fl_name) < 4)
				DB_RETURN( *Xlast = last);

			U_free(last);

		} while(Fnext(segm, ofs));
	}
	DB_RETURN( *Xlast = NULL);
}

#ifdef _MICROC_
void forEachList(int fct)
#else
void forEachList(int (*fct)(struct cmdList *))
#endif
{	struct cmdList *act;
	word segm, ofs;

	assert(fct);

	chkHeap()
	segm = DW_HI(usedBuffers);
	ofs = DW_LO(usedBuffers);

	if((segm | ofs) != 0) do {
		if((act = Fdup(segm, ofs)) != NULL) {
			if(fct(act))			/* delete act entry */
				Fdelete(segm, ofs);
			else Fupdate_(segm, ofs, act);	/* update the maybe changed item */
			U_free(act);
		}
	} while(Fnext(&segm, &ofs));

	chkHeap()
}


void appList(int flags, char *s, int upcase)
/* append a new item to the list */
{	struct cmdList *act;
	word segm, ofs;
	int len;

	DB_ENTER("appList");

	if(!s || !*s)
		DB_EXIT

	DB_PRINT("arg", ("flags = %x; name = %s", flags, s));

	chkHeap()
	act = NULL;
	upCaseFct(upcase, s);
	/* perhaps this thing is already in the list? */
	if(!(flags & CMD_THROUGH)			/* request a physically new entry */
	 && inList_(CMD_ALL, s, &segm, &ofs, &act) != NULL) {
	 /* only alter the flags */
		if(matchFnam(act->fl_name, s))		/* no exact match */
			warning(W_globMatch, act->fl_name, s);
		else {
			act->fl_flags |= flags;
			Fupdate_(segm, ofs, act);
		}
	}
	else {
		act = getmem(len = sizeof(struct cmdList) + strlen(s));
		strcpy(act->fl_name, s);
		act->fl_flags = flags;

		chkHeap()

		Fappend(act, len);
		U_free(act);
	}

	chkHeap()

	DB_EXIT
}

struct cmdList *inList(int flags, char *s, int upcase)
/* Check, if s with at least one of the flags set is available.
	Preserves the last retreivial, to be updated via Fupdate() */
{	upCaseFct(upcase, s);
	return inList_(flags, s, &segm_, &ofs_, &last_);
}

void Fupdate(void)
{	if(last_) Fupdate_(segm_, ofs_, last_); }
