#include <mem.h>
#include <string.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#include <dos.h>
#include <fcntl.h>
#include <io.h>

#include "iw.h"
#include "list.h"
#include "patch.h"

#define TBUFLEN 80
#define IWU_VENDOR_BUFLEN 80

int rom_get_patch_config(char *romcfg)
{
    char buf[TBUFLEN];
    char vendor_info[IWU_VENDOR_BUFLEN];
    char default_vendor[IWU_VENDOR_BUFLEN];
    char *cp;
    struct patch_lib *pl, *npl;
    int n;

    if (plib) {
	for (pl=plib; pl != NULL; pl = npl) {
	    npl = pl->next;
	    iwu_fff_unload(pl);
	    free(pl);
	}
	plib=NULL;
    }
    /* example: [vendors] */
    /* example: default=forte */
    iwu_get_profile_string("vendors","default","",(char RFAR *)default_vendor,IWU_VENDOR_BUFLEN,romcfg);
    if (strcmp(default_vendor, "") == 0) {
	return(IWU_PATCH_NO_DEFAULT_VENDOR);
    }
    /* example: [vendors] */
    /* example: forte=gm.fff */
    iwu_get_profile_string("vendors",default_vendor,"",buf,TBUFLEN,romcfg);
    if (strcmp(buf, "") == 0) {
	return(IWU_PATCH_NO_VENDOR_PATCHES);
    }
    /* get list of patch libraries */
    cp = strtok(buf, ",");
    while (cp) {
	while (*cp == ' ' || *cp == '\t') cp++;
	pl = (struct patch_lib *)malloc(sizeof(struct patch_lib));
	if (pl == NULL) {
	    return(IWU_PATCH_NOMEM);
	}
	strncpy(pl->patch_filename, cp, IWU_PATCH_FILENAME_LEN);
	pl->next = plib;
	plib = pl;
	cp = strtok(NULL, ",");
    }
    /* get directories for patch libraries */
    strcpy(vendor_info, "vendor ");
    strcat(vendor_info, default_vendor);
    for (pl=plib; pl != NULL; pl = pl->next) {
	/* example: [vendor forte] */
	/* example: gm.fff=c:\forte\patches */
	iwu_get_profile_string(vendor_info,pl->patch_filename,"",pl->patch_dir,IWU_PATCH_DIR_LEN,romcfg);
	if (strcmp(pl->patch_dir, "") == 0) {
	    return(IWU_PATCH_NO_DIR);
	} else {
	    n = strlen(pl->patch_dir)-1;
	    if (pl->patch_dir[n] != '\\') {
		strcat(pl->patch_dir, "\\");
	    }
	}
    }
    return(iwu_fff_load(0));
}
