#include "cl.h"

int config_file( char *file ) {
    char str[ STR_MAX ];
    FILE *fcfg = fopen( file, "rt" );

    if ( fcfg != NULL ) {
        while( fgets( str, STR_MAX, fcfg ) != NULL )
            config_str( str );
        fclose( fcfg );
        return 1;
    }
    else
        return 0;
}

void config_str( char *s ) {
    char arg[ STR_MAX ];
    int  len;

    for ( len = 0; *s; s++ ) {
        if ( *s == ' ' || *s == '\t' || *s == '\n' ) {
            if ( len > 0 ) {
                arg[ len ] = '\0';
                config_arg( arg );
            }
            arg[ len = 0 ] = '\0';
        }
        else {
            arg[ len++ ] = *s;
        }
    }
    if ( len > 0 ) {
        arg[ len ] = '\0';
        config_arg( arg );
    }
}

#define is_arg(s) \
    (  ( (s)[0] == '-' ) || ( (s)[0] == '+' ) || ( (s)[0] == '/' )  )
#define is_rsp(s) \
    ( (s)[0] == '@' )

void config_arg( char *arg ) {
    if ( is_arg(arg) )
        get_param( arg );
    else if ( is_rsp(arg) ) {
        if (! config_file( arg + 1 ) ) {
            fprintf( stderr, "File '%s' not found !", arg + 1 );
            exit(-1);
        }
    }
    else
        get_file( arg );
}
