//----------------------------------------------------------------------
//  IMPLEMENTATION FILE (password.cpp)
//  This module provides functions to store and verify a password.
//  Note: A password is only valid during the lifetime of the
//        importing program.
//----------------------------------------------------------------------
#include "bool.h"
#include "password.h"
#include <iostream.h>

const  int  MAXLEN = 10;            // Max password length
static char passStr[MAXLEN+1];      // Updated as a global variable

void GetPassword()
    //..................................................................
    // PRE:  Input is coming from the keyboard
    // POST: The user has typed a password which is, say,
    //       "len" characters long (up to '\n')
    //    && (len <= MAXLEN ) --> (passStr[0..len-1] == input string
    //                             && passStr[len] == '\0')
    //    && (len > MAXLEN )  --> (passStr[0..MAXLEN-1] == start of
    //                                                input string
    //                             && passStr[MAXLEN] == '\0')
    //..................................................................
{
    cout << "Establish a password of up to " << MAXLEN
         << " characters.\n"
         << "Type password then <RETURN>  --> ";

    cin.get(passStr, MAXLEN+1);
    cin.ignore(100, '\n');       // Previous "get" doesn't consume '\n'
}

Boolean ValidUser()
    //..................................................................
    // PRE:  passStr contains a string terminated by '\0'
    //       and does not contain '\n'
    //    && Input is coming from the keyboard
    // POST: A user-input sequence of chars (thru '\n') has been read
    //    && FCTVAL == TRUE,  if the input chars up to '\n' equal
    //                        the chars of passStr up to '\0'
    //              == FALSE, otherwise
    //..................................................................
{
    char inChar;
    int  i = 0;

    cout << "Type password then <RETURN>  --> ";
    cin.get(inChar);
    while (inChar == passStr[i]) {  // INV (prior to test):
                                    //    All passStr[0..i-1] match
                                    //    corresponding input
        i++;
        cin.get(inChar);
    }
    // ASSERT: inChar != passStr[i]

    if (inChar == '\n')
        // ASSERT: Input password may be valid
        return (passStr[i] == '\0');
    else {
        // ASSERT: Input password definitely invalid
        cin.ignore(100, '\n');            // Consume chars through '\n'
        return FALSE;
    }
}

