/*******************************************************************************
 * JMMC project ( http://www.jmmc.fr ) - Copyright (C) CNRS.
 ******************************************************************************/
/**
 * @file
 * Useful functions related to string.
 */

#define _POSIX_SOURCE 1

/*
 * System Headers
 */
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include "fitsio.h"

/*
 * Local Headers
 */
#include "amdlib.h"
#include "amdlibProtected.h"

/*
 * Protected functions
 */

/**
 * Removes the leading and trailing blanks
 *
 * This function set removes the leading and trailing blanks. The function
 * strips these off using the same character buffer for storing the processed
 * string. The string must be NULL terminated.
 *
 * @param str string to process.
 */
void amdlibStripBlanks(char *str)
{
    char  *chrPtr;
    char  *strPtr;

    strPtr = str;
    chrPtr = str;

    /* Skip possible blanks  */
    while ((*chrPtr != '\0') && (*chrPtr == ' '))
    {
        chrPtr++;
    }

    /* Copy until NULL terminator */
    while (*chrPtr != '\0')  
    {
        *strPtr = *chrPtr;
        strPtr++;
        chrPtr++;
    }

    /* If the string only contains blanks or is of length 0, strPtr still
     * points to the beginning of the string */
    if (strPtr != str)
    {
        strPtr--;
        /* Yank possible trailing blanks
         */
        while (*strPtr == ' ')
            strPtr--;
        strPtr++;
    }
    *strPtr = '\0';
}

/**
 * Removes the leading and trailing single quotes
 *
 * This function set removes the leading and trailing quotes. The function
 * strips these off using the same character buffer for storing the processed
 * string. The string must be NULL terminated.
 *
 * @param str string to process.
 */
void amdlibStripQuotes(char *str)
{
    char  *chrPtr;
    char  *strPtr;

    strPtr = str;
    if ((chrPtr = strchr(str, '\'')) != NULL) /* " */
    {
        /* Skip possible blanks after the quote
         */
        chrPtr++;
        while (*chrPtr == ' ')
            chrPtr++;
        /* Copy until single quote or NULL terminator
         */
        while ((*chrPtr != '\0') && (*chrPtr != '\'')) /* " */
        {
            *strPtr = *chrPtr;
            strPtr++;
            chrPtr++;
        }
        /* If the string only contains blanks or is of length 0, strPtr still
         * points to the beginning of the string
         */
        if (strPtr != str)
        {
            strPtr--;
            /* Yank possible trailing blanks
             */
            while (*strPtr == ' ')
                strPtr--;
            strPtr++;
        }
        *strPtr = '\0';
    }
}

/*___oOo___*/
