(function(exports){
	'use strict'
	
	
	var avr_boot_exe = (system.os == "windows") ? "flashers/avr-boot/avr-boot.exe" : "avr-boot";
	var flash_ok, flash_str="";
	
	
	function stdout_line(text)
	{
		print("stdout: '"+text+"'\n");
		
		if (text.match(/^Package succesfully loaded$/))
			flash_ok=true;
		
		var p = /^Writing page: ([0-9]+)\/([0-9]+)$/.exec(text);
		if (p != null)
		{
			ui.progress(100 * p[1] / p[2]);
		}
	}
	
	
	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;
	}
	
	
	exports.pkg = function(filename) {
		try
		{
			flash_ok=false;
			flash_str="";
			var rv=system.exec(avr_boot_exe, [COM, "pkg", filename], stdout, stdout);
			if (rv != 0) throw new Error("errorcode="+rv);
			if (! flash_ok) throw new Error("ok-pattern not found");
		} catch (e)
		{
			print("avr_boot error: "+e+"\n");
			return false;
		}
		
		return true;
	};
	
})(typeof exports === 'undefined' ? this['_avr_boot_js']={} : exports);
