(function(exports){
	'use strict'
	
	
	var stm8flash_exe = (system.os == "windows") ? "flashers/stm8flash/stm8flash.exe" : "stm8flash";
	var flash_ok, flash_str="";
	
	
	function stdout_line(text)
	{
		print("stdout: '"+text+"'\n");
		if ( (text.match(/^Bytes written: /)) ||
			 (text.match(/^Bytes received: /)) ||
			 (text.match(/^Bytes verified: /)) )
			flash_ok=true;
	}
	
	
	function stdout(text)
	{
		text=text.replace(/\r/g, '\n');
		var nl;
		while ( (nl=text.indexOf('\n')) >= 0 )
		{
			stdout_line(flash_str + text.substring(0, nl));
			flash_str="";
			text=text.substring(nl+1);
		}
		flash_str=text;
	}
	
	
	function stm8flash(args)
	{
		try
		{
			flash_ok=false;
			flash_str="";
			var rv=system.exec(stm8flash_exe, args, stdout, stdout);
			if (rv != 0) throw new Error("errorcode="+rv);
			if (! flash_ok) throw new Error("ok-pattern not found");
		} catch (e)
		{
			print("stm8flash error: "+e+"\n");
			return false;
		}
		
		return true;
	};
	
	
	
	exports.unlock = function(part) {
		if (part=="stm8s003f3p6")
		{
			return true;
		} else
		{
			return stm8flash( [ "-c", "stlinkv2", "-p", part, "-u" ] );
		}
	};
	
	
	exports.write = function(part, memtype, filename) {
		return stm8flash( [ "-c", "stlinkv2", "-p", part, "-s", memtype, "-w", filename ] );
	};
	
	
	exports.read = function(part, memtype, filename, size) {
		var args=[ "-c", "stlinkv2", "-p", part, "-s", memtype ];
		if (size) args=args.concat( [ "-b", size ] );
		args=args.concat( [ "-r", filename ] );
		return stm8flash(args);
	};
	
	
	exports.verify = function(part, memtype, filename) {
		return stm8flash( [ "-c", "stlinkv2", "-p", part, "-s", memtype, "-v", filename ] );
	};
	
})(typeof exports === 'undefined' ? this['_stm8_js']={} : exports);
