/****************************************************************************

  $Workfile: $
  $Revision: $
  $Modtime:: $
  $Copyright:

  Copyright (c) 1997 Novell, Inc.  All Rights Reserved.

  THIS WORK IS AN UNPUBLISHED WORK AND CONTAINS CONFIDENTIAL PROPRIETARY
  AND TRADE SECRET INFORMATION OF NOVELL, INC. ACCESS  TO  THIS  WORK IS
  RESTRICTED TO (I) NOVELL, INC.  EMPLOYEES WHO HAVE A NEED TO  KNOW HOW
  TO  PERFORM  TASKS WITHIN  THE SCOPE  OF  THEIR   ASSIGNMENTS AND (II)
  ENTITIES OTHER  THAN  NOVELL, INC.  WHO  HAVE ENTERED INTO APPROPRIATE
  LICENSE   AGREEMENTS.  NO  PART  OF  THIS WORK MAY BE USED, PRACTICED,
  PERFORMED COPIED, DISTRIBUTED, REVISED, MODIFIED, TRANSLATED, ABRIDGED,
  CONDENSED, EXPANDED, COLLECTED, COMPILED, LINKED,  RECAST, TRANSFORMED
  OR ADAPTED  WITHOUT THE PRIOR WRITTEN CONSENT OF NOVELL, INC.  ANY USE
  OR EXPLOITATION  OF  THIS WORK WITHOUT AUTHORIZATION COULD SUBJECT THE
  PERPETRATOR  TO CRIMINAL AND CIVIL LIABILITY.$

 ***************************************************************************/


#include <jni.h>
#include <sys_api.h>
#include <stdio.h>
#include <conio.h>
#include <sys\stat.h>

/*
 * Class:     com_novell_service_security_protocols_XplatTextProtocolProxy
 * Method:    readChars
 * Signature: (C)Ljava/lang/String;
 */
#define MAX_CHARS 256

JNIEXPORT jstring JNICALL
Java_com_novell_service_security_protocols_XplatTextProtocolProxy_readChars
(
    JNIEnv *env,
    jobject obj,
    jchar echo
)
{
//    char ch;
    char bytes [MAX_CHARS];
    int c, i = 0;
    char bStdIn;

#ifdef N_PLAT_NLM

    struct stat411 statbuf;

    fstat_411(fileno(stdin), &statbuf);

#else

    struct stat statbuf;

    fstat(fileno(stdin), &statbuf);

#endif

    if ((statbuf.st_mode & S_IFCHR) == S_IFCHR)
    {
        // stdin is reading from console (don't use)
        bStdIn = 0;
    }
    else
    {
        // stdin is reading from a file, use it.
        bStdIn = 1;
    }

    // Get chars
    // We can't read from stdin unles it has been redirected from a file
    // because stdin (con) reads until EOL, echoing characters before
    // returning
    while ((c = (bStdIn ? getc(stdin) : getch())) != '\r')
    {
        if (c == '\n')
            break;
        if (c == '\b')
        {
            if (i > 0)
            {
                i--;
                printf("\b \b");
            }
        }
        else
        {
            if (i < MAX_CHARS)
            {
                bytes[i++] = c;
                if (0 != echo)
                {
                    putchar(echo);
                }
                else
                {
                    putchar(c);
                }
            }
        }
    }
    bytes[i] = 0;

/* debug code
    i=0;
    printf("\n");
    while((ch = bytes[i++]) != 0)
    {
        printf("byte[%i] = %i\n", i, ch);
    }

    printf("\nbytes: %s\n", bytes);
*/

    return (*env)->NewStringUTF(env, bytes);
}
