/*
 * l'affichage ecran ne se fait que si optionDebug
 * pas doubler horloge
 * emissionHtmlEnRetard ??? 
 *  option pour afficher memoire 
 * 
 * Copyright (c) 2007, Sun Microsystems, Inc.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are By provided that the following conditions
 * are met:
 *
 *  *  Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions aappnd the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *  * Neither the name of Sun Microsystems nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package example.http;

import com.nokia.mid.ui.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.io.file.*;

// import javax.microedition.lcdui.DateField;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.pim.*;
// JSR 179 
import javax.microedition.location.*;

// bt

import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
 

// fin BT
import java.io.*;


// BT 
 public class HttpTest extends MIDlet implements CommandListener,   DiscoveryListener ,Runnable {
     
 
 /*
public class HttpTest extends MIDlet implements CommandListener,   Runnable {
   */
     
  PIM singleton=PIM.getInstance();
//  boolean sendMailActif=false;
 
 //  int nl=0;
  
  
  // BT
  
   public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
        //No implementation required
    }
 
   public void serviceSearchCompleted(int transID, int respCode) {    
        //No implementation required
    }
 public void inquiryCompleted(int discType) {
        // No implementation required    
    }
   public void deviceDiscovered(RemoteDevice remoteDev, DeviceClass devClass) {
        String un=null;
        try {
            //add device "Friendly name" to a listbox
            un=remoteDev.getFriendlyName( false )+": "+remoteDev.getBluetoothAddress();
//            listDev.append( remoteDev.getFriendlyName( false )+": "+remoteDev.getBluetoothAddress(),
//                    null);
        } catch ( IOException e ) {
            //TODO: Handle error
            DEBUG(159875,"IOException en devDiscoderd",e);
        }
       if (bm.length()>0) bm.append ("\n"); 
       bm.append("BT:"+un);
        
 
    
    
    }
    
     
     private LocalDevice devLocal;
    private DiscoveryAgent discoverAgent;
 
// StringBuffer quoi = new StringBuffer("");    
final long TA=20000;
final long TR=40000;
boolean pile=true;

 protected int initLocalDevice() {
        try {
            devLocal = LocalDevice.getLocalDevice();
        } catch (BluetoothStateException e) {
            showErrAlert( "Error getting local device!" );
            return -1;
        }
        return 0;
    }

void showErrAlert(String t){
    INFO (454545,t);
}
protected int startDeviceSearch() {
        discoverAgent = devLocal.getDiscoveryAgent();
        try {
            discoverAgent.startInquiry( DiscoveryAgent.GIAC,
                    this );
        } catch( BluetoothStateException e ) {
            showErrAlert( "Error starting device enquiry!" );
            return -1;
        }
        return 0;
    }
 
    

 void btSearch(){
     DEBUG(7148,"Bt pour milli:"+TA);
     bmerase() ;  // effacer la liste du moment 
  //   autoDiscover();
     int err = 0;
            err = initLocalDevice();
            if( err != 0 ){
                ERROR(6421,"erreur init BT");    
                return;
            }
            err = startDeviceSearch();
            if( err != 0) {
                ERROR(6421,"ereur start BT");    
                return;
            }
  
     waitMilli(1,TA);
  //   stopDiscover();
          discoverAgent.cancelInquiry( this );
     lock(bm.toString());     
     
 }
 
   
  // fin BT

  
  
   final   String listeApres="<>*!~";
  final   String listeAvant="#'/-+";
 
  // 2610 ne connait que .txt
  String extxy=".xy";
  String extyx=".yx";
  final boolean APPENDSUPPORTED=true; 
  boolean S60=false;
  
  boolean dessusDessous=false;
  final int MAXRECEIVEHTML=20000;
  boolean premsPIM=true;
  
  String ContentType="Content-Type: multipart/mixed;\n boundary=";
  String mimeSeparator="----123456789";
  String enteteMime="";
  String epilogueMime="";
  boolean afficherFirst=true;
  boolean multipartDone=false;
   StringBuffer totalRapport = new StringBuffer("");  
boolean uploadByPostReussi=false;
final String SMTPSERVER="socket://smtp.orange.fr:25";
boolean emissionHtmlEnRetard=false;
// pour date()
final int DATECOURTE=1;
final int HHMMSS=3;

StringBuffer lecoup= new StringBuffer();
String ligne="";
 
// int final TIMEOUT179=20;
int timeout179=0;
int jsr179Accuracy=10000;
  
//          InputStream ism =null;
//        OutputStream osm =null;
// partagés entre ouvrir / fermer smtp et mailX ou rapporte
          InputStream ismX =null;
        OutputStream osmX =null;
      SocketConnection scX =null;
      
 //   boolean background=false;
   
    boolean usePim=false;   // passera à vrais si prop vide
    //                         et voir quoi si rechargement web
    
    boolean faireVoir=false;
    final int insisteHtmlMax=2;
    final int insisteSmtpMax=2;
    // contante pour rapportefichier
    final int CONTENU=1;
    final int TAILLE=2;
    final int ENCODEDBASE64=3;
    final int AVECCRLF=4;
    final int EXISTS=5;
    final int DELETE=6;
    final int RENAME=7;
    // buffer lecture fichier
 //    final int TAILLEBUFFERFICHIER=64000;
    final int TAILLEBUFFERSMART=4000;
    byte[] data= new byte[TAILLEBUFFERSMART];
 
    //
 //   final int FINOPTMAX=99999;
   String jsr179Version=null; 
   String jsr256Version=null; 
    final String HEXA ="0123456789ABCDEF";
   
   
    boolean emettreCarConfig=false;
     /**
      * This character array provides the alphabet map from RFC1521.
      */
     /**
      * Encodes 1, 2, or 3 bytes of data as 4 Base64 chars.
      *
      * @param in buffer of bytes to encode
      * @param len how many bytes to encode
      * @param out buffer to put the output in
      */
   
  String toEmail=""; // modifiable par >
  String excAbendSend="";
   final String version="1.0044" ;
   String logsmphp="";  // obligatoire
   final String AMORCE="http://mobile.orange.fr/0/accueil/Retour?SA=CHADEPTFCGEO";
       
int ch=0;
   StringBuffer bm = new StringBuffer();  // utilisé par upload?

  String TROUVE="T";
  
  String lastUrl="";
//  boolean cgopen=false;
//  boolean oldopen=true;
  boolean backlightDone=false;
  
  int periodeHorloge=10;   // miodifie dans deveice
  int BACKLIGHTPERIODE=5;
  
  StringBuffer bbrut = new StringBuffer();

  int NBMAXREDIR=8;
 //      int po3f;  
//  HttpConnection cg = null;  // pour getUrl
//  HttpConnection cm = null;  // pour mail
//  InputStream is=null;
  
  int gapSecondes=-1;
  int shutDown=-1;
   final String PO="Po.";
   String HOMEFSLOCAL="";   
     
   final String NOKIA2610="Nokia2610";  
   final String NOKIA5800="Nokia5800d-1";  
   final String SAMSUNGC3050="SamsungC3050";
   String FICHIERABEND="";
   String FICHIERLOCK="";
   String FICHIERXY="";
   String FICHIERYX="";
   String home="";  // nom de fichier/chemin reçu par option "!"
   String PILE="";
   String FACE="";
   boolean fileCreated=false;
   final String HEUREMATIN="08:00:00";
   final String HEURENUIT="20:00:00";
   StringBuffer resumeTout=new StringBuffer(); 
   String stamp="";
   long nowMilli=0;
//   long startMilli=-1;
   long nextMilli=-1;
   
   String globalTete="";
   //  si ABANDON ou fini, on va à l'écran 
    boolean ABANDON=false;
    boolean XXfini=false;
    
   String numTelephone="";
   String modeleTelephone="";
   
   int pointsFaits=0;
   int GLOBup=0;   // compte les émissions par html
 
   String lat="";
   String lon="";
//   String latLonEcran="";

//   OutputConnection globalOs = null;
   
   String lastMailRc = "";
//   String sortieMailRc = "";
 //  int mailCount=0;
 //  final int WAITECRAN=1;
   int waitDebug=5;
//   String xyxy="";
//   String xyxyEcran="";
   String XXafficher;
   String trouve=""; // sera T quand localisé
 //  int attendu=0; // cumul des attentes à décompter de inter-coups
  // aux ordres de l'url
  int locSucces=0;
  int nbGet=0;
//   String Xoptions=""; // obsolete JSR179 ?
   String PropDescription="";
   
// options seront modifiées par config.txt puis réponses
//   boolean optionConfig=false;
   boolean optionBluetooth=false;
   boolean optionZombie=false;
   boolean zombie=false; // passe à vrai si Z
   boolean optionDump=false;
   boolean optionNoTrafic=false;
   boolean optionFirst=false;
   boolean optionQuit=false;
   boolean optionGps=false;
 //  boolean optionTous=false;
   boolean optionPack=false;
   boolean optionVoir=false;
//   boolean optionFatigue=false;
   boolean optionRaz=false;
   boolean optionApi=false;
 //  boolean optionGetConfig=false;
 //  boolean optionListe=false;
   boolean optionInternetMax=false;
   boolean optionInternetNuit=false;
//   boolean optionTelephone=false;
//   boolean optionAutoUrl=false; // pas modifiable 
   boolean optionBacklight=false; 
   boolean zombieDone=false;
   boolean optionWriteFinal=false;
   boolean optionDebug=false;  //pour l'avoir au début
   boolean optionLog=false;  //pour l'avoir au début
   boolean optionFichier=false;
   boolean optionHorloge=false;
   // affichage et horloge
   String globalTitre="";
   String globalTexte="";
   String globalTime=""; // heure création de la page
   //
   int finOpt=-1;
   int debutOpt=-1;
   //
   String sessionID="" ; //a partir de premiere localisation d'orange
  long iterations;
  long periodePointS;
  long nbGroupage;
  
   int             mail2Number=0;
   String              mail2Subject="";
   String              mail2Contenu="";
   
   boolean premsConfig=true;
   
   // Command probablemen t pas utilisé, en souvenir de modèle
    /** User interface command to exit the current application. */
    private Command exitCommand = new Command("Exit", Command.EXIT, 2);

    /** User interface command to issue an HTTP GET request. */
  //  private Command getCommand = new Command("Start", Command.SCREEN, 1);

    /** User interface command to choose a configuration */
  //  private Command chooseCommand = new Command("Choose", Command.SCREEN, 2);

    /** User interface command to Add a new location. */
  //  private Command addCommand = new Command("Add", Command.SCREEN, 1);

    /** User interface command to save a new location. */
