#! /bin/jsh
#
# Copyright 2013-2014 Yuichiro Moriguchi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
if [ -z "$2" ]
then
  putlicense_cstyle.sh
  class_nm="${CLASSNAME}"
  echo '/**'
  awk '{ printf(" * %s\n", $0) }' description
  echo ' */'
  cat definition
else
  class_nm="$2"
fi

this='$this'
c='$c'
cat << EOF
function ${class_nm}() {
	this.__state = 0;
	this.iseof = null;
	this.unread = null;
}

EOF
[ -z "$2" ] && cat << EOF
${class_nm}.ENDMARKER = {};

${class_nm}.prototype._read = function(itr) {
	var c;

	if(this.unread != null) {
		c = this.unread;
		this.unread = null;
	} else if((c = itr()) == null) {
		this.iseof = ${class_nm}.ENDMARKER;
	}
	return c;
}
EOF

nina_template.nfa.js.sub2.sh "$1" "" "$class_nm"

[ -z "$2" ] && cat << EOF

${class_nm}.prototype.reset = function() {
	this.__state = 0;
	this.iseof = null;
	this.unread = null;
}

${class_nm}.prototype.searchToken = function(itr) {
	var b = '';
	var f = false;
	var o = null;
	var c;

	if(this.iseof != null)  return this.iseof;
	while((c = this._read(itr)) != null) {
		b += String.fromCharCode(c);
		if(this._step(this, c) == 0) {
			if(f) {
				this.unread = c;
				this.__state = 0;
				return o;
			} else {
				return null;
			}
		} else if(f = this._accepted(this)) {
			o = this._gettoken(this, b);
			if(this._isdead(this)) {
				this.__state = 0;
				return o;
			}
		} else if(this._isdead(this)) {
			return null;
		}
	}
	return f ? o : null;
}

${class_nm}.newStream = function(stream) {
	return function() {
		var c;

		c = stream.read();
		return c < 0 ? null : c;
	};
}

${class_nm}.newString = function(s) {
	var p = 0;

	return function() {
		return p < s.length ? s.charCodeAt(p++) : null;
	};
}

${class_nm}.newJavaString = function(s) {
	var p = 0;

	return function() {
		return p < s.length() ? s.charAt(p++) : null;
	};
}

${class_nm}.newStdin = function() {
	return ${class_nm}.newStream(
			new java.io.InputStreamReader(java.lang.System['in']));
}
EOF
[ -z "$2" ] && cat fragment
