/*
    Robot Interface Remote Client
    (C) 2006 Jason Hunt
    nulluser@gmail.com

    file: config.cpp
*/

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

#include "config.h"
#include "network.h"
#include "types.h"
#include "display.h"




/* gets the nextr string in a line, up to a space or endline */
void get_next_string(char *line, unsigned int &i, char *str)
{
    int done_str = 0;   // flag for done with string
    
    unsigned int s = 0; // index into target string

    // eat white space at front of line
    while ((line[i] == ' ' || line[i] == '\t') && i < LINE_MAX) i++;
  
    while (!done_str && i < LINE_MAX)
    {
        char ch = line[i++];
                               
        if (ch == ' ' || ch == '\t' ||  ch == 0)
            done_str = 1;
        else
            str[s++] = ch;
    }

    str[s] = 0;   // null terminate
}
/* end of get_next_string */


/* parse a config line for commands */
void parse_line(char *line)
{
    unsigned int index = 0;
    char str[LINE_MAX];
    
    get_next_string(line, index, str);

    if (!strcmp("server_hostname", str))                   // set hostname
    {
        // read hostname from line
        get_next_string(line, index, str);
        if (strlen(str))
            strcpy(server_hostname, str);
    }  else
    if (!strcmp("server_port", str))              // trigger threshold
    {
        // read hostname from line
        get_next_string(line, index, str);
        if (strlen(str))
            server_port = atoi(str);
    } 
}
/* end of parse_line */


/* loads configuration values from config file */
void load_config(char *config_filename)
{
    FILE *f = fopen(config_filename, "rt");
    
    if (!f)
    {
        add_line("load_config: Unable to load config file");
        return;
    }    

    // load each line
    while (!feof(f))
    {
        char line[LINE_MAX];    // temperary line

        unsigned int i = 0;     // index
        
        int line_done = 0;      // line end
        
        // read line
        while (i < LINE_MAX && !line_done)
        {
            char ch = fgetc(f);             // get char from file

            // eat rest of line
            if (ch == '#')
            {
                while (ch != 0x0a && ch != 0x0d && !feof(f))  ch = fgetc(f);
            } else    
    
            // limit check
            if (ch == 0x0d || ch == 0x0a || feof(f)) line_done = 1; else
                line[i++] = ch;
        }            
               
        line[i] = 0; // null terminate
        
        // check for blank line
        if (i > 0)
            parse_line(line);
    }    
    
    fclose(f);
}
/* end of load config */



