/* populateLocale.c
 * Called by gddcalc when the user chooses "locale" from the top menu.
 * If a preferences file exists the persistant geographic values in that
 * file are assigned to the active variable set, and are copied into the
 * dialog window.
 */

#include <gtk/gtk.h>
#include <gtk/gtkx.h>
#include "gddcalc.h"
#include "solpos.h"

float getDescriptor(char *);                         // prototype

void populateLocale() {

	size_t lth = 128;
	char *bfr = malloc(lth);
	FILE *fp;
	
	fp = fopen("locale.txt", "r");

/* If a locale has been set, read its contents into active variables */

	if (fp == NULL) {haveprefs = 0;}
	else
	{
		haveprefs = 1;
		while (fgets(bfr, lth, fp))
		{
			if (bfr[0] == 'l' && bfr[1] == 'a' && bfr[2] == 't')
				active_latitude = getDescriptor(bfr);
			else if (bfr[0] == 'l' && bfr[1] == 'o' && bfr[2] == 'n')
				active_longitude = getDescriptor(bfr);
			else if (bfr[0] == 'e' && bfr[1] == 'l' && bfr[2] == 'e')
				active_elev = getDescriptor(bfr);
			else if (bfr[0] == 'a' && bfr[1] == 's' && bfr[2] == 'p')
				active_aspect = getDescriptor(bfr);
			else if (bfr[0] == 't' && bfr[1] == 'i' && bfr[2] == 'l')
				active_tilt = getDescriptor(bfr);
		}
		fclose(fp);   
	}

/* Intialize the remaining active variables, which are defined and
 * stored in gddcalc.h. Put in values for noon at Eugene.
 */
	active_temp = 15;
	active_press = 1006;
	active_timezone = -8;
	active_hour = 12;
	active_minute = 0;
	active_second = 0;
	active_dt = 1;

 /* If there is a preferred locale (i.e., if locale.txt exists) we
  * copy the active variables into them.
  */
 
	gtk_entry_set_has_frame (GTK_ENTRY(locale_entry_lat), TRUE);

	if (haveprefs) {
		sprintf(bfr, "%8.4f", active_latitude); 
		gtk_entry_set_text (GTK_ENTRY (locale_entry_lat), (gchar*) bfr);
		sprintf(bfr, "%8.4f", active_longitude); 
		gtk_entry_set_text (GTK_ENTRY (locale_entry_lon), (gchar*) bfr);
		sprintf(bfr, "%8.1f", active_elev); 
		gtk_entry_set_text (GTK_ENTRY (locale_entry_elev), (gchar*) bfr);
		sprintf(bfr, "%8.1f", active_aspect); 
		gtk_entry_set_text (GTK_ENTRY (locale_entry_aspect), (gchar*) bfr);
		sprintf(bfr, "%8.1f", active_tilt); 
		gtk_entry_set_text (GTK_ENTRY (locale_entry_tilt), (gchar*) bfr);
	}
	free(bfr);
}
