(function(exports){
	'use strict'
	
	var ch341prog_exe = (system.os == "windows") ? "flashers/ch341prog/ch341prog.exe" : "ch341prog";
	var flash_str;
	var erase_ok, flash_ok;
	var percent_add=0;
	
	
	function stdout_line(text)
	{
		// Write started!
		// Bytes: 179968 (4%),  Time: 3, ETA: 66
		// Read started!
		// Bytes: 179968 (4%),  Time: 3, ETA: 66
		// Write completed successfully.
		
		print("stdout: '"+text+"'\n");
		
		if (text.indexOf("Write started!") >= 0)
			percent_add=0; else
		if (text.indexOf("Read started!") >= 0)
			percent_add=50;
		
		if (text.indexOf("Write completed successfully") >= 0)
			flash_ok=true;
		if ( (text.indexOf("Chip erase done!") >= 0) ||
			 (text.indexOf("Erase done !") >= 0) )
			erase_ok=true;
		
		var p = /^Bytes: [0-9]+ \(([0-9]+)%\)/.exec(text);
		if (p != null)
		{
			ui.progress(p[1] / 2 + percent_add);
		}
	}
	
	
	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 eraseChip()
	{
		try
		{
			erase_ok=false;
			flash_str="";
			var rv=system.exec(ch341prog_exe, ["-e"], stdout, stdout);
			if (rv != 0) throw new Error("errorcode="+rv);
			if (! erase_ok) throw new Error("ok-pattern not found");
		} catch (e)
		{
			print("ch341prog error: "+e+"\n");
			return false;
		}
		
		return true;
	}
	
	
	function erase(offset, length)
	{
		try
		{
			erase_ok=false;
			flash_str="";
			var rv=system.exec(ch341prog_exe, ["-o", offset, "--erase="+length], stdout, stdout);
			if (rv != 0) throw new Error("errorcode="+rv);
			if (! erase_ok) throw new Error("ok-pattern not found");
		} catch (e)
		{
			print("ch341prog error: "+e+"\n");
			return false;
		}
		
		return true;
	}
	
	
	function write(filename)
	{
		try
		{
			flash_ok=false;
			flash_str="";
			percent_add=0;
			var rv=system.exec(ch341prog_exe, ["-v", "-w", filename], stdout, stdout);
			if (rv != 0) throw new Error("errorcode="+rv);
			if (! flash_ok) throw new Error("ok-pattern not found");
		} catch (e)
		{
			print("ch341prog error: "+e+"\n");
			return false;
		}
		
		return true;
	}
	
	
	exports.write = function(filename) {
		
		// Получаем размер для стирания
		var length=fs.readBinary(filename).length;
		length=(length+4095) & ~0xfff;
		
		return erase(0, length) && write(filename);
	};
})(typeof exports === 'undefined' ? this['_spiflash_js']={} : exports);
