package cn.hopefulme.jfortran;

import java.io.*;

public class Run {

	/**
	 * 运行程序
	 * @param is socket输入流，用来读取客户端输入
	 * @param br socket输入流，用来按行读取客户端输入
	 * @param os socket输出流，向客户端返回信息
	 * @param callback 回调，程序执行结束后调用
	 */
	public static void run(InputStream is, BufferedReader br, OutputStream os, Runnable callback) {
		try {
			//读取代码
			String code = "";
			/*
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String info;
			while((info=br.readLine()) != null) {
				if(info.equals("**##*#*#code ended**##*#*#")) break;
				code += info + "\n";
			}
			*/
			code = Server.readCode(br);
			//编译代码
			String compile = FCompiler.compileCode(code, "./temp/exe");
			if(! compile.contains("编译成功！")) {
				os.write(compile.getBytes());
				return;
			}
			//执行程序
			Terminal terminal = new Terminal("./temp/exe");
			terminal.start();
	 		while(terminal.process.isAlive()) {
				String input = "";
				//有输入时获取输入
				if(is.available() > 0) {
					String data;
					while((data=br.readLine()) != null) {
						if(data.equals("**##*#*#input ended**##*#*#")) break;
						input += data + "\n";
				 	}
					terminal.input(input);
				} 
				String output = terminal.output();
				//有输出时输出信息
				if(output.length() > 0) {
					os.write(output.getBytes());
					os.flush();
	 			}
				Thread.sleep(30);
			}
			String output = terminal.output();
			//有输出时输出信息
			if(output.length() > 0) {
				os.write(output.getBytes());
				os.flush();
	 		}
		} catch (IOException e) {
			System.out.println("Run_run_IOException" + e.getMessage());
	 	} catch (InterruptedException e) {
			System.out.println("Run_run_InterruptedException" + e.getMessage());
		} finally {
			//执行回调
			callback.run();
		}
	}

}

@@ -727,18 +727,16 @@
 %09if(
-! 
 compile.
 cont
@@ -735,25 +735,18 @@
 ile.
-contains(%22%E7%BC%96%E8%AF%91%E6%88%90%E5%8A%9F%EF%BC%81%22)
+length %3E 0
 ) %7B%0A
@@ -758,16 +758,26 @@
 s.write(
+%22%E7%BC%96%E8%AF%91%E5%A4%B1%E8%B4%A5%EF%BC%81%5Cn%22+
 compile.
@@ -785,24 +785,40 @@
 etBytes());%0A
+%09%09%09%09os.flush();%0A
 %09%09%09%09return;%0A

fix no run