//    private Command addSaveCommand = new Command("OKsave", Command.SCREEN, 1);

    /** User interface command to confirm current operation. */
//    private Command okCommand = new Command("OKconfig", Command.OK, 1);

    /** User interface command to abort current operation. */
//    private Command cancelCommand = new Command("Cancel", Command.CANCEL, 1);

    /** The current display object. */
    private Display display;
    boolean displayOpen= false;

    /** The configuration  */
    private String configRecue="";
    private String configPrev="";  // pour ne pas decoder si identique 
  
    // prochaine url a ouvrir (mise par getandfollow quand site dit 301 ou 302)
    private String urlNext;
  
        /** Current command to process. */
    private Command currentCommand;

    /** The current command processing thread. */
    private Thread commandThread;

    /** Current attempt count. */
    private int attempt;
    
class NokiaS40S60LightThread extends Thread {   //1
    // 20100227 - semble fonctionner si au démarrage
    // pas programmé l'exticntion!
    //
    public void run() {
       // premier essai pour voir   
      // DEBUG(1111,"LightThread...");
       //   System.out.println("lightTread lancé! "+heureCourte());
       while(true){
          try{
            DeviceControl.setLights(0, 100);
          }catch (Exception e){
   //          DEBUG(1111,"Nokia hardware? cron");
          }
       
          try {
              Thread.sleep(1000*BACKLIGHTPERIODE);
          } catch (InterruptedException ex) {
     //         DEBUG(1111,"Nokia sleep?");
          } // try
       } //while
    }  // run
  }  // LightThread
 

    
    /** Initialize the MIDlet with a handle to the current display */
public HttpTest() {
    
     // pas d ECRAN avant ce display!
     // esasi de ne l'ouvrir que dans clock !
  //    display = Display.getDisplay(this);
   }

   
void lightOn(){
 // nokia seulement
 if (faireVoir){   
 // ne fonctionne pas
      try{
              // nom long pour la frime
              com.nokia.mid.ui.DeviceControl.setLights(0, 100); 
      
     }catch (Exception e){
     }
} //option Voir

}

void newDisplay(int appel,String titre,String texte){
    
    
    // range dans variables globales l'écran à affichier par clockDisplay
    // attetion pas d'attente
    // conserver les paraametres sn global
    //   globalAppel=appel;
    globalTitre=titre;
    globalTexte=texte;
    globalTime=date(HHMMSS); // time de création du message
    // si DEBUG ou ABEND ajouter le numéro d'appel
    if (appel!=0){
        if (appel>0) {globalTete = "["+appel+"]";}
        else {globalTete = "{"+(-appel)+"}";}
    }else{globalTete="";}
    clockDisplay();  
}

void clockDisplay(){
    
    if (zombie || !displayOpen) return;
    // appellé par newDisplay ou waitSecondes!
    // avrec délai à prochain scan ?
    String resteAvantProchain="";
    if (nextMilli>=0)  resteAvantProchain= "<"+(nextMilli-nowMs())/1000;
    String uneOuDeux="["+ globalTime+"]";
    if (optionHorloge) uneOuDeux=globalTete+date(HHMMSS)+uneOuDeux;
    String tt1=uneOuDeux+resteAvantProchain+"\n"+globalTitre;
 //   String tt2=globalTexte.toString();
 //   TextBox tc = new TextBox(tt1, tt2, tt2.length(), 0);
 //   tc =  new TextBox(tt1, tt2, tt2.length(), 0);
 //   display.setCurrent(tc);
 //     display.setCurrent(new TextBox(tt1, tt2, tt2.length(), 0));
      display.setCurrent(new TextBox(tt1, globalTexte, globalTexte.length(), 0));
    lightOn();   
}

void waitMilli( int appel, long m) {
    if (optionHorloge) {
    long n=m*1000;
  // essai horloge toutes les 10 secondes (fixé par periodeHorloge) !
     long inw;
     
     for (inw=1; inw<=n;++inw) {
        try {
                  Thread.sleep(1000);
        }  catch (Exception e) {
        }
        if ((inw % periodeHorloge)==0) clockDisplay();
// si configPimModifiée, on sort
        if (usePim && configPimModifiee()) return;
        if (optionFichier){
            if (lockDisparu()) return;
        }
    
    }
     
    }else {
     long n=m;
  // essai horloge toutes les 10 secondes (fixé par periodeHorloge) !
        try {
                  Thread.sleep(n);
        }  catch (Exception e) {
        }
    }
}

  
 
 String Z2(int mo) {      // ajouter un zero à gauche si int 1 chiffre
   String m="0"+Integer.toString(mo); 
   return (m.substring(m.length()-2));
 }
 
 String date(int longueOuCourte) {
   Calendar cal = Calendar.getInstance();
   String rep="";
   String hhmmss=Z2(cal.get(cal.HOUR_OF_DAY)) +Z2(cal.get(cal.MINUTE))+Z2(cal.get(cal.SECOND));

  switch (longueOuCourte){
      case DATECOURTE:  
          rep=cal.get(cal.YEAR)+Z2(1+cal.get(cal.MONTH))+Z2(cal.get(cal.DAY_OF_MONTH)) + "_" + hhmmss;
          break;
      case HHMMSS:
         rep= hhmmss;

  }
  return rep;
 }
 
 String noSpecial(String t) {
 // nettoyaer la date pour obtenit un stamp tulisable en nom de fichier
  String w="";
  String c="";
  for (int i=0;i<t.length();i++){
    c=t.substring(i, i+1);
    if (c.equals(" ")) c="_";
    if ((c.equals("-"))||(c.equals(":"))) c="";
    w+=c;
  }
  return (w);
 }
 
long secondesDuJour() {
   String s=date(HHMMSS);
   int h=Integer.parseInt(s.substring(0,2));
   int m=Integer.parseInt(s.substring(2,4));
   int ss=Integer.parseInt(s.substring(4,6));
   return(h*3600+m*60+ss);
 }

final void appelTelephone(String num){
    DEBUG(1,"appel phone "+num);
     try{
       platformRequest("tel:"+num);
     }
     catch(Exception e){
        ECRAN("catch",e.toString()); 
     }
     
}

    
final void ECRAN(String titre, String texte) {
   // filtré par E 
/*
 String T1=" ";
        if (!texte.equals("")){
             T1=texte;
        }
       String T2=" ";
        if (!titre.equals("")){
             T2=titre;
        }
        newDisplay(0,T2,T1);
 */
         newDisplay(0,titre,texte);
      if (optionDebug)     waitMilli(2,waitDebug*1000);
       
 }

  final void DEBUG(int appel,String s) {
      debugOuError ("DEBUG",appel,s,null);
  }
 
  final void INFO(int appel,String s) {
    debugOuError ("INFO",appel,s,null);
  }
 
  final void DEBUG(int appel,String s,Exception e) {
    debugOuError ("DEBUG",appel,s,e);
  }
  
  final void debugOuError(String verbe, int appel,String s,Exception e) {
     // initiazliser l'acran si ce n'est déjà fait
      if (!zombieDone) faireZombie(false);
    // si optionLog (J) affiche dans la log
    // si optionDebug (D) affichere écran   et attendre waitDebug
      
         if (optionDebug || (verbe.equals("INFO"))) {
                newDisplay(-appel,"",s);
                waitMilli(0,waitDebug*1000);
        }
    // 
         if (optionLog || (verbe.equals("INFO"))) {
           //      log(verbe+": "+appel+" " +date(DATECOURTE)+" "+s);
                 log(verbe+": "+appel+" "+s);
                  if (e!=null) {
                      log("Exception (qui a causé debug/abend):");
                      log(e.toString());
                      log("---------");
                  }
        }
   }
  
  final void ABEND(int appel,String s) {
      ABEND(appel,s,null);
  }  
  final void ABEND(int appel,String s,Exception e) {
      
      // si ce n'est pas fait ouvrir l'affichage
    // affiche et fini!
   //   DEBUG (1,"OPTION\nABEND");
   //   DEBUG (1,"optionWrite:\n"+optionWrite);
       optionDebug=true;
       optionLog=true;
       log ("ABEND---#: "+appel);
       log ("à:"+date(DATECOURTE));
       log("MOTIF:"+s);
       if (e!=null) excAbendSend="\nException:"+e.toString()+"\n"+e.toString()+"\n";           
        excAbendSend=excAbendSend+"\nETAT--------:\npointsFaits:"+pointsFaits+
                "("+locSucces+")"+
                "\nconfig:"+configPrev+
                "\nlastUrl"+lastUrl+
                "\nlastMailRc="+lastMailRc+
                "\nFree:"+java.lang.Runtime.getRuntime().freeMemory();
    //    DEBUG (1,"excabecnd:\n"+excAbendSend);      
        log (excAbendSend);      
        log ("FIN ETAT+++++++++++++");
         
 // message final        
        ECRAN("ABEND "+appel,resumeTout.toString());
  // A FAIRE essayer d'envoyer le rapport par uploadResults
       ABANDON=true;
  // normalement cet écran restera affiché car tout appel est suivi de if (ABANDON) return;     
   // et ecrire fichier
       
  }
  
  final void ERROR(int appel,String s) {
     ERROR(appel,s,null);
  }
  
  final void ERROR(int appel,String s,Exception e) {
      // affiche  et continue
      boolean saveG=optionDebug;
      boolean saveJ=optionLog;
      optionDebug=true;
      debugOuError("ERROR",appel,s,e);
      // reprendre valeur sauvegardée
      optionDebug=saveG;
      optionLog=saveJ;
  }
  
    /**
     * Start creates the thread to do the timing.
     * It should return immediately to keep the dispatcher
     * from hanging.
     */
  
    public boolean nokiaBacklightAvailable(){ 
                  try{
              // nom long pour la frime
              com.nokia.mid.ui.DeviceControl.setLights(0, 100); 
      
     }catch (Exception ey){
         ERROR(1111,"Nokia hardware? ",ey);
         optionBacklight=false;
         return (false);
     }
        return (true);
       
}

     
public void vendorAndDebug(){
    //   DEBUG(100011,"OK bersion"); 
     if (!getAppProperty("MIDlet-Vendor").equals(PO))  {
       optionDebug=true;    
       optionLog=true;
       faireZombie(false);
       log("Options debug et Log (D et J) forcées par suppression de MIDlet-Vendof"); 
     }
 
}    

