/*
 * Copyright (c) 1995, 1996 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Permission to use, copy, modify, and distribute this software
 * and its documentation for NON-COMMERCIAL purposes and without
 * fee is hereby granted provided that this copyright notice
 * appears in all copies. Please refer to the file "copyright.html"
 * for further important copyright and licensing information.
 *
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */
#include <StubPreamble.h>
#include <javaString.h>

#include "InputFile.h"
#include "OutputFile.h"

#include <sys/types.h>
#include <sys/param.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>

#define        LOCAL_PATH_SEPARATOR        '/'

static void
convertPath(char *str)
{
    while (*str != '\0') {
        if ((*str == InputFile_separatorChar) ||
            (*str == OutputFile_separatorChar)) {
            *str = LOCAL_PATH_SEPARATOR;
        }
        str++;
    }
    return;
}

long InputFile_open(struct HInputFile *this)
{
    int                fd;
    char        buf[MAXPATHLEN];

    javaString2CString(unhand(this)->path, buf, sizeof(buf));
    convertPath(buf);

    fd = open(buf, O_RDONLY);
    if (fd < 0)
        return(FALSE);

    unhand(this)->fd = fd;
    return(TRUE);
}

void InputFile_close(struct HInputFile *this)
{
     close(unhand(this)->fd);
     unhand(this)->fd = -1;
     return;
}

long InputFile_read(struct HInputFile *this, 
                    HArrayOfByte *buffer, 
                    long count)
{
    char *data        = unhand(buffer)->body;
    int  len        = obj_length(buffer);
    int  actual;

    if (len < count) {
        actual = len;
    }
    else {
        actual = count;
    }
    actual = read(unhand(this)->fd, data, actual);
    if (actual == 0)
        return(-1);
    return(actual);
}
