/*
 * Copyright (C) 1992 by Software Research Associates, Inc.
 *      Author: Y. Kawabe <kawabe@sra.co.jp>
 *
 * Permission to use, copy, modify, and distribute, and sell this software
 * and its documentation for any purpose and without fee is hereby granted,
 * provided that the above copyright notice appear in all copies and that
 * both that copyright notice and this permission notice appear in supporting
 * documentation, and that the name of Software Research Associates not be
 * used in advertising or publicity pertaining to distribution of the software
 * without specific, written prior permission.  Software Research Associates
 * makes no representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 *
 */

#include <NLS/nlsfile.h>
//#include <strings.h>
#include <stdlib.h>
#include <ctype.h>

nlsFile::nlsFile (const char* path) {
    if (*path == '/') {
	file_ = fopen (path, "r");
    } else {
	const char *dir = getenv("IV_NLSPATH");
	if (dir) {
	    char *p = new char [strlen(dir) + strlen(path) + 2];
	    sprintf (p, "%s/%s", dir, path);
	    file_ = fopen(p, "r");
	    delete p;
	} else {
	    file_ = nil;
	}

	if (!file_) {
            dir = getenv("HARMONY_HOME");
            if (dir) {
              char *p = new char [strlen(dir) + strlen(path) + 7];  // +1 for nullbyte
              sprintf(p, "%s/misc/%s", dir, path);
//             dir = IV_LIBALL "/nls";
//             char *p = new char [strlen(dir) + strlen(path) + 2];
// 	       sprintf (p, "%s/%s", dir, path);
              file_ = fopen(p, "r");
              delete p;
            }
	}
    }
}

nlsFile::~nlsFile () {
    if (file_) { fclose (file_); }
}

/*
 * check if continuous line
 */

int nlsFile::continued () {
    return int(isspace(line_[0]));
}

/*
 * split string with white space 
 */

int nlsFile::getline (char** argv, int size) {
    if (file_ == NULL) return -1;

    char *p = fgets(line_, sizeof(line_), file_);
    if (p == NULL) return -1;

    int argc = 0;
    while (1) {
	while (*p && isspace(*p)) p++;

	if (size == argc || *p == '\0' || *p == '#')
	    return argc;

	argc++, *argv++ = p;
	while (*p && !isspace(*p)) p++;
	if (*p) *p++ = 0;
    }
}

/*
 * String to Int
 */

int nlsFile::str2int (const char* s) {
    int r = 0;
    if (*s == '0') {
	if (*(s+1) == 'x') {	    /* Hex to Integer */
	    s += 2;
	    while (*s) {
		if (*s >= '0' && *s <= '9') {
		    r = r * 16 + (*s) - '0';
		} else if (*s >= 'a' && *s <= 'f') {
		    r = r * 16 + 10 + (*s) - 'a';
		} else if (*s >= 'A' && *s <= 'F') {
		    r = r * 16 + 10 + (*s) - 'A';
		} else
		    break;
		s++;
	    }
	} else {		    /* Octal to Integer */
	    s += 1;
	    while (*s && *s >= '0' && *s <= '7') {
		r = r * 8 + (*s) - '0';
		s++;
	    }
	}
    } else {
	while (*s && *s >= '0' && *s <= '9') {
	    r = r * 10 + (*s) - '0';
	    s++;
	}
    }
    return r;
}