void nokiaBack(){
    
        try{
                new NokiaS40S60LightThread().start();   
             }catch (Exception ex){
                ERROR (444,"exception LigthThread ",ex);
            //    optionBacklight=false;
             } // try
       
}
public void domodele(){
      boolean modeleTrouve=false;  // passera à true si modèle trouvé  
// Nokia 2610 
  
  try{
      
  if(modeleTelephone.equals(NOKIA2610) )  {
        modeleTrouve=true;
        extxy="_xy.txt";
        extyx="_yx.txt";
  
        if (optionBacklight | optionVoir) {
          if (nokiaBacklightAvailable()){
        
              if (optionBacklight)  nokiaBack();
              if (optionVoir) faireVoir=true;
          }
            
       } //back
 
    
  } // nokia2610
// Nokia 5800
  if(modeleTelephone.equals(NOKIA5800))  {
        S60=true;
        modeleTrouve=true;
   //      DEBUG(881188,"check FS "+HOMEFSLOCAL); 
        periodeHorloge=1;
        if (optionBacklight | optionVoir) {
          if (nokiaBacklightAvailable()){
        
              if (optionBacklight)  nokiaBack();
              if (optionVoir) faireVoir=true;
          }
            
       } //back
  } // nokia5800
  if(modeleTelephone.equals(SAMSUNGC3050))  {
        modeleTrouve=true;
  } // C3050
  
    // autres configs
    
  // .....
  
  // vérifier si modèle a été trouvé
  if (! modeleTrouve) {
        log("modèle inconnu");
    } 
  
  }catch (Exception e){
      DEBUG (67676,"exception au milieu de prepare (liste modèles).",e);
  }



}
public void prepare(){
   stamp=date(DATECOURTE);
String propUrl;
     
try{        
// DEBUG(45411,"va faire log premiere partie de prepare");
     
log("----------------------");
 
log("STAMP: "+stamp);
 
log("VERSION(source): "+version);
log("FREE: "+java.lang.Runtime.getRuntime().freeMemory());
jsr179Version=System.getProperty("microedition.location.version" );
log("JSR179: "+jsr179Version);
jsr256Version=System.getProperty("microedition.sendor.version" );
log("JSR256: "+jsr256Version);
sessionID=System.getProperty("com.nokia.mid.imei" );
        log("IMEI: "+sessionID);
log("IMSI: "+System.getProperty("com.nokia.mid.imsi" ));
modeleTelephone=System.getProperty("microedition.platform" );
log("PLATFORM: "+modeleTelephone);
modeleTelephone=modeleTelephone.substring(0, modeleTelephone.indexOf("/"));
log("MODELE: "+modeleTelephone);

// Config

   //  DEBUG(43331,"fait option BAckLight");
   PropDescription=getAppProperty("MIDlet-Description");
   //  DEBUG(100011,"Descrip: "+PropDescription); 
   log("DESCRIPTION: "+PropDescription);
   // 20100226 vérifier si version dans description
   
   if (!version.equals(getAppProperty("MIDlet-Version"))) {
    log("MIDlet-VERSION: "+getAppProperty("MIDlet-Version"));
    ERROR(555,"Version erreur "+version+"<>"+getAppProperty("MIDlet-Version")); 
   }
   
// racine
propUrl=getAppProperty("MIDlet-Info-URL");
//DEBUG(10002,"Description: "+PropDescription); 
   if (propUrl == null) {
//     ABEND(123,"manque propriété: MIDlet-Info-Url");
//     return;
    logsmphp="";
   } else{
    logsmphp=propUrl;
   log("HTTP(MIDlet-Info-Url): "+logsmphp); 
   }
// DEBUG(10003,"url: "+racine); 

}catch(Exception e){
    ABEND(45414,"dans debut de prepare ",e);
}
// selon modele

// domodele();

String origConfig=""; 
 try{
 // prendre la config initiale du 2do  
   propUrl=getAppProperty("MIDlet-Install-Notify");
 //  DEBUG(5454,"getPropUrl:"+propUrl);
      log ("MIDlet-Install-Notify: "+propUrl);
   if (propUrl == null) {
       // si S60 Pim sera relu à caque point
       if (S60) usePim=true;
         configRecue=configPIM();
         if (configRecue.length()==0) ABEND(45451,"pas de config");
         if (ABANDON) return;
            origConfig="Pim";
   } else{
         origConfig="Midlet-Install-Notify";
      configRecue=propUrl;
  //    DEBUG (7654,"Install-Notify="+configRecue);
    }
  //    DEBUG(123211,"decodeCONFIG\n"+configRecue);
 }catch(Exception e){
   ABEND  (43314,"DECODE call PIM",e);
 }    
try{
 if   (decodeConfigError(origConfig)) return;
}catch(Exception e){
    ABEND(18739,"durant decodeConfigError",e);
}

  // forcer demandes d'autorisation
   // créer le fichier .lck
    try{
       if (optionWriteFinal) if (appendFileSmartError("",FICHIERABEND,new StringBuffer(stamp))) return;

       if (optionFichier) if (appendFileSmartError("",FICHIERLOCK,new StringBuffer(stamp))) return;
    }catch(SecurityException e){
        ABEND(541189,"Vous n'avez pas autorisé l'écriture de fichier sur le mobile.");
        return;
    }catch(Exception e){
        ABEND(541189,"durant création fichier .lck/.txt",e);
        return;
    }
 
     
     if (internetNow() ) {
// INTERDIT LE LANCEMENT DE JOUR SI INTERNET NUIT
         //   DEBUG(541198,"prem internet "); 
         // essayer logsm pour avoir autorisation immédiate
       uploadResults ("0","","");  
        if (ABANDON) return;
     }
  
    if (optionGps && (jsr179Version != null)) log("TestJsr179:"+jsr179(1));
     

    }


    
    public void startApp() {
       ABANDON=false;
    // "ma" première instruction exécutée!
    // pour obtenir debug au depart modifier la propiete vendor (!="Po."
        
       vendorAndDebug(); //passe en debug si pas de Vendor
   
       try{ 
             bigMain();
         }catch (Exception e){
            ABEND (4444431,"durant big exception non traitée: ",e);
         }
        // si zombie décharger!
        if (zombie) {
        // semble faire une faute système
        // mais termine l'application
            this.notifyDestroyed();
        }
    }

   public String jsr179(){
       return jsr179(timeout179);
   }
   
   public String jsr179(int timeout){
/**/
     double x=0;
     double y=0;
String method="";
     long startMs=nowMs();
     if (jsr179Version==null) return ""; 
// à décommenter pour jouir du GPS!     

     Criteria cr=new Criteria();
     cr.setHorizontalAccuracy(jsr179Accuracy);
     Location l=null;
 //  
     LocationProvider lp=null;
     try{  
       lp=LocationProvider.getInstance(cr);
       
//       l=lp.getLocation(60);
     }catch (Exception e){
     //  ERROR (5164,"gps179:" ,e);
    //   ABANDON=false;
       return("*" + " ["+(nowMs()-startMs)/1000+"]");    
     }
     ECRAN("Gps/Net","wait location  "+timeout);
     try{
       l=lp.getLocation(timeout);
     }catch (LocationException e){
       return("*"+ " ["+(nowMs()-startMs)/1000+"]");    
     
     }catch (IllegalArgumentException e){
       ERROR (5163,"gps179 getLocation illegalargument :" ,e);
    //   ABANDON=false;
       return("*"+ " ["+(nowMs()-startMs)/1000+"]");    
     
     }catch (NullPointerException e){
       log("NoRepGps");  
       ERROR (5161,"GPS ne repond pas (NULLPOINTER en gps179) " );
    //   ABANDON=false;
       return("*"+ " ["+(nowMs()-startMs)/1000+"]");    
     
     }catch (Exception e){
       ERROR (5161,"autre Exception inattendue dans gps179:" ,e);
    //   ABANDON=false;
       return("*"+ " ["+(nowMs()-startMs)/1000+"]");    
     }
     try{
     Coordinates c=l.getQualifiedCoordinates();
     y=c.getLatitude();
     x=c.getLongitude();
     }catch (Exception e){
       ERROR (5164,"gps179:" ,e);
    //   ABANDON=false;
       return("*"+ " ["+(nowMs()-startMs)/1000+"]");    
     }
     
     try{
         int i=l.getLocationMethod();
     
     if ((i & Location.MTA_ASSISTED)!=0) method=method + " Assisted"; 
     if ((i & Location.MTA_UNASSISTED)!=0) method=method + " Unassisted";
     if ((i & Location.MTE_CELLID)!=0) method=method + " CellId";
     if ((i & Location.MTE_SATELLITE)!=0) method=method + " Satellite";
     if ((i & Location.MTE_SHORTRANGE)!=0) method=method + " Shortrange";
     if ((i & Location.MTY_NETWORKBASED)!=0) method=method + " Network";
     if ((i & Location.MTY_TERMINALBASED)!=0) method=method + " Terminal";
     }catch (Exception e){
       ERROR (5167,"gps179:" ,e);
    //   ABANDON=false;
       return("*"+ " ["+(nowMs()-startMs)/1000+"]");    
     }
 
// */ //fin de jsr179 dispo!   
     
     return (y+"*"+x+ " (" +method+")"+ " ["+(nowMs()-startMs)/1000+"]");
}
  
  
  public void bigMain(){
      ABANDON=false;
      
try{
        prepare();
}catch(Exception e){
    ABEND (154441,"big, exception non i nterceptée durant prepare",e);
    return;
    
}   
   if (ABANDON) return;
      
     if (optionQuit) {
             log("QUIT:");
             ABEND(72981,"Quit demandé par config");
             return;
     //        fini=true;
     }

    // peut-être inutile, mais ne peut pas faure de mal!
          try{
            principal();
            }catch(Exception e1){
            ABEND(123321,"Exception en PRINCIPAL",e1);
          // continue
     
            }
       if (ABANDON) return;
       log("FINI");
   
    if (optionWriteFinal){
       log ("Ecriture fichier final (W): "+FICHIERABEND);
       try{
         if (appendFileSmartError("",FICHIERABEND,resumeTout))  return;

       }catch(Exception e){
          ERROR(5411891,"dans writeFile de "+FICHIERABEND,e);
       }
    }
   
   if (optionFichier) if (deleteError(FICHIERLOCK)) return ;
  
    newDisplay(12,"FINI:"+pointsFaits+"("+locSucces+")\n"+configPrev+" FIN",resumeTout.toString());
    // si excAbendSed non vide essayr de l'écrire sur fichier
    
    return;

  }

   
    
    public void pauseApp() {
      // not used
    }

    /**
     * Destroy must cleanup everything.  The thread is signaled
     * to stop and no result is produced.
     * @param unconditional Flag to indicate that forced shutdown
     * is requested
     */
    public void destroyApp(boolean unconditional) {
        // not used
     }

    /**
     * Respond to commands, including exit
     * @param c command to perform
     * @param s Screen displayable object
     */
    public void commandAction(Command c, Displayable s) {
       // probably not used
        synchronized (this) {
            if (commandThread != null) {
                // process only one command at a time
                return;
            }

            currentCommand = c;
            commandThread = new Thread(this);
            commandThread.start();
        }
    }

  public void getDataHtml(boolean dump, HttpConnection cg){
    InputStream is=null;
   
       StringBuffer basurl  = new StringBuffer();

       bbrut.delete(0, bbrut.length());
       //   DEBUG(19,"getUrlAndFollow now reading stream");
       try{
            is = cg.openInputStream();
       }
       catch(Exception eee){
          // $$$$$$ eee not used!            
       }
        
 //     DEBUG(20,"getUrlAndFollow is = " + is);
 //      int nlu=0;1
 //      byte[] data = new byte[MAXRECEIVEHTML];
       int n=-1;
       try{
       n = is.read(data, 0, data.length);
       }catch(Exception po){
           ABEND(142301,"getDataHtml Erreur lectute data",po);
           return;
      }
               
       if (n>0){
            for (int i = 0; i < n; i++) {
   //             nlu=nlu+1;
                ch = data[i] & 0x000000ff;
                bbrut.append((char)ch);
                if ( (ch <= ' ') | (ch>'z')  | (ch == '#')| (ch == '&') | (ch == '&')| (ch == ';')  ) {
                    basurl.append(pct(ch));
                } else {
                    basurl.append((char)ch);
                 }
            }   // for
         //  DEBUG(2102,"getUrlAndFollow reçu        :"+basurl.toString());
// abréviations
        String contenuOk=   basurl.toString();
        log("LONG:"+contenuOk.length());
        if (contenuOk.indexOf("manuel")>0)contenuOk="manuel...";
        if (contenuOk.indexOf("localiser")>0)contenuOk="localiser...";
        if (contenuOk.indexOf("ouhaitez vous vous localiser")>0)contenuOk="PAS LOCALISABLE...";
        if (contenuOk.indexOf("avez plus de cr")>0)contenuOk="PLUS CREDIT...";
        if (contenuOk.indexOf("avez")>0)contenuOk="AVEZ EPUISE...";
        //
        if (dump){
                  log("optionDump");
                  log(basurl.toString());
                   log("optionDump fin");
        } else {     // donc n<=0
            log("GETRECU: "+contenuOk);
        }
        //
         ECRAN("GETRECU: ",bbrut.toString());
        }else{
          log("2021- reçu_un_code_200_sans_contenu_pour:");
     }
           
                if (ABANDON) return;

       try{
                is.close();
       }  
       catch(IOException ioe){
           ERROR (23,"IOException for is.close: ",ioe);
       }
        
           
       try {
        int len= is.available();
                 DEBUG(24,"Inputstream is.available failed to throw IOException after close il en reste len="+len);
    //            DEBUG (25,"au dela du is.close fla (sans IOException)");
       } 
       catch (IOException io) {
  //              DEBUG(26,"(3) expected IOException (available())");
        }
  }
  
   String pct(int ch){
                      int h=ch / 16;
                      int u=ch % 16;
      return("%"+HEXA.substring(h,h+1)+HEXA.substring(u,u+1));
      
   }
   
   String pctStr(String in){
       char ch1=' ';
       StringBuffer w=new StringBuffer();
       for (int i=0;i<in.length();i++){
           ch1=  in.charAt(i);
           if ( (ch1 <= ' ') || (ch1>'z')  || (ch1 == '#')|| (ch1 == '&') || (ch1 == ';')  ) {
                    w.append(pct(ch1));
                } else {
                    w.append((char)ch1);
                 }
         
       }
     return(w.toString());  
   }
   String visibleStr(String in){
       char ch1=' ';
       StringBuffer w=new StringBuffer();
       for (int i=0;i<in.length();i++){
           ch1=  in.charAt(i);
     switch (ch1){
        case ' ':w.append("_space_");
            break;
        case '#':w.append("_diese_");
            break;
        case '&':w.append("_amp_");
            break;
        case ';':w.append("_PV_");
            break;
         default: w.append((char) ch1);
  }
     
         
       }
     return(w.toString());  
   }
   
   private boolean extrConfEtDecodeError(String recu){
    // extraire la configuration de la réponse et l'exécuter
    //   log("CONF("+ou+"): "+recu);
    // 20100408 possibilite reprise si usePim
    String nextconf=""   ;
    usePim=false ; //a priori
          int isep=recu.indexOf("|");
          if (isep==-1){
              // pas de conf, ren à faire!
          }
          else {
              nextconf=recu.substring(isep+1);    
              isep=nextconf.indexOf("?");
              if (isep>=0)       nextconf=nextconf.substring(0,isep);
       //       DEBUG(2381,"ConfigReçue ("+ou+")==="+configRecue+"===");
              if (nextconf.length()==0) {
                 if (S60) usePim=true;
              }else{        
                  // si config reçue, ignorer PIM
                 configRecue=nextconf;
                 if( decodeConfigError("extrConf:"))  return(true);
          
              }
          }
       return(false);   
   }
   

  private void getUrlAndFollow(boolean dump, String urlbis) {
     HttpConnection cg = null;  // pour getUrl
    
     lastUrl=urlbis;
     // demander une url et suivre si redirigé jusque'à
     // profondeur 8 (dit IMPASSE)
     // intercepter coordonnées si vers carto!
     nbGet=nbGet+1;
     urlNext="";    // variable globale de retour; sera mise à redirerection si Location:
     lastMailRc="fUnomail" ; // mis a blanc au début
//       
     cg = null;
     InputStream is = null;
//
     INFO (616751,"GET:"+pctStr(urlbis));
  
     int rc=-1;
 
     try{ // global peut-etre de trop
        try{
          cg = (HttpConnection)Connector.open(urlbis);
        }catch (ConnectionNotFoundException cnfe){
             ERROR (8,"connexion not found!",cnfe);
             lastMailRc="fUCnf"+cnfe.toString() ; // mis a blanc au début
             return;
        } catch (IOException cnfe){
          ERROR (9,"io exception!",cnfe);
          lastMailRc="fUIoex"+cnfe.toString() ; // mis a blanc au début
          return;
        }
        try{    
            cg.setRequestMethod(HttpConnection.GET);
        }
        catch (Exception e) {
            ERROR(11,"catch exception while request ",e);
            return;
        }
  
        try{
            
          //   ECRAN("set properties","_");
          cg.setRequestProperty("User-Agent", "Pof/1.0 (HTTP Win32)");
          cg.setRequestProperty("Accept", "text/vnd.wap.wml,application/vnd.wap.wmlc");
          cg.setRequestProperty("Accept-Charset", "iso-8859-1");
          // 20081120 selon http://java.sun.com/developer/J2METechTips/2001/tt0820.html
          cg.setRequestProperty("Connection", "Close");
          
        }
        catch (Exception ex1){
                ERROR(12876,"set properties request ",ex1);
                return;
        }

        try{
        lastMailRc="fUGetRc(1)" ; // mis a blanc au début  
        boolean getResponseReussi=false;
        //     boolean getResponseAbandon=false;
        int insisteHtml=0;
        for ( insisteHtml=0;
            (insisteHtml<insisteHtmlMax) && ! getResponseReussi ;
            insisteHtml++){
               if (insisteHtml>0) DEBUG (123432,"Retry html "+insisteHtml);
               try{
                 rc = cg.getResponseCode();
                 if (rc!=-1) getResponseReussi=true;
               } catch (IOException e5) {
//                 DEBUG(131312,"PAS ACCES INTERNET, exception e5 "+insisteHtml,e5);
                   ERROR(131312,"PAS ACCES INTERNET, exception e5 "+insisteHtml);
               }   catch (Exception e6) {
   //             DEBUG(131312,"PAS ACCES INTERNET, exception e6 "+insisteHtml,e6);
                  ERROR(131312,"PAS ACCES INTERNET, exception e6 "+insisteHtml);
               }  // e6
       
            }   // fin for insiste html
      
        //   tester rérussi
        if (!getResponseReussi){
                  log ("IOException getResponseCode(1) ");
                  log("pointsFaits:"+pointsFaits);
                  log ("insisteHtml:"+insisteHtml);
                  log("Url:"+pctStr(urlbis));
       //           xyxyEcran="pas Orange";
                  // close cg
                  cg.close();
                  if (cg!=null) cg=null;
                  return;
         
        }
        lastMailRc="fU(14)Rc="+rc;
}
        catch (Exception ex1){
                ERROR(12876,"premier groupe ",ex1);
                return;
        }

        try{
        switch (rc) {
           case  200:    // httpOK sera traité plus bas 
              //       DEBUG (15,"réponse rc OK (200) = OK! ");  
              trouve="N";
              log("IMPASSE(OK!): "+pctStr(urlbis));
              //        DEBUG(16,"trouve mis a N 1");
              lastMailRc="fU(15)Rc="+rc+"N";
              getDataHtml(dump,cg);
              if (ABANDON) return;
              break;
           
           case 301:
           case 302: 
              String redir;
              redir=cg.getHeaderField("Location"  );
              if (dump) log("REDIR:"+pctStr(redir));
            
              lastMailRc="fU(17)Rc="+rc+" "+redir;
              int xloc= redir.indexOf("locaOrange");
 // enregistrer les redirections supplémentaires
              if (!urlbis.equals(AMORCE) && (xloc==-1))  log("REDIR(1): "+pctStr(redir));
         //       log("REDIR(2): "+visibleStr(redir));
            
       //     ECRAN("fU2 "+ version + "_"+locSucces+"/"+attempt+"_redir_"+xloc,redir  );
               
              if ( xloc != -1) {     // trouvé locaOrange
                  xloc=redir.indexOf("X=");
                  String xy=redir.substring(xloc+2, redir.length());
 
                  // extraire 
                  xloc=xy.indexOf("Y=");
                  // nettoyer le Y=
                  lat=xy.substring(0,xloc-1);
                  lon=xy.substring(xloc+2,xloc+10);
       //           xyxyEcran=xy.substring(0,xloc-1)+"\n"+xy.substring(xloc+2,xloc+10);
                  // numero (reutilise xloc mal nommé)
                  xloc=redir.indexOf("IDP=");
                  String nextID=redir.substring(xloc+4,xloc+14 );
                  if (!sessionID.equals(nextID)) {
                     sessionID=nextID;
                     
                     log("NUMERO: "+sessionID);
                   }
                  trouve=TROUVE;
                  
                 locSucces=locSucces+1;
              } else {  // xloc=-1 pas trouvé, il n'y pas de locaOrange ?        
                         
                   //placer la redirection qui va être faite
                   urlNext=redir;
              }
              break;
       
              default:
                log ("RC: "+rc+" ("+urlbis+")")    ;
   // on pourrait donner contenu si ill y a lieu        
   // ne pas sortir faire close
          
              }  // fin de switch
        }
        catch (Exception ex1){
                ERROR(12876,"pendant switch "+ex1.toString(),ex1);
                return;
        }

        try{
          cg.close();
        }
        catch (IOException ioe){
                ABEND (28,"IOEXception during c.close:",ioe);
                return;
        }         
    
       is = null;
       cg = null;
    
       
   } // try global  normalement pas grand chose à attrapper ci dessous // try global
   catch (NullPointerException ex1) {
        ABEND(31,"NullPointerException getUrlAndFollow reading from http: "+urlbis,ex1);
        return;
   
        
        
   } catch (IllegalArgumentException ille) {
            ABEND (34,"illegal argument", ille);
            return;
   } 
   catch (SecurityException se) {
            // Check if an invalid proxy web server was detected.
  //          t = new TextBox("Vous avez refusé l'accès GPRS", se.getMessage(), 128, 0);
            ABEND(7167,"Vous n'avez pas autorisé l'accès Internet ", se);
            return;
   } 
   catch (Exception e) {
            
           ABEND (35,"dans getUrlAndFollow catch exception",e);
           return;
    }

   if (is != null) {
            try {
                is.close();
            } 
            catch (Exception ce) {
// ne pas faire ettention à une erreur!
            }
    }

    
    if (cg != null) {
            try {
                cg.close();
            } 
            catch (Exception ce) {
// ne pas faire attention à une erreur!
            }
     
//
     String recu=bbrut.toString();
     if (recu.length()==0){
     //   DEBUG (37,"--fin de getUrlAndFollow sans contenu--------------------------------------------");
        
     }else{
      String toLog=bbrut.toString();   
      if (toLog.indexOf("Souhaitez vous vous localiser en mode manuel")>0)toLog="PASLOCMANUEL:";
      if (toLog.indexOf("avez plus de cr")>0)toLog="PLUSCREDIT:";
      
       log("GETURL-RECU: "+toLog.toString());
     } // else  
     
    } //  if (c != null) {
        
  }
       

  private void uploadResults(String lettre,String sujet,String contenu){
     GLOBup++;    
      String pleinSujet =sessionID+"_"+stamp+"_"+GLOBup+"_"+pointsFaits+"_V"+version+"_"+sujet;
           uploadResultsByPost (lettre,pleinSujet,contenu.toString());  
  }
  
