#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stddef.h>

char* get_values(char* file){

	FILE *f;
    char c;
	char* result;
    f=fopen(file,"rt");
	if (f==NULL) return result;
	int size = 1024;
	char* values = malloc(sizeof(char)*size);
	//char values[4096];
	int var = 0;
	int end = 0;
	size = 0;
    while((c=fgetc(f))!=EOF){
		if (c!=' ' && c!='\n' && c!='\t'){
			if (var!=0)
				values[size] = c;
			size++;
			end = 1;
		} else {
			if (c=='\n'){
				var=1;
				values[size]='\0';
				size = 0;
				end = 0;
			}
			switch(end){
				case 1:
					if (var!=0)
						values[size] = '%';
					size++;
					end = 0;
				break;
				default:
					end = 0;
				break;
	
			}
		}
    }
	//result=(char*)malloc(4096); 
	//strcpy(result,values);
    fclose(f);
    //return result;
	return values;

}


void printFileDebug(char* line){

	FILE *pfile = NULL;
	char *filename = "C:\\out.txt";
	//char *filename = "F:\\Wokspace\\SDLPSModels\\buildingSim\\out.txt";

	char cwd[1024];
	if (getcwd(cwd, sizeof(cwd)) != NULL)
		fprintf(stdout, "Current working dir: %s\n", cwd);
      

	pfile = fopen(filename, "w");
	if(pfile == NULL)
	{
		printf("Error opening %s for writing. Program terminated.", filename);
	}
	fputs(cwd, pfile);
	fputs(line, pfile);

}

double recoverOptiValue(char* PM, int position){

	char* path;
	char* result;
	char* val;
	int count = 0;
	char* pathA;
	char * copy = malloc(strlen(PM) + 1); 
	strcpy(copy, PM);
	size_t message_len = strlen(PM)+11;
	path = malloc(message_len*sizeof(char));
	memset(path, 0, message_len*sizeof(char));
	pathA = strtok(copy,"'");
	
	strcpy(path,pathA);
	path= strcat(path,"\\optim.out");
	result = get_values(path);
	if (result==NULL) return -1;
	val = strtok(result,"%");
	while (val!=NULL)
	{
		if(count==position){
			return atof(val);
		}
		count++;
		val = strtok(NULL,"%");
	}
	
	return -1;

}

