// myLib.c
//
// Useful general purpose functions 

#include        <string.h>
#include        <ctype.h>

#define	BUFLEN	512
#define	YES	1
#define	NO	0


//
//  Fatal error message to stderr then exit (never returns)
//
void fatal(char *errStr)
{
    fprintf(stderr, "%s\n", errStr);
    exit(1);
}

//
//  Random generator
//
//   // set random seed
//   srand(getpid());

/*
// Random generator
*/
double randomInt(int min, int max)
{
    int range = max - min;
    
    return rand()%range + min;
}


//
// Init all values in array to '\0'
//
void initArray(char mArray[], int arraySize)
{
    int i;
    for (i = 0;  i <= arraySize-1 ; i++)
            mArray[i] = '\0';
}


//
// Trim leading and trailing whitespace (including '\n')
//
void trimWhiteSpace(char source[])
{    
    int  i;
    char target[BUFLEN];
    
    // strip trailing whitespace
    for (i = strlen(source)-1; isspace((int)source[i]) && i >= 0 ; i-- ) {
            source[i] = '\0';
    }

    // count leading whitespace
    for (i = 0; isspace((int)source[i]) ; i++) {
    }

    // copy into target
    strcpy(target, &source[i]);

    // copy back to source
    strcpy(source, target);
}


//
// Read chars into field line[BUFLEN]
// until reaching item delimiter (itemDel[]), return delimiter reached
//
char readChars(int itemDel[], FILE *fp, char line[BUFLEN])
{    
    char mChar;               // my char from stream
    int  i, 
    endStr    = NO,
    charCount = 0;
    
    // empty target String
    initArray(line, BUFLEN);

    do {
            // get a char
            mChar = fgetc(fp);

            // check for delimiter
            for (i = 0; itemDel[i]; i++)
                    if (mChar == itemDel[i] || mChar == EOF )
                            endStr = YES;

            // append char to target string
            if ( ! endStr)
                    line[charCount] = mChar;
        
            charCount++;

    } while (! endStr);

    // conclude target string
    line[charCount] = '\0';

    return mChar;
}


//
// Print contents of array (useful for debugging)
// if arraySize = -1 then array terminated with '\0' (string)
//
void printCharArray(char mArray[], int arraySize) {
    
    int i;

    printf("[");

    // if string. (p.s. could use strlen)
    if (arraySize == -1) {
            for (arraySize = 0; mArray[arraySize] != '\0'; arraySize++) {
            }
    }
        
    for (i = 0; i <= arraySize ; i++) {
            if (mArray[i] == '\0')
                    printf(" 0 ");
            else
                    printf("%c", mArray[i]);
                
            if (i < arraySize)
                    printf(",");
        }
        
        printf("]");
}


//
// Parse mString into an array of separate fields
// accepts an array of item delimiters to determine breaks
//
int parse_line( int  itemDel[],
                char mString[],
                char fields[BUFLEN][BUFLEN])  
{
    int i       = 0,  // general purpose counter
    endFlag     = 0,  // flag for indicating record is finished
    readAt      = -1, // reading position in source array
    currentFld  = 0,  // item in fields[] array
    destination = 0;  // destination in current field                
        
    do {
            // loop through mString
            readAt++;
                
            // loop through each possible delimiter
            for (i = 0; itemDel[i] != NULL && ! endFlag ; i++) {

                    // check for delimeter or the end of string
                    if ( mString[readAt] == itemDel[i] ||
                         mString[readAt] == NULL )
                            endFlag = 1;    // flag that record as ended
            }

            if ( ! endFlag ) {
            
                    // copy the char
                    fields[currentFld][destination] = mString[readAt];
                    destination++;
            }
            else {

                    // end record, terminate this field
                    fields[currentFld][destination] = '\0';    

                    // check if field is empty before incrementing
                    if ( fields[currentFld][0] != '\0')
                            currentFld++;

                    // reset for new field
                    destination = 0;
                    endFlag = 0;
            }
            
            // error check: array limits
            if (readAt      == BUFLEN ||
                currentFld  == BUFLEN ||
                destination == BUFLEN )
                    break;

        } while ( mString[readAt] != NULL );
        
        // return number of fields found in line
        return currentFld;
}

// -- Using sprintf
// sprintf(myString, "%s%c%s", strA, myChar, strB);

// -- Using strstr
// if (strstr(line, "<delim")) {
//      cp = strstr(line, "value=");
//      valueChar = cp[6];
// }

//  readers = atoi(optarg);    atoi()   asci to string

