#include "readint.h"
#include "yacintfc.h"
#include <ctype.h>
#include "mkstr.h"
#include "usercom.h"

void ReadInt::open_f(int force_error)
{
	const char * new_name = def_name(GetFileName());
	const char * e_name = TargetNode::open_file(&new_name,ReadIntFile,0,force_error);
	if (!ReadIntFile) return ;

	if (e_name != new_name) exp_name = Concatenate(e_name);
	else exp_name = 0 ; 

	if (new_name != GetFileName()) new_name = delete_name = Concatenate(new_name);
	FileName_1 = new_name ;
}




ErrCode ReadInt::kernel(int k)
{
/*
 *	TheLog << "ReadIntFile = " << (void *) ReadIntFile << ", good = "
 *		<< ReadIntFile->good() << "\n" ;
 */
	if (State.IsError()) return FatalError ;
	if (!ReadIntFile) {
		open_f(1);
		if (State.IsError()) return FatalError ;
	}
	if (!ReadIntFile->good()) {
		if (DidCheck) return EndOfData ;
		State.Error("Cannot read file `",GetFileName(),"'");
		expand_name(GetFileName(),exp_name);
		HelpOut << "Error in node `" << GetName() << "'.\n" ;
		return FatalError ;
	}
	DidCheck = 1 ;
	int i ;
	int write_binary = GetFlags()&2 &&
		TheArithType != ArithType::ArithInt16;
	if (GetFlags()&1) for (i = 0 ; i < k ; i++) {
		int32 Temp ;
		int Peek = ReadIntFile->peek() ;
		while(isspace(Peek)) {
			ReadIntFile->get();
			Peek = ReadIntFile->peek() ;
		}
		if (Peek == 'X' || Peek == 'x') ReadIntFile->get();
		else if (Peek == '0') {
			ReadIntFile->get() ;
			int Peek = ReadIntFile->peek();
			if (Peek == 'X' || Peek == 'x') ReadIntFile->get();
			else if (!isxdigit(Peek)) {
				if (write_binary) WriteInteger(0);
				else WriteWord(0);
				continue ;
			}
		}
		*ReadIntFile >> hex >> Temp ;
		if (ReadIntFile->fail()) return EndOfData ;
		if (write_binary) WriteInteger(Temp);
		else WriteWord(Temp) ;
	} else for (i = 0 ; i < k ; i++) {
		int32 Temp ;
		*ReadIntFile >> Temp ;
		if (ReadIntFile->fail()) return EndOfData ;
		if (GetFlags()&2) WriteInteger(Temp);
		WriteWord(Temp);
	}
	return OK ;
}
