import java.io.*;
import java.net.*;

class ForPDAruSimplifier
{
  public static void main(String[] s) throws Exception
  {
	int STEPS = Integer.parseInt(s[0]);
	int UPPER_LIMIT = Integer.parseInt(s[1]);
	int TOPIC_NUMBER = Integer.parseInt(s[2]);
	String FILENAME_PREFIX = s[3];

	boolean alreadySeenFirstPost = false;

	 for (int i=0; i<UPPER_LIMIT; i=i+STEPS)
	 {	
		int innerCounter = 0;
		java.net.HttpURLConnection url = (java.net.HttpURLConnection)new java.net.URL("http://4pda.ru/forum/index.php?showtopic="+TOPIC_NUMBER+"&st="+i).openConnection();
	      	url.connect();


	  	DataInputStream dis = new DataInputStream (url.getInputStream());
	      	String line;
      		PrintStream ps = new PrintStream (new FileOutputStream(FILENAME_PREFIX+returnNextFileCount(i / STEPS +1)+".html"));
		
		// print out the sufficient headers so that 1. Babelfish doesn't refuse the document 2. all browsers handle it as Russian
		ps.println("<html xml:lang=\"en\" lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <META HTTP-EQUIV=\"content-language\" CONTENT=\"ru\"> <meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1251\" />  </head> <body>");

		String author = null;
	      	while ( (line = dis.readLine()) != null)
      		{
      			// getting author + date
      			if (line.indexOf("<div align=\"center\"><a name='entry")!=-1)
			{

				if (alreadySeenFirstPost && innerCounter == 0) continue; // skip the first post if not the one at start
				int authorstartsat = line.indexOf("onmouseover=\"copyQ('")+"\"onmouseover=\"copyQ('".length()-1;
      				author = line.substring(authorstartsat, line.indexOf("'", authorstartsat+3));
				System.out.println("author:   "+author); 
				int datestartsat = authorstartsat + author.length()+ 3; 
				String date = line.substring(datestartsat, datestartsat+17);
				System.out.println(date); 
				ps.println("<TABLE width=\"100%\"><TR><TD width=\"50%\" bgcolor=#cccccc>"+author+"</TD><TD width=\"50%\" bgcolor=#cccccc>"+date+"</TD></TR>");
			}

			// post body
      			if (line.indexOf("<div class='postcolor'>")!=-1)
			{
				if (alreadySeenFirstPost && innerCounter++ == 0) continue; 
				ps.println("<TR><TD COLSPAN=2 bgcolor=#eeeeee>"+line+"</TD></TR>");
				alreadySeenFirstPost = true; 
			}
	      	} // while 
		ps.println("</TABLE> </body> </html>"); // close the file
		ps.close();      	
	 } // for
 } // main
 static String returnNextFileCount(int i) 
 {
 		String nextNumberString = ""+i;
 		if (nextNumberString.length() == 1) nextNumberString = "0"+nextNumberString;
 		return nextNumberString;
 }
}