void bmerase(){
   if (bm.length()>0) bm.delete(0, bm.length());       
    
}
  private void uploadResultsByPost(String typeCILR, String sujet, String contenu) {
    uploadByPostReussi=false; 
    lastMailRc="Mail:essai";
// ET NUIT!
//   DEBUG(7182,"uploadResultByPOst "+optionInternetMax);     
 if (internetNow()){     // tout le reste de upload...
  // netoyer le fichier bm pour la reponse
   bmerase();
   HttpConnection cm=null;
   InputStream is=null;
 //  String urlMail=logsmphp; // sans type ou type="R"
 //  DEBUG (616752,"POST:"+urlMail);
   lastMailRc="Mail:rapport";
       
 //  long len = -1;
//   long count = 0;
   int rc;
   try {
          cm = (HttpConnection)Connector.open(logsmphp);
   }catch (IOException sopencm) {
      lastMailRc="Mail:catch2";
            ERROR (528,"IOException interceptée",sopencm);
        //    s.printStackTrace();
            return;
   }catch (Exception sopencm) {
      lastMailRc="Mail:catch2";
            ERROR (527,"UploadResultByPost interceptée open "+logsmphp,sopencm);
        //    s.printStackTrace();
            return;
   }
 
   try{         
   cm.setRequestProperty("User-Agent", "Pof/1.0 (HTTP Win32)");
   cm.setRequestProperty("Accept", "text/vnd.wap.wml,application/vnd.wap.wmlc");
   cm.setRequestProperty("Accept-Charset", "iso-8859-1");
   cm.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
 // 20081120 selon http://java.sun.com/developer/J2METechTips/2001/tt0820.html
   cm.setRequestProperty("Content-Length",Integer.toString(contenu.length()));
  // pas dans exemple
   cm.setRequestProperty("Connection", "Close");
  // voir disconnect ?        
             
   cm.setRequestMethod(HttpConnection.POST);
   }catch (IOException sopencm) {
      lastMailRc="Mail:catch2";
            ABEND (52,"IOException interceptée",sopencm);
        //    s.printStackTrace();
            return;
   }catch (Exception sopencm) {
      lastMailRc="Mail:catch2";
            ABEND (52001,"Exception interceptée",sopencm);
        //    s.printStackTrace();
            return;
   }
   OutputStream osu=null;
   try{ 
        osu=cm.openOutputStream();
   }catch (IOException sopencm) {
      lastMailRc="Mail:catch2";
            ABEND (52002,"SecurityException interceptée",sopencm);
        //    s.printStackTrace();
            return;
              
   } catch (Exception sopencm) {
      lastMailRc="Mail:catch2";
            ABEND (52003,"Exception interceptée",sopencm);
        //    s.printStackTrace();
            return;
              
   }
    String tout="type=" + typeCILR + "&numtel="+sessionID+"&sujet="+sujet.toString()+"P"+
             "&tomail="+toEmail.toString()+"&text=" +contenu.toString();
    try {
        osu.write(tout.getBytes());
    }
    catch (Exception e){
      DEBUG(2405,"MailByPost catch Exception osu.write",e)  ;
      // close à faire
      return;
    }

    try{
        osu.close();
    }catch (Exception e){
        DEBUG (787878,"osu.close()",e);
        log ("ERREUR 787878 osu.close() "+e.toString());
        //close à faire
        return;
    }
    
    lastMailRc="Mail:write";
    rc=0;
    try{  
       rc = cm.getResponseCode();
    }
    catch (Exception e) {
           ABEND(2401,"getResponseCode(4) Post URL="+logsmphp,e);
           // si erreur 2401 faudrait tenter une ré-émission
           // vu vendredi matin après 600 points!
           // close
        return;
    }
      
    lastMailRc="MailByPost a eu:" + rc;
    //       ECRAN("MailByPost a eu RC","Rc="+rc);
    //         DEBUG(54,"MailByPost a eu RC Rc="+rc);
            
    if (rc != HttpConnection.HTTP_OK) {
                lastMailRc="Mail:NoOkRc="+rc;
             //   ECRAN("10","ERREUR RC MAIL "+rc);      
                DEBUG (55,"Erreur rc="+rc+" ouverture url:"+logsmphp );
                bm.append(logsmphp);
                return;
                
    }  else  {
        //     ATTENDRE(4,"Ok de mail2 url urlbis="+urlbis);
        lastMailRc="Mail:rcOk";
             
        try{
            is = cm.openInputStream();
        }catch(Exception eff){
            ABEND(321221,"PO",eff);
        }

         int nnlluu=0;
         lastMailRc="Mail:read";

//ATTENDRE(4,"Ok de mail2 url len pas utilisé="+len);
//         byte[] data = new byte[1000];
int n=-1;
         try{
          n = is.read(data, 0, data.length);
}catch(Exception dff){
ABEND(13331,"bbb",dff);
}
    for (int i = 0; i < n; i++) {
              ch = data[i] & 0x000000ff;
              bm.append((char)ch);
              nnlluu=nnlluu+1;
         }
             
         try {
                if (is != null) is.close();
                if (cm != null)  cm.close();
         } catch (Exception ce) {
                DEBUG(56,"Error closing connection");
         }

         try {
                int len = is.available();
                DEBUG(57,"Inputstream failed to throw IOException after close");
         } catch (IOException io) {
                // vide, normal, exception est OK!
         }

    // DEBUG("dans mail2 b.length="+b.length());
     
         bm.append (" en réponse a atempt="+attempt);
     //
         String aff2=bm.toString();
         // à fare par ECRAN

         ECRAN("réponse uploadResults:",aff2);
  //       DEBUG(5131,"appel de extrconfetdecode pour "+aff2);
         if (extrConfEtDecodeError(aff2)) {
            ABEND(6723232,"config téléchargée erreur:"+aff2);
             return;
         }
   //
  //      DEBUG(6723232,"config apres"+configPrev);
         uploadByPostReussi=true; 
     // plutot close ?
         is = null;
         cm = null;
    } // du else try pourrait être plus bas   
 
// on pourrait peut etre virer ce try/catch
    
    if (is != null) {
            try {
                is.close();
            } catch (Exception ce) {
            }
        }

    if (cm != null) {
            try {
                cm.close();
            } catch (Exception ce) {
    }
  }
 } // internet ou nuit     
} // uploadResults


 
boolean setOption(String nom,/*String*/ char lettre){
    // 
    boolean opt;
    int lmaj=lettre;
    int lmin=lettre;
    if ((lettre>='a') && (lettre<='z')) lmaj=lmaj-32;
    if ((lettre>='A') && (lettre<='Z')) lmin=lmin+32;
    
    
    int oumin=configRecue.indexOf(lmin);
    int oumaj=configRecue.indexOf(lmaj);
   // DEBUG(4543,"min="+(char)lmin+" à " +oumin+" maj="+(char)lmaj+ " à "+oumaj);
    if ( (oumaj>=0) && (oumin >= 0)) return false;  // Aa est une erreur
    int ou=oumin+oumaj+1; // l'un des deux est vaut -1
    // DEBUG (3041,"setOption "+nom+" " +lettre+" "+configRecue);
    if (ou>=0) {
         opt= true;
         log (nom+"("+lettre+"): true");
//        configActuelle=configActuelle+lettre;
        // Oter la lettre traitée       
        if (ou==0) {                    // c'est la première'
            configRecue=configRecue.substring(1);
        } else if (ou == configRecue.length()-1) {  // la dernière
            configRecue=configRecue.substring(0,ou);
        }else {    // en cours
        configRecue=configRecue.substring(0,ou)+configRecue.substring(ou+1);
        }
    } else {
         opt=false;    
    }
    return (opt);  
} 

