/*
	Combat Team 2 - SoundBlaster variables save utility
	Made by Ismo Horppu on 1996 - 1997
*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "blaster.h"

int GetNum (int index, int many)
{
	int copy;
	unsigned int multiplier = 1;
	char val;
	int cnt;
	
	if (many > 10) return -1;
	
	for (cnt = 0; cnt < many - 1; cnt++){
		multiplier *= 16;
	}
	
	char *conv[16] = {
		"0",
		"1",
		"2",
		"3",
		"4",
		"5",
		"6",
		"7",
		"8",
		"9",
		"A",
		"B",
		"C",
		"D",
		"E",
		"F"
	};
	
	copy = 0;
	value = 0;
	
	while (many > 0){
		for (cnt = 0 ; cnt < 16; cnt++){
			val = conv[cnt][0];
			
			if (val == BLASTER[index]){
				value += cnt * multiplier;
				cnt = 16;	
			}
		}
		
		many--;
		copy++;
		index++;
		multiplier /= 16;
	}
	
	return 0;
}

int FindChar (char c)
{
	int len;
	int seek = 0;
	
	len = strlen (BLASTER);
	if (len < 1) return -1;
	
	for (seek = 0; seek < len; seek++)
	{
		if (BLASTER[seek] == c){
			//printf ("found at %d\n", seek);
			return seek;
		}
	}
	
	return -1;
}

int DetectBLASTER (void)
{
	int pos;
	
	if ((BLASTER = getenv ("BLASTER")) == NULL) return -10;
	BLASTER = strupr (BLASTER);
	
//	printf ("%s\n", BLASTER);
	
	pos = FindChar ('A');
	if (pos == -1) return pos;
	GetNum (pos + 1, 3);
	printf ("BASE %xH\n", value);
	base = value;
	
	pos = FindChar ('I');
	
	if (pos == -1){
		return pos;
	}
	
	GetNum (pos + 1, 1);
	printf ("IRQ %xH\n", value);
	irq = value;	
	
	pos = FindChar ('D');
	
	if (pos == -1){
		return pos;
	}
	
	GetNum (pos + 1, 1);
	printf ("DMA8 %xH\n", value);
	dma8 = value;	
	
	pos = FindChar ('H');
	
	if (pos == -1){
		value = dma8;
		// return pos;
	}

	else{	
		GetNum (pos + 1, 1);
	}
	
	printf ("DMA16 %xH\n", value);
	dma16 = value;	
		
	pos = FindChar ('T');
	
	if (pos == -1){
		return pos;
	}
	
	GetNum (pos + 1, 1);
	printf ("TYPE %xH\n", value);
	type = value;	
	return 0;
}

int main (void)
{
	FILE *f;
	int stat;
	unsigned char SB = 1;
		
	printf ("Seeking for BLASTER environment variable...\n");	
	stat = DetectBLASTER ();
	
	if (stat == -1){
		printf ("Invalid BLASTER variable !\n");
		return -1;
	}

	if (stat == -10){
		printf ("No BLASTER variable found\n");
		SB = 0;
	}
	
	else printf ("BLASTER variable found !\n");
	
	f = fopen ("config.ct2", "r+b");

	fseek (f, 15, SEEK_SET);
	
	fputc (SB, f);
	fwrite (&base, 1, 2, f);
	fwrite (&dma8, 1, 1, f);
	fwrite (&dma16, 1, 1, f);
	fwrite (&irq, 1, 1, f);
	fwrite (&type, 1, 1, f);
	fclose (f);
	return 0;
}
