/*
 * COPYRIGHT (c) 1998-1999 Jan-Henrik Haukeland, http://www.tildeslash.com/
 */

package ts.mail;

/**
 * Utillity class for handling mime encoded strings.
 * 
 * @author  Jan-Henrik Haukeland &lt;hauk@tildeslash.com&gt;
 * @version $Id: Mime.java,v 1.7 1999/03/21 10:28:13 hauk Exp $
 */ 
public final class Mime 
{


  private Mime() {}



  /**
   * Returns a decoded mime encoded string
   *
   * @param s - An encoded mime string
   * @return a decoded mime string
   */
  public static String deCode(String s) 
  {
    String prev=         "", 
           rest=         "", 
           mime=         "", 
           result=       s;

    if (s == null || s.toUpperCase().indexOf("=?ISO-8859-")<0)
        return (result);
    do 
    {
      int i,j,k;
      i= result.indexOf("=?");
      prev= result.substring(0, i);
      j= result.indexOf("?Q?", i+2);
      k= result.indexOf("?=", j+3);
      mime= result.substring(j+3, k);
      rest= result.substring(k+2);
      result= prev + deCodeMime(mime) + rest;
      
    } while( result.toUpperCase().indexOf("=?ISO-8859") >= 0 );
    
    return(result);
  }


  private static String deCodeMime(String mime)
  {
    byte[] c= mime.getBytes();
    int x,y;
    for(x=0, y=0; y<c.length; ++x, ++y) {
      if((c[x]= c[y]) == '=') {
        c[x]= x2b(new byte[] {c[y+1],c[y+2]});
        y+= 2;
      }
    }
    return(new String(c).substring(0,x).replace('_',' '));
  }


  private static byte x2b(byte[] what) 
  {
    byte digit;
    digit = (byte)(what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 :
                   (what[0] - '0'));
    digit *= 16;
    digit += (byte)(what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 :
                    (what[1] - '0'));
    return(digit);
  }
  
}
