/** \file
 *
 *  Contains the ParameterHandler class implementation.
 *
 *  Copyright (c) 2007,2008,2009 MBARI
 *  MBARI Proprietary Information.  All Rights Reserved
 */

#include "ParameterHandler.h"
#include <cctype>
#include <math.h>
#include <cstdlib>
#include <cstring>

size_t ParameterHandler::ChopParameterList( char* list )
{
    size_t listLength = strlen( list );
    char* strTokPtr;
    char * pch = strtok_r( list, "&", &strTokPtr );
    while( pch != NULL )
    {
        pch = strtok_r( NULL, "&", &strTokPtr );
    }
    return listLength;
}

char* ParameterHandler::GetParameter( const char* name,
                                      const char* list, int listLength )
{
    int nameLength = strlen( name );
    int checks = listLength - nameLength;
    if( checks <= 0 ) return NULL;
    for( int i = 0;  i < checks; ++i )
    {
        if( ( 0 == *list || 0 == i )
                && !memcmp( list + ( 0 == i ? 0 : 1 ), name, nameLength )
                && list[nameLength + ( 0 == i ? 0 : 1 )] == '=' )
        {
            return ( char* )list + nameLength + ( 0 == i ? 1 : 2 );
        }
        ++list;
    }
    return NULL;
}

double ParameterHandler::AsDouble( const char* name,
                                   const char* list, int listLength )
{
    char* parameter = GetParameter( name, list, listLength );
    if( NULL == parameter || !isdigit( *parameter ) )
    {
        return nan( "" );
    }
    return atof( parameter );
}

bool ParameterHandler::GetDouble( double& valueToSet, const char* name,
                                  const char* list, int listLength )
{
    char* parameter = GetParameter( name, list, listLength );
    if( NULL == parameter )
    {
        return false;
    }
    valueToSet = atof( parameter );
    return true;
}