void oteDeb(int ix){
      // retirer de la config la partie qui a été traitée avant les options
  if (ix==configRecue.length()-1) {
      configRecue="";
  } else {
     configRecue=configRecue.substring(ix+1);
  }

}

String getChaineConfig(String prevVal,char sep,String quoi){
   int ix=configRecue.indexOf(sep);
   if (ix==-1) return "";
   // int i1=configRecue.indexOf("<");
   int inext=configRecue.length(); //le premier separateur au delà de sep a prioroi a pres fin
   int iautre=-1;
   for (int lequel=0;lequel<listeApres.length();lequel++) {
     iautre=configRecue.indexOf(listeApres.charAt(lequel));
     if ((iautre<inext)&& (iautre>ix)) inext=iautre;
   }
   String w="";  
   String v=prevVal;
   String dev="";
   v=configRecue.substring(ix+1,inext);
   w=v;
   dev="";
   if (v.length()==1){
       w=abrev(v);
       dev="-->"+w;
   }   
   configRecue=configRecue.substring(0,ix)+configRecue.substring(inext); 
   log (quoi+"("+sep+"):"+v+dev); // +" reste:"+configRecue); 
    
   return(w);
}

int getNombreConfig(char sepfin,String quoi){
//DEBUG(541498,"getNombre("+sepfin+") "+quoi);
    int valeur=0;
char unefin= ' ';
   int finDemandee =configRecue.indexOf(sepfin);
   // caractere fonction n'est pas là
   
//DEBUG(541497,"getNombre FIN="+finDemandee+" " +finOpt);
   if ((finDemandee==-1)||(finDemandee>debutOpt))   return(0);
   
  int unx=-1;    
  String debut=   configRecue.substring(0,finDemandee);
//DEBUG(541497,"getNombre debut="+debut);
  for (int iune=0;iune<listeAvant.length();iune++) {
      unefin=listeAvant.charAt(iune);
      if (unefin!=sepfin){
        //      DEBUG (1941,sepfin +" ?precede de "+unefin+" dans "+debut );
        unx=debut.indexOf(unefin);
        if (unx>=0 )  debut=debut.substring(unx+1);
  //      DEBUG (1940,"debut="+debut);
      }
  }
  
 // DEBUG(54981,"chaine==="+debut+"===");
  // supprimer espace initiaux
   while ((debut.charAt(0)<=' ') && (debut.length()>0))  debut=debut.substring(1);
  // et finaux
   while ((debut.charAt(debut.length()-1)<=' ') && (debut.length()>0))  debut=debut.substring(0,debut.length()-1);
  //
//DEBUG(541498,"getNombre trouve:"+debut);
  try{
  valeur= Integer.parseInt(debut);
}catch(Exception e){
  ABEND(541498,"erreur parseint de "+debut.length()+"\n=="+debut+"==",e);    
  return 0;
}
// String next="";
configRecue=configRecue.substring(0, finDemandee-debut.length())+configRecue.substring(finDemandee+1);
log(quoi +"("+sepfin+"): "+valeur);
//DEBUG (1944,"config après:"+configRecue);
//  DEBUG(4520,"reste:"+configRecue.toString() );
 // DEBUG (4541,"rep getNombre:"+quoi+"("+sepfin+")="+valeur);
  return(valeur);
}

