/*
 * Gary Cornell and Cay S. Horstmann, Core Java (Book/CD-ROM)
 * Published By SunSoft Press/Prentice-Hall
 * Copyright (C) 1996 Sun Microsystems Inc.
 * All Rights Reserved. ISBN 0-13-565755-5
 *
 * Permission to use, copy, modify, and distribute this 
 * software and its documentation for NON-COMMERCIAL purposes
 * and without fee is hereby granted provided that this 
 * copyright notice appears in all copies. 
 * 
 * THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR 
 * WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER 
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS
 * AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED 
 * BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING 
 * THIS SOFTWARE OR ITS DERIVATIVES.
 */
 
/**
 * @version 1.00 07 Feb 1996 
 * @author Cay Horstmann
 */

import java.io.*;
import java.net.*;
import corejava.*;

class ProxySvr
{  public static String urlDecode(String in)
   {  StringBuffer out = new StringBuffer(in.length());
      int i = 0;
      int j = 0;
     
      while (i < in.length())
      {  char ch = in.charAt(i);
         i++;
         if (ch == '+') ch = ' ';
         else if (ch == '%') 
         {  ch = (char)(Format.atoi("0x" 
               + in.substring(i, i + 2)));
            i++;
         }
         out.append(ch);
         j++;
      }
      return new String(out);      
   }

   public static void main(String[] args)
   {  try 
      {  String urlname = urlDecode(args[0]);
         DataInputStream is = null;
         try
         {  URL url = new URL(urlname);
            is = new DataInputStream(url.openStream());         
         }
         catch (MalformedURLException e)
         {  // 1.0 release doesn't know Gopher
            int pos = urlname.indexOf("://");
                     
            String protocol = urlname.substring(0, pos);
            if (!protocol.equals("gopher")) throw e;
            pos += 3;
            int pos2 = urlname.indexOf("/", pos);
            if (pos < 0) throw e;
            String host = urlname.substring(pos, pos2);
            String file = urlname.substring(pos2);
         
            Socket t = new Socket(host, 70);
            PrintStream os 
               = new PrintStream(t.getOutputStream());
   
            is = new DataInputStream(t.getInputStream());
            os.print(file + "\r\n");
         }
      
         System.out.print("Content-type: text/html\n\n");
         boolean more = true;
         while (more)
         {  String str = is.readLine();
            if (str == null) more = false;
            else System.out.println(str);
         }
      } 
      catch(Exception e) { System.out.println("Error" + e); }
   }
}