/* mapsetup.c -- Miles V. Aronnax
 *   Functions to read, store and return values from the mapping table.
 */

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

// Structure for storing the parsed mapping table.
struct nucleus_mapping_table {
	char nucleus_name[32];
	float ground_state_energy;
	char storage_location[200];
} numap[3];

// Get nucleus name
void mapget_name(int *nucounter, char *name) {
	int idx = *nucounter - 1;
	strcpy(name, numap[idx].nucleus_name);
}

// Get absolute ground state energy
void mapget_eabs(int *nucounter, float *eabs) {
	int idx = *nucounter - 1;
	*eabs = numap[idx].ground_state_energy;
}

// Get nucleus storage folder
void mapget_nloc(int *nucounter, char *nloc) {
	int idx = *nucounter - 1;
	strcpy(nloc, numap[idx].storage_location);
}

// Read values from a table row (line) and load into numap.
void parse_table_row(int idx, char *line) {
	char *afield;
	afield = strtok(line, "\t"); // first column: number
	strcpy( numap[idx].nucleus_name, strtok(NULL, "\t") );
	numap[idx].ground_state_energy = atof(strtok(NULL, "\t"));
	strcpy( numap[idx].storage_location, strtok(NULL, "\n") );
	printf("   Stored: {%s, %f, %s} --> numap[%i]\n",
		numap[idx].nucleus_name,
		numap[idx].ground_state_energy,
		numap[idx].storage_location,
		idx);
}

// Read values from mapping table fspec into array numap.
void read_mapping_table(char *fspec) {
	printf("  In read_mapping_table()...\n");
	int idx=0;
	char line[100];
	FILE *mapfile;

	// Open the mapping file.
	printf("  fopen(%s, r)\n", fspec);
	mapfile = fopen(fspec, "r");
	if( mapfile==NULL ) { printf("Couldn't open mapfile.\n"); exit(0);}

	// Read the file one line at a time.
	while(!feof(mapfile)) {
		fgets(line, 100, mapfile);
		//printf("line=[%s]", line);
		if( line != "" && strlen(line) > 5 ) {
			printf("  Parsing table row %i...\n", idx);
			parse_table_row(idx, line);
			idx++;
		}
	}

	// Close file and exit subroutine.
	fclose(mapfile);
}