int bornerApres(){
    //trouver le premier séparateur 
    int i1;
int finLoc=configRecue.length();
// String liste="*><!";
int itrouve=-1;
for (int lequel=0;lequel<listeApres.length();lequel++){
    itrouve=configRecue.indexOf(listeApres.charAt(lequel));
    if ((itrouve<finLoc)&&(itrouve>-1)) finLoc=itrouve;
}
  return finLoc;
}

int bornerAvant(){
    //trouver le premier séparateur 
    int i1;
int finLoc=-1;
// String liste="*><!";
int itrouve=-1;
for (int lequel=0;lequel<listeAvant.length();lequel++){
    itrouve=configRecue.indexOf(listeAvant.charAt(lequel));
//    DEBUG(4141,"Avant ("+listeAvant.charAt(lequel)+")="+itrouve);
    if ((itrouve>finLoc)) finLoc=itrouve;
}
  return finLoc;
}

boolean internetNow (){
        String d=date(HHMMSS);
    return (optionInternetMax||
           (optionInternetNuit && (d.compareTo(HEUREMATIN)<0) || (d.compareTo(HEURENUIT)>0) ));
}

String abrev(String lettre){
    String a="";

    if (lettre.equals("0"))a="antiguide@free.fr";
    if (lettre.equals("1"))a="flavigny@free.fr";
    if (lettre.equals("2"))a="marchal@inrets.fr";
    if (lettre.equals("0"))a="antiguide@free.fr";
    if (lettre.equals("A"))a="http://www.logsm.net/logsmpo.php";
    if (lettre.equals("B"))a="http://antiguide.free.fr/logsm/java/logsm.php";
    if (lettre.equals("a"))a="file:///C:/Data/Sounds/Simple";
    if (lettre.equals("b"))a="file:///C:/predefgallery/predefrecordings";
     
  return a;
}

void setLock(){
 }

void faireZombie( boolean z)    {
            zombieDone=true;
            if (z){
                zombie=true;
            }else{
               displayOpen=true;
               display = Display.getDisplay(this); // en test supprime 20100302
            }
         }

boolean configPimModifiee(){
  boolean ret=false;  
  if (usePim){   
     String cp=configPIM();
     if ((cp.length()!=0) && (!cp.equals(configPrev))) ret=true;
  }
  return ret;
}

boolean decodeConfigError(String ouCa){
 // la config est dans une variable globale configRecue!

   // ne rien faire si pas chgt 
    
if ((configRecue.length()!=0) && (!configRecue.equals(configPrev))) {
       configPrev=configRecue;
       emettreCarConfig=true;
// determiner la fin des options
  finOpt=bornerApres();
  debutOpt=bornerAvant();
       
   // écrire dans la log si changement
       log("CONFIG("+ouCa+"): " +configRecue);
   


 shutDown=60*getNombreConfig('-',"Shutdown");
if (ABANDON) return (true);

    gapSecondes=60*getNombreConfig('+',"delay");
if (ABANDON) return (true);

   nbGroupage= getNombreConfig('/',"groupage");
if (ABANDON) return (true);

  iterations= getNombreConfig('#',"iterations");
 // log("Iterations mis a "+iterations);
   if (ABANDON) return (true);
  

  
if (jsr179Version !=null)  timeout179= getNombreConfig('"',"timeoutJsr179");  // "
   if (ABANDON) return(true);
//////
   
 
  if (nbGroupage==0) nbGroupage=1;
 
  
  periodePointS= 60*getNombreConfig((char) 39,"période");   // 's
if (ABANDON) return (true);
  // fini des préfixes facultatifs
  String    forged="";
       toEmail=getChaineConfig (toEmail,'>',"toEmail");
 
       forged=getChaineConfig(forged,'~',"Forged");
         if (forged.length()>0) modeleTelephone=forged;
 
         home=getChaineConfig(home,'*',"Home");
 
       logsmphp=getChaineConfig (logsmphp,'!',"HTTP");
     
   forged =getChaineConfig (sessionID,'<',"numero");
      if (forged.length()>0) sessionID=forged;
    
   // la ligne suivante ne fonctionne pas (reste ~)     
   //     if (finOpt>-1) configRecue=configRecue.substring(0,finOpt);
   //  DEBUG (5652323,"config Option="+configRecue);
   // test de la possibilité d'avoir un bip!     
   //     if (setOption("testBeep","$")) beep();
    
         //optionPack
         if (!zombieDone) faireZombie( optionZombie=setOption("optionZombie",'Z'));
        
   jsr179Accuracy=0;
    //     optionConfig=setOption("optionConfig","C");  // relire Pim
         optionPack=setOption("optionPack",'K');
         optionDump=setOption("optionDump",'Y');
        optionBluetooth=setOption("optionBluetooth",'B');
//         optionTous=setOption("optionTous","T");
         optionNoTrafic=setOption("optionNoTrafic",'X');
      if (jsr179Version !=null)   optionGps=setOption("optionGps",'G');
         optionVoir=setOption("optionVoir",'V');
    //     optionFatigue=setOption("optionFatigue","*");
         optionRaz=setOption("optionRAZ",'0');
         if (setOption("optionRAZ",'O'))optionRaz=true;  // la lettre aussi
         optionApi=setOption("optionApi",'A');
  //       optionGetConfig=setOption("optionGetConfig","C");
         optionDebug= setOption("optionDebug",'D');
         optionLog= setOption("optionLog",'J');
         optionHorloge=setOption("optionHorloge",'H');
         optionInternetMax=setOption("optionInternetMax",'I');
         optionFichier= setOption("optionFichier",'F');
  //       optionListe=setOption("optionListe","L");
         optionInternetNuit=setOption("optionInternetNuit",'N');
         if (!backlightDone) {
            optionBacklight=setOption("optionBacklight",'S');
             backlightDone=true;
         }
   //      optionTelephone=setOption("optionTelephone","%");
         optionWriteFinal=setOption("optionWriteFinal",'W');
         optionFirst=setOption("optionFirst",'1');
         if (setOption("optionFirst",'U')) optionFirst=true;
         optionQuit=setOption("optionQuit",'Q');
  
//' accuracy
     if (optionGps && (jsr179Version !=null)) {
         if (jsr179Accuracy==0) if (setOption("Accuracy",'2'))jsr179Accuracy=100;
         if (jsr179Accuracy==0) if (setOption("Accuracy",'3'))jsr179Accuracy=1000;
        if (jsr179Accuracy==0) if (setOption("Accuracy",'4'))jsr179Accuracy=10000;
        if (jsr179Accuracy==0) if (setOption("Accuracy",'5'))jsr179Accuracy=100000;
         
        log("ACCURACY:"+jsr179Accuracy); 
     }
         if (optionDebug){
         waitDebug=0;
         // pris meme si pas option debug !
         if (waitDebug==0) if (setOption("Délai",'6')) waitDebug=6;
         if (waitDebug==0) if (setOption("Délai",'7')) waitDebug=7;
         if (waitDebug==0) if (setOption("Délai",'8')) waitDebug=8;
         if (waitDebug==0) if (setOption("Délai",'9')) waitDebug=9;
         }
         // si path
         // POURQUOI ?
//         if (optionPath||optionTous){
         if ( optionFichier |optionWriteFinal ){
            if (home.indexOf("file:///")<0){
                ABEND(43131,"Options F, W exigent path absolu (file:///)\n"+home);
                return(true);
             }
                // évidemment doit être absolu
             HOMEFSLOCAL=home;
             log("HOME: "+home);
         }
  
     if (configRecue.trim().length()!=0) {
         ABEND (454545,"options inutiles: "+configRecue);
     
         return true;
     }
     
 // verification email pour upload   
     if ((optionInternetMax||optionInternetNuit) && toEmail.equals("")) 
     {   ABEND (174,"manque paramètre toEmail!");
       return (true);
     }
 
     if (optionFichier || optionWriteFinal){
        if (home.length()==0){
       ABEND (174,"option F T W & LOCK exige chemin local (*) ");
       return (true);
            
        } 
     }
     // on construit les noms 
         if (optionWriteFinal)   FICHIERABEND=home+"/"+stamp+".txt"; //1
  if (optionFichier) {
      FICHIERLOCK=home+"/"+stamp+".lck";
  
     FICHIERXY=home+"/"+stamp+extxy;
     FICHIERYX=home+"/"+stamp+extyx;
  }  
 
     if (optionWriteFinal) log("FICHIERFINAL:"+FICHIERABEND) ;
  
     
 }   // decodeConfig

 domodele();
 
   return(false);
}


