package comment;

import java.io.*;
import java.net.*;

class CommentServer
{	private static int port = 4443;
	private static String filename = "comments.txt";
	public static void main(String [] args)
	{	if( args.length >0)
			port = Integer.parseInt(args[0]);
		if(args.length > 1)
			filename = args[1];	
		
		Socket sock= null;
		ServerSocket servsock = null;
		try
		{	servsock = new ServerSocket(port);
		}
		catch(IOException e)
		{	System.out.println("Could not open port.");
			System.exit(1);	
		}
		while (true) try 
		{	sock=servsock.accept();
			BufferedWriter dump;
			BufferedReader in  = new BufferedReader(new InputStreamReader( sock.getInputStream() ));
				
			String contents = "";
			File inputFile = new File(filename);
			if (!inputFile.exists()) // create it. 
			{	OutputStream makeOut = new FileOutputStream(filename);
				makeOut.close();	
			}
			InputStream grab = new FileInputStream(filename);
			int bufLen = grab.available();
			if (bufLen > 0) 
			{	byte [] buf = new byte[bufLen];	
				grab = new BufferedInputStream(grab, bufLen);
				int length = grab.read(buf);
				grab.close();				
				contents = new String(buf);
				int len = contents.length();
				dump = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()), len);
				
				dump.write(""+len +"\n");
				dump.flush();
				
				dump.write(contents,0, len);
				dump.flush();
			}
			else
			{	dump = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
				dump.write("0\n");
				dump.flush();
			}
			boolean dirty = false;	
			while (true)
			{	String comment = in.readLine();
				if (comment == null || comment.trim().equals("..")) break;
				dirty = true;
				contents +=  comment + "\n";
				//	System.out.println(comment);
			}
			if (dirty)
			{	PrintWriter out = new PrintWriter(new FileWriter(filename));
				contents += "---\n";	
				out.write(contents);
				out.flush();
				out.close();
			}			
		}
		catch (IOException e)
		{ 	//System.out.println("IOException from comment server." + e);
		}
		finally // just in case
		{	try
			{ sock.close();
			}
			catch(Exception o)
			{
			}
		}						
	}
}