private void log(String texte){
     resumeTout.append(texte+"\r\n");
}


private void logClear(){ 
 resumeTout.delete(0, resumeTout.length()-1);
}      


private String configPIM(){
  String todo1="";
 
  
  String v = System.getProperty( "microedition.pim.version" );

      if( v == null ){
       // FCOP not available
     log ("PIMOP: NOT AV.");
   //  ABEND (11111,"ABANDON microedition.io.file.FileConnextion.version NOT AV.");
     return("");
   }
//    log("PIM: microedition.pim.version "+v);

// seulement prems!
  
  ToDoList list=null;  
  try {list= (ToDoList) singleton.openPIMList(PIM.TODO_LIST,PIM.READ_ONLY);
  
  } catch (PIMException e){
    return("");
  }
  // DEBUG(18541,"todoList:\n"+list.toString());
  int [] possible =  list.getSupportedFields();
 
  if (premsPIM) {
      premsPIM=false;
  
  String possibleListe="";
  for (int ip=0;ip<possible.length;ip++){
        possibleListe=possibleListe+possible[ip]+" " ; // +Array.getLength(possible));
     }
  DEBUG (31414,"ToDoList: "+possibleListe);
 // log ("ToDoList:"+possibleListe);
  }
 // DEBUG (32414,"Summary:"+Event.SUMMARY);
  ToDo task=null;
  Enumeration lenum=null;
  try{
  lenum=list.items();
  }catch (PIMException e){
    return("");
  }
  int ct=0;
  while (lenum.hasMoreElements()){
  task=(ToDo)lenum.nextElement();
//    DEBUG(43133,"task "+ct+"\n"+task.);
    //DEBUG(43331,"-->"+task.)
/*    if (list.isSupportedField(Event.NOTE)){
        log ("NOTE:"+task.getString(task.NOTE,0));
    }
  */
    if (list.isSupportedField(Event.SUMMARY)){
        String todox=task.getString(task.SUMMARY,0);
        if (todox.indexOf("logsm:")==0)
        {    DEBUG(17661,"SUMMARY:"+todox);
         //  log("SUMMARY:"+todox);
        }else{
          //          log("SUMMARY-Ignored:"+todox);
        }        
   //     DEBUG(128743,"SUMMARY:"+todox);
          if (todox.indexOf("logsm:")==0) {
               if (todo1.length()>0){
                 ABEND (12122,"Config par PIM ambigue");
                 return("");
               }
               todo1=todox.substring(6);
     //      DEBUG(128743,"ConfigPIM:"+todo1);
          }
        
    }
    ct++;
   }
// DEBUG(454,"configPim rerourne:"+todo1); 
 return( todo1);
}

 
// en fait read & send
private boolean appendFileSmartError(String urlin, String urlto, StringBuffer quoi){
    // ersatz en attente de append 
// DEBUG (111571,"appendFile "+urlin +" vers " +urlto); 
//
long tot=0;
 OutputConnection connOut=null;
 OutputStream os=null; 
 InputStream isf=null; 
 InputConnection connIn=null;

 
 int length=-1;
// byte[] data = new byte[TAILLEBUFFERSMART];
 
 // creer si besoin
  try{    
    FileConnection fconn = (FileConnection) Connector.open(urlto) ;
    if (!fconn.exists()) fconn.create();
    fconn.close();

  }catch (IOException e4){
    ABEND (111571,"appendFile IO création/fermeture aborted ",e4); 
    return true;
  }

 //  reecriture

 try{
   connOut=  (OutputConnection) Connector.open (urlto,Connector.WRITE); 
 } catch (SecurityException e){
    ABEND (1115724,"appendFileSmart SECURITY création/fermeture  "+e); 
    return true;
 }catch (IOException e){
     ABEND (111182,"appendFileSmart Exception open write: "+urlto,e);
     return true;
     
 }
   
 //DEBUG (76233,"Ok création de connOut write "+urlto);
 
 if (urlin.length()>0){
 try{    
    FileConnection fconn = (FileConnection) Connector.open(urlin) ;
    if (!fconn.exists()) {
        ABEND (67233,"append sur fichier non existant "+urlin,null);
        return true;        
    }
    fconn.close();

    }catch (IOException e4){
    ABEND (111571,"appendSmart IO lecture/fermeture aborted ",e4); 
    return true;
    }

 
 //  lecture et copie
 
 try{
   connIn=  (InputConnection) Connector.open (urlin,Connector.READ); 
 }catch (Exception e){
     ABEND (111181,"appendFilesSmart Exception open: ",e);
     return true;
 }

 try{
   isf = connIn.openInputStream();
 }catch (IOException e){
  // 
             
    ABEND(1112171,"appendFileSmart exception openInputStream ",e);
     return true;
 
 }catch (Exception e){
    ABEND(1112172,"appendFileSmart exception openInputStream ",e);
  return true;
 }
 
 } // lecture ajoute
 //  DEBUG(1112133,"au dela de connIn ouvertur connOou.output "+urlto);
    
 try{
   os = connOut.openOutputStream();
 } catch (SecurityException e){
    ABEND (1115723,"appendFileSmart SECURITY création/fermeture aborted "+e); 
 //   return;
 }catch (IOException e){
   ABEND(1112132,"appendFileSmart IOexception openOutputStream "+urlto,e);
  return true;
 
 }catch (Exception e){
  // on échoue ICI!   
  ABEND(111214,"appendFileSmart other Exception openOutputStream ",e);
 }
 
 
 if (urlin.length()>0){
 
  // copier ancien
   boolean termine=false;
   
   while (!termine){
             try{
             length = isf.read(data, 0, data.length);
            }catch(Exception po){
           ABEND(142302,"Erreur appendFileSmart data "+urlin+ " "+urlto,po);
           return true;
      }
        tot=tot+length;
   //     DEBUG(142310,"lu tot="+tot);
      // moche
      StringBuffer tow=new StringBuffer();
      for (int i=0;i<length;i++){
          tow.append((char)data[i]);
      }
      try{
      os.write(tow.toString().getBytes());
      }catch(IOException e){
         ABEND(8934,"appendFileSmart en cours de copie",e);
                 return true;
      }
     if (length!=data.length) termine=true; 
   }

   
 try{ 
    isf.close() ;

 } catch (IOException e){
    ABEND(111241,"appendFileSmart exception close "+e,null);   
    return true;   
 }
    
 
 try{ 
    connIn.close() ;
 } catch (IOException e){
    ABEND(111242,"appendFileSmart exception close connIn"+e,null);   
    return true;   
 }
   
 }
 // DEBUG (8934,"cpie tot="+tot);
 //  DEBUG(111248,"fin de lecture");
   try{
   os.write(quoi.toString().getBytes());
   }catch (IOException e){
    ABEND(111243,"appendFileSmart IOException write ",e);
    return true;    
 }catch (Exception e){
   ABEND(11124,"appendFileSmart Exception write ",e);
   return true;  
 }  
   tot=tot+quoi.length();
 try{ 
    os.close() ;
 } catch (IOException e){
    ABEND(111249,"appendFileSmart IOException close ",e);
    return true;
 }
   catch (Exception e){
    ABEND(111248,"appendFileSmart Exception close ",e);
    return true;
 }
 //   log("appenfFile:"+urlto+ " ["+tot+"]");
 // DEBUG (8934,"allonge tot="+tot);
    return false;
 }
 
   


 
private boolean deleteError(String url){
  String r= rawEncodeSizeDeleteRename(DELETE,url,null);
 
  return r.length()!=0;
}
private String sizeNoError(String url){
  return rawEncodeSizeDeleteRename(TAILLE,url,null);
 }
private boolean renameError(String url,String newname){
  String r= rawEncodeSizeDeleteRename(RENAME,url,newname);
  return r.length()!=0;
}

private String rawEncodeSize(int quefaire,String url){
 return  rawEncodeSizeDeleteRename(quefaire,url,null);   
}
private String rawEncodeSizeDeleteRename(int quefaire,String url,String newname ){
 
    
 if (quefaire==DELETE){
 try{    
   FileConnection connDel=  (FileConnection) Connector.open (url);
//   DEBUG(6734,"delte opened:"+url);
   connDel.delete(); 
//   DEBUG(6735,"delte deleted");
   
 }catch (IOException e){
     return ("ERROR");
 }
    return "";  
     
 }
 
 if (quefaire==RENAME){
 try{    
   FileConnection connRen=  (FileConnection) Connector.open (url); 
    connRen.rename(newname);
   }catch (IOException e){
     return ("ERROR");
 }
   //pas de close ?  connRen.close();
    return "";  
     
 }
 
 // donc selse
 
 //  lecture
 InputConnection connIn=null;

 try{
   connIn=  (InputConnection) Connector.open (url,Connector.READ); 
 }catch (Exception e){
     ABEND (111181,"readFile Exception open: ",e);
     return("");
 }

 InputStream isf=null; 
 try{
   isf = connIn.openInputStream();
 }catch (IOException e){
  // 
             
    if (quefaire==TAILLE) return("");  
    ABEND(111217,"readFile exception openInputStream ",e);
  return("");
 
 }catch (Exception e){
    if (quefaire==TAILLE) return("");  
    ABEND(111217,"readFile exception openInputStream ",e);
  return("");
 }
 
 int length=-1;
 int lengthTot=0;
 boolean eof=false;
 // byte[] data= new byte[TAILLEBUFFERSMART];
 while (!eof){
       try{
       length = isf.read(data, 0, data.length);
       }catch(Exception po){
           ABEND(1423,"Erreur readFile data",po);
           return("");
      }
 if (length==-1) {
      DEBUG(671212,"fichier taille -1 "+url);
 }            
      lengthTot=lengthTot+length;
      
      if (length != data.length) eof=true;
      
 }
 
 //  DEBUG(123,"Apres lecture");
 StringBuffer buf= new StringBuffer();
 //buf.
 switch (quefaire){
 
  case CONTENU:
      ABEND (65181,"CONTENU IMPOSSIBEL");
      if (ABANDON) return "";
       for (int in=0;in<length;in++) {
 //      buf.append ((char) data[in]);
       buf.append (String.valueOf( (char) data[in]));
   }
   break;
 
     
   case TAILLE:
     if (length==-1) { // vide
     }else{
         buf.append (lengthTot);
     }   
   //  DEBUG(1843,"TAILLE="+buf.toString());
     break;
    
   case EXISTS:
         break;
         
     
 }
 
 try{ 
    isf.close() ;

 } catch (IOException e){
    ABEND(11124,"readFile exception close "+e);   
    return("");   
 }
    
 
 try{ 
    connIn.close() ;
 } catch (IOException e){
    ABEND(11124,"readFile exception close connIn"+e);   
    return("");   
 }
 //   ABEND(1000,"lu:\n"+buf.toString());
    return (buf.toString());  
 
}

         
         

private boolean shadockError () {
 // en homage à leur infini pompage   
 //  DEBUG(45414,"Sgadock option ficier="+optionFichier); 
     
     if (appendFileSmartError(FICHIERXY,FICHIERYX,resumeTout)) {
         ABEND (561212,"appndSmartFile return error pout "+FICHIERYX);
         return true;
     } 
     if (deleteError(FICHIERXY)) {
         ABEND (561213,"delete return error pout "+FICHIERXY);
         return true;
     }
     if (renameError(FICHIERYX,stamp+extxy)) {
             ABEND (561214,"rename return error pout "+FICHIERYX);
     return true;
     }
     return false;
}

long nowMs(){
    return(new Date().getTime());
}

 void lock(String t){
     // copier dansla log 
     log(t);
     // copier sur .lck 
     if (lecoup.length()!=0) lecoup.append("\n");
     lecoup.append(t);
 }
 
 boolean lockDisparu(){
 boolean ret=false;
     if (optionFichier)
       if (sizeNoError(FICHIERLOCK).length()==0 ) {
      //   DEBUG(4343,"fichier lock de taille nulle");
         ret=true;
        }
     return ret;
 }
 
 public void principal() {
  // int dejaComptes=0;   
    // initialiser les fichiers log!
  if (optionFichier)
      try{
        if (appendFileSmartError("",FICHIERXY,new StringBuffer(FICHIERXY))) return;
        if (appendFileSmartError("",FICHIERYX,new StringBuffer(FICHIERYX))) return;

       }catch(Exception e){
         ERROR(54441,"en initial shadock ",e);
      }
  attempt=0; 
    
  try{    //po3   
    for (pointsFaits=1;pointsFaits<=iterations;++pointsFaits) {
//     
 
    DEBUG(454512,"LoGsm va faire le point: "+pointsFaits);    
     emettreCarConfig=false;
     
 
        // aux tours suivants, attendre
        if (pointsFaits != 1)   waitMilli(1,nextMilli-nowMs());

        if (lockDisparu() ){
             lock("Fin forcée par suppression du fichier .lck");
             iterations=0;  // forcera l'émission
             // et ne meme pas faire le prochain point
             optionNoTrafic=true;
             optionGps=false;
         }
 
        nowMilli=nowMs() ;  // noter time début itération
//        if (startMilli==-1)startMilli=nowMilli;
        nextMilli=nowMilli+periodePointS*1000;
        //     
       ++attempt;
       trouve=""; //passera à N ou T
// test si il y a une limite au nb de open!         

// si en mode usePim, relire la configPim à chaque tour
// à voir surveiller configPim pendant wait       
 String nc=null;
       if (usePim) {
              DEBUG(3232,"PimModifi reload");
              nc= configPIM();
              if (!nc.equals(configPrev))  if (decodeConfigError("ConfigPimModifiée"))return;
       }
        
     lecoup.delete(0, lecoup.length());  
     urlNext=AMORCE;
    //      DEBUG(012121,"AMORCE"+pointsFaits+"/"+iterations);
   long startTraficInterrogation=nowMs();
   lat="";
   lon="";
   if (!optionNoTrafic){ 
      for (int limite=0;(limite<NBMAXREDIR) && !urlNext.equals("") ;++limite){    // récursion redirection sur site orange
      //      po3f=7;
           try{ //poe
                // appel  sur redirection (comme si recursif) 
             lat="";
             lon="";
             // DEBUG(17365,pointsFaits+" va faire: "+urlNext);
    if (afficherFirst ) {
           ECRAN("première localisation","en cours");
           afficherFirst=false;
       }
                getUrlAndFollow(optionDump,urlNext);
             // si erreur laisser l'écran tel quel
             if (ABANDON) return;
           } catch (Exception poe) {       // try getUrlFollow
  
              lastMailRc="Main:catch";
              ECRAN ("CATCH DANS main erreur dans getUrlAndFollow",urlNext);
              ABEND(434,"exception dans getUrlAndFollowurl cath dans principal (1)",poe);
              return;
           }   // catch poe
            // garbage collector
           java.lang.Runtime.getRuntime().gc();
    
   
      }  // fin de la boucle for limite ou urlNext=""
   
      lock("LOC: "+pointsFaits+" "+lat+"*"+lon+" ["+(nowMs()-startTraficInterrogation)/1000+"] "+date(DATECOURTE));  // éventuellement écrit LOC: !c'est tout
       } // pas X
 
     lock("FREEMEMORY: "+ java.lang.Runtime.getRuntime().freeMemory());
     
     String t2= System.getProperty("com.nokia.mid.batterylevel");
     if (t2!=null)lock("TANK:"+t2);
 
     
     String loc179="";   // pour écran à passer en globale

     
    if (optionBluetooth) {
     //   DEBUG(18731,"va faire bt");
        btSearch();
     //   DEBUG(18732,"fini bt");
        
    }
     
     if (optionGps){
            try {    //po4
              loc179=jsr179();    
            }catch (Exception po4){
              ERROR (1107,"en cours Jsr1979",po4);
            }
            lock("GPS/NET: "+pointsFaits+" "+loc179+" "+date(DATECOURTE));
     }  // if option 179
     
     // sauvegarde sur fichier
        // message de fin de course!  
     
       // faut-il une transaction d'émission maintenant ?
         
        boolean emettreCarModulo=(0==pointsFaits%nbGroupage);
        // ne pas oublier le dernier
    //    lock("ConfigRetardModuloFini\n"+emettreCarConfig+emissionHtmlEnRetard+emettreCarModulo+(pointsFaits>=iterations));
        boolean emettreNow= emettreCarConfig || emissionHtmlEnRetard  || emettreCarModulo || 
                       (pointsFaits>=iterations) || optionFirst;
        optionFirst=false;
        //
        if ( internetNow() && emettreNow ) {
              
              lock("EMISSION: "+date(DATECOURTE)+"_"+pointsFaits+"?>="+iterations);
              
              if ( pointsFaits<iterations) {
                           lock("NEXT Point:"+(nextMilli-nowMs())/1000+"\", Upload (approx): "+
                      (nbGroupage*periodePointS)/60 + "\'");
              }else {
                  log("C'est fini...");
              }
        // uoload des resultats du groupe   
              try{  // po5
                uploadResults ("R","",resumeTout.toString());  
              }catch(Exception po5){
                 ABEND (1105, "Exception au cours de uploadResults ",po5);
                 return;
              } // catch po5

// mettre un lessage si config modif
       //  DEBUG(5689,"Now shadock");     
         if (optionFichier)  try{
                 if (shadockError()) {
                     ABEND(5689,"shadockError a voir");    
                     
                     return;
                 }
            }catch(Exception e){
             ABEND (54441,"en shadock ",e);
             return;
            }
       
          if(uploadDemandeEtReussi())   emissionHtmlEnRetard=false;   
  
          if (optionRaz){
                   if(uploadDemandeEtReussi()){
                      logClear();
                      log("Suite.........\n");
                      log("RAZ: "+date(DATECOURTE)+"_"+pointsFaits+">="+iterations);
                      log("NUMERO: "+sessionID);
                      log("CONFIGPREV:"+configPrev); 
                   }else{
                      log ("pas efface cause erreur emission "); // option RAZ
                   } //REUSSI
          } // raz   
    //    } // Internet and co
       // garbage collector
       java.lang.Runtime.getRuntime().gc();
       
        // afficher le nb de secondes avant prochaine transaction
        long patience=(pointsFaits-nbGroupage*(pointsFaits / nbGroupage))-nbGroupage;
        if ((pointsFaits-patience)>iterations) patience=pointsFaits-iterations;
  
 // pour ecran
  String locgps="";
        if (optionGps && (jsr179Version != null))  locgps="\nGPS:"+loc179;
  
        
        ECRAN (pointsFaits+"/"+iterations+"("+locSucces+")"+patience+" "+trouve+" = ",
                "lat="+lat+"\nlon="+lon+locgps);   
    
        //   DEBUG(012121,"Ecran fait"+pointsFaits+"/"+iterations);
    if  (gapSecondes>0){
         ECRAN("départ différé","attente de "+gapSecondes);
         lock("Début_attente:"+date(DATECOURTE));
         waitMilli(4,gapSecondes*1000);
         lock("FIN_Attente:"+date(DATECOURTE));
         gapSecondes=0;
    }  //gapSecondes  
 
  if (optionFichier)  if (appendFileSmartError("",FICHIERLOCK,lecoup)) return;

      }  // fin de boucle sur for globIter iter 
    }
    pointsFaits--;  // montrer la dernière et pas la suivante!
 
  } catch (Exception po3){    
        ABEND(98765,"po3 Exception dans principal",po3);
        return;
     } // catch try po3
 
    
 }
 
 public boolean uploadDemandeEtReussi(){
     return ((optionInternetMax||optionInternetNuit) &&    // une sauvegarde demande
              // si mail, mail réussi
             (!optionInternetMax || uploadByPostReussi) && //
             (!optionInternetNuit || uploadByPostReussi ));
 }
        
 public void run() {
    // run est exécuté à l'appui sur une touche
    // actuellement jamais!
     
    ERROR (102,"execution de run "+currentCommand.toString());
        
    if (currentCommand == exitCommand) {
        log("FIN: au clavier");
        newDisplay(0,"fin","finale");
        ERROR(9876,"Exit command)");
        destroyApp(false);
        notifyDestroyed();
    } else {
        ERROR (95,"autre cas");
    }  // currentcommand

    synchronized (this) {
            // signal that another command can be processed
        commandThread = null;
    } 
               
        
}// public void run

} // public class HttpT